Reassigning Values to Existing Variables in Go
In Go, reassignment to an existing variable necessitates the removal of the colon (:) to avoid the "no new variables on left side of :=" error. This error occurs when a colon is used in a subsequent statement that assigns a new value to an already declared variable.
For example:
Consider the following code snippet:
package main import "fmt" func main() { myArray := [...]int{12, 14, 26} fmt.Println(myArray) myArray := [...]int{11, 12, 14} // Error: no new variables on left side of := fmt.Println(myArray) }
The first statement (myArray := [...]int{12, 14, 26}) declares myArray as an array of integers and assigns it the specified values. However, the subsequent statement, myArray := [...]int{11, 12, 14}, attempts to redeclare myArray and reassign it new values, which is not valid.
To rectify this issue, remove the colon (:) from the second statement:
myArray = [...]int{11, 12, 14}
Now, the code should run without encountering the "no new variables on left side of :=" error.
The colon (:) is used in the initial declaration of a variable using short variable declaration syntax. Once a variable has been declared, reassignment should be done without the colon.
The above is the detailed content of How to Reassign Values to Existing Variables in Go?. For more information, please follow other related articles on the PHP Chinese website!