Hi fellow gophers
The following code compiles
package main
import (
"fmt"
)
func main() {
mymap := map[string]int{"a": 1, "b": 2}
for k, v := range mymap {
k, v := k, v
fmt.Printf("k %s, v: %d\n", k, v)
}
}
while this one doesn't.
package main
import (
"fmt"
)
func main() {
a := 1
b := 2
a, b := a, b
fmt.Printf("a %d, b: %d\n", a, b)
}
I looked at the language spec and for the ':=' (the "walrus operator") in
the "Short variable declarations"[0] section the spec says the following.
"Unlike regular variable declarations, a short variable declaration
may redeclare variables provided they were originally declared earlier
in the same block (or the parameter lists if the block is the function
body) with the same type, and at least one of the non-blank variables is
new. As a consequence, redeclaration can only appear in a multi-variable
short declaration."
This explains why the second example doesn't compile since none of the
variables in the second short variable declaration is new.
The same is true for the first example however and this one compiles
just fine (even when using a short variable declaration on only one
variable like in 'k := k' which shouldn't be allowed either according
to this quote).
The only explanation for this that I could come up with after being asked
about this case is that the variables declared in the range clause are
a special case, the so called "iteration variables" according to the
"For statements" section[1]. The spec does not mention this but for
these "iteration variables" the rules for the regular short variable
declaration don't seem to uply. If that is indeed the case, I wonder if
the spec shouldn't be updated to reflect this.
Is this really the case or am I missing something?
Cheers,
Silvan
[0]
https://golang.org/ref/spec#Short_variable_declarations
[1]
https://golang.org/ref/spec#For_statements