Home > Backend Development > Golang > Why am I getting the 'no new variables on left side of :=' error in my Go code?

Why am I getting the 'no new variables on left side of :=' error in my Go code?

Patricia Arquette
Release: 2024-11-25 01:34:10
Original
418 people have browsed it

Why am I getting the

Error in Code: "no new variables on left side of :="

In the Go programming language, the error "no new variables on left side of :=" occurs when you try to reassign values ​​to an existing variable using the short declaration syntax.

This error is encountered in the following code snippet:

package main

import "fmt"

func main() {
    myArray  :=[...]int{12,14,26}  // Short declaration and assignment
    fmt.Println(myArray)

    myArray  :=[...]int{11,12,14} // Error on this line
    fmt.Println(myArray)
}
Copy after login

Reason:

In Go, the colon (:) is used for short declarations and assignments. This is the syntax used when declaring and assigning a variable for the first time, as shown in the first line of the example.

However, on the following line, you try to assign again to the existing variable myArray using a colon (:). This causes an error because the new variable is not declared on the left side.

Solution:

To fix this error, remove the colon (:) from the second statement:

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

Now, The variable myArray will be reassigned without error.

The above is the detailed content of Why am I getting the 'no new variables on left side of :=' error in my Go code?. 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