What's happening here?
package main
import "fmt"
func main() {
myArray :=[...]int{12,14,26} ;
fmt.Println(myArray)
myArray :=[...]int{11,12,14} //error pointing on this line
fmt.Println(myArray) ;
}
It throws an error that says
no new variables on left side of :=
What I was doing was re-assigning values to an already declared variable.
Remove the colon :
from the second statement as you are assigning a new value to existing variable.
myArray = [...]int{11,12,14}
colon :
is used when you perform the short declaration and assignment for the first time as you are doing in your first statement i.e. myArray :=[...]int{12,14,26}
.
There are two types of assignment operators in go :=
and =
. They are semantically equivalent (with respect to assignment) but the first one is also a "short variable declaration" ( http://golang.org/ref/spec#Short_variable_declarations ) which means that in the left we need to have at least a new variable declaration for it to be correct.
You can change the second to a simple assignment statement :=
-> =
or you can use a new variable if that's ok with your algorithm.
myArray :=[...]int{12,14,26}
As stated by the previous commenters, :=
is a type of short-hand and/or the short-form of variable declaration.
So in the statment above you are doing two things.
- You are declaring your variable to be myArray.
- You are assigning an array of integers to the myArray variable.
The second part of your code fails, because what you are doing here:
myArray :=[...]int{11,12,14} //error pointing on this line
Is RE-declaring the existing variable myArray, which already contains integer values.
This works:
myArray = [...]int{11,12,14} //error pointing on this line
Because, it is assigning the integer array to the existing ( pre-declared / initialized ) variable.
As a side note, redeclaration can only appear in a multi-variable short declaration
Quoting from the Language specification:
Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block 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. Redeclaration does not introduce a new variable; it just assigns a new value to the original.
package main
import "fmt"
func main() {
a, b := 1, 2
c, b := 3, 4
fmt.Println(a, b, c)
}
Here is a very good example about redeclaration of variables in golang: https://stackoverflow.com/a/27919847/4418897
来源:https://stackoverflow.com/questions/13329154/no-new-variables-on-left-side-of