In the provided Go code:
package main import "fmt" func main() { myArray :=[...]int{12,14,26} ; fmt.Println(myArray) myArray :=[...]int{11,12,14} //error on this line fmt.Println(myArray) ; }
The first statement correctly declares and initializes the myArray variable using the ":=" notation. However, in the second statement, attempts to reassign values to the existing myArray variable using ":=" again.
In Go, ":=" is a shorthand for declaring and initializing a new variable. It assigns the value on the right-hand side to the identifier on the left-hand side. In other words, in the first statement, ":=" is valid because it introduces a new variable myArray and assigns it the list of integers.
However, when re-assigning values to an existing variable, ":=" cannot be used. Instead, the regular assignment operator "=" should be used as shown below:
myArray = [...]int{11,12,14}
By removing the colon (":") from the second statement, the code correctly assigns new values to the myArray variable using the "=" operator. The corrected code is:
package main import "fmt" func main() { myArray :=[...]int{12,14,26} ; fmt.Println(myArray) myArray = [...]int{11,12,14} //correct assignment fmt.Println(myArray) ; }
The above is the detailed content of Why is my Go code throwing an 'Error: 'no new variables on left side of :=''?. For more information, please follow other related articles on the PHP Chinese website!