Home >Backend Development >Golang >Why Can\'t I Declare a Typed Variable in a Go For Loop\'s Initialization Statement?
Variable Declaration in the Initialization Statement of a For Loop
In Go, the syntax for a for loop allows declaring a variable in the initialization statement. However, this declaration must follow a specific format.
The question arises as to why a variable cannot be declared with a specific type in the initialization statement, such as for var i int64 = 0; i < 10; i {}. Instead, the code requires a separate variable declaration (var i int64) followed by an assignment statement (i = 0).
The language specification for the for loop explains that the init statement can only be a short variable declaration, which is an assignment of the form i := 0. It cannot be a full variable declaration using var.
This restriction likely stems from the desire for language simplicity. By limiting the initialization statement to a short variable declaration, the syntax becomes more concise and less confusing.
However, it is worth noting that there is a workaround to declare a variable with a specific type in the initialization statement. This can be done using an explicit type conversion:
for i := int64(0); i < 10; i++ { // i here is of type int64 }
In this example, the variable i is explicitly cast to type int64 in the initialization statement.
The above is the detailed content of Why Can\'t I Declare a Typed Variable in a Go For Loop\'s Initialization Statement?. For more information, please follow other related articles on the PHP Chinese website!