Home > Backend Development > Golang > Why does Go throw an 'no new variables on left side of :=' error when re-assigning values to an array?

Why does Go throw an 'no new variables on left side of :=' error when re-assigning values to an array?

Linda Hamilton
Release: 2024-11-13 08:34:02
Original
369 people have browsed it

Why does Go throw an

Reassignment of Array: "no new variables on left side of :="

In the provided Go code snippet, an error is encountered when attempting to reassign values to the 'myArray' variable on the second line:

myArray := [...]int{12, 14, 26}
myArray := [...]int{11, 12, 14} // error: no new variables on left side of :=
Copy after login

This error stems from the use of := in the second assignment. When you declare a variable using := for the first time, such as in the first statement, it creates a new variable and assigns it a value. However, when you try to reassign a value to an existing variable using :=, it treats it as an attempt to declare a new variable, which is not allowed.

The solution is to remove the := from the second assignment line and instead use the standard assignment operator =:

myArray = [...]int{11, 12, 14}
Copy after login

The : syntax is specifically intended for the initial declaration and assignment of a variable. After the variable has been declared, reassignment should be done using the = operator.

The above is the detailed content of Why does Go throw an 'no new variables on left side of :=' error when re-assigning values to an array?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template