A common question for Go beginners is regarding variable declaration in the initialization statement of a for loop. While you can write a loop like for i := 0; i < 10; i , specifying a type explicitly within the initialization statement seems impossible.
Attempting to specify a type directly within the initialization, such as for var i int64 = 0; i < 10; i , will result in an error. Contrary to expectations, you must declare the variable outside of the loop initialization and assign it within:
var i int64 for i = 0; i < 10; i++ { // i here is of type int64 }
The language specification for a for loop states that the initialization statement may be a short variable declaration, which assigns a value (e.g., i := 0) but not a full variable declaration (var i = 0).
The reason behind this is likely to maintain language simplicity. However, it's worth noting that you can achieve a similar result by using a type conversion:
for i := int64(0); i < 10; i++ { // i here is of type int64 }
The above is the detailed content of Can I Explicitly Type a Variable in a Go For Loop\'s Initialization Statement?. For more information, please follow other related articles on the PHP Chinese website!