10

Yet another beginner's question for golang:

I can write:

for i := 0; i < 10; i++ {}

But if I want i to be of a specific type as int64, apparently I am not supposed to write:

for var i int64 = 0; i < 10; i++ {}

I am surprised that I cannot specify a type in the start statement of the for loop. I need to write something like this:

var i int64
for i = 0; i < 10; i++ {}

Am I missing a point here? Is there any explanation for it?

2 Answers 2

14

The language specification for a for loop states that: The init statement may be a short variable declaration, which is assignment of the form i := 0 but not a declaration of the form var i = 0. As for the reason behind this - I'm guessing language simplicity. See here: http://golang.org/ref/spec#For_statements

BTW You can do something like this:

for  i := int64(0); i < 10; i++ {
   // i here is of type int64
}
Sign up to request clarification or add additional context in comments.

Comments

2

According to the Go Language Specification: For statements if you choose the form of the ForClause:

ForClause = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] .

The definition of the InitStmt:

SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | Assignment
               | ShortVarDecl .

So as you can see if you want to create a new variable in the for statement, it can only be a Short Variable declarations, like this:

for i := 0; i < 10; i++ {}

The Short variable declaration can be used to declare new variables of any types, and the types of the variables will be the types of of the corresponding initialization values on the right side.

Let's examine it a little bit closer:

i := 0

On the right side there is 0: it is an untyped numeric constant. Note that untyped consants in Go have a default type which is used if a type is needed, like this case. The default type of an untyped integer consant is int hence the variable i will have int type.

If you want it to have the type int64, use an expression which has int64 type, like these:

for i := int64(0); i < 10; i++ {} // Explicit type conversion

const ZERO int64 = 0
for i := ZERO; i < 10; i++ {}     // Typed constant

var vzero int64

for i: = vzero; i < 10; i++ {}    // Expression of type int64

Or create the i variable before the for statement using var declaration:

var i int64
for i = 0; i < 10; i++ {}         // Variable is declared before for using "var"

Note that this last example does not use the Short Variable declaration just a simple assignment.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.