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
Patricia ArquetteOriginal
2024-11-25 01:34:10370browse

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)
}

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}

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!

Statement:
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