Go中标识符和表达式之间的区别

http://golang.org/ref/spec#RangeClause

RangeClause = ( ExpressionList "=" | IdentifierList ":=" ) "range" Expression .

Trying to understand the range clause and specifically the difference between an identifier and an expression

Thanks.

With the range keyword you can iterate over many things and assign the results while doing so. You can assign to two things:

  • Identifiers (via IdentifierList)
  • Expressions (via ExpressionList)

Identifiers

These are new variables for use in the inner loop. They must obey the rules for identifiers (unicode names, no whitespaces, etc.). If you use these you have to use the := operator between the list an the range keyword.

Example:

for i := range []int{1,2,3} {
    fmt.Println(i)
}

Expressions

You don't necessarily need to declare new variables, you can use existing ones and even have expressions evaluated which return the storage location. A few examples:

Assign to a pointer (Play):

var i = 0

func main() {
    p := &i

    for *p = range []int{1,2,3} {
        fmt.Println(i)
    }
}

Return a pointer and assign it (Play):

var i = 0

func foo() *int {
    return &i
}

func main() {
    for *foo() = range []int{1,2,3} {
        fmt.Println(i)
    }
}