Home > Backend Development > Golang > Why Am I Getting a 'no new variables on left side of :=' Error in Go?

Why Am I Getting a 'no new variables on left side of :=' Error in Go?

Patricia Arquette
Release: 2024-11-14 13:37:02
Original
945 people have browsed it

Why Am I Getting a

Rewriting Code to Avoid "no new variables on left side of :=" Error

In this code, we witness an issue in the second statement, resulting in an error message "no new variables on left side of :=":

package main

import "fmt"

func main() {

    myArray  :=[...]int{12,14,26}  // Correct: Short declaration with assignment using ":"
    fmt.Println(myArray)

    myArray  :=[...]int{11,12,14} // Error: Second assignment with ":" attempts to create a new variable
    fmt.Println(myArray) ;

}
Copy after login

To address this issue, it is crucial to comprehend that the colon symbol (:) is specifically employed during the initial declaration and assignment of a variable. In this case, the first statement is legitimate:

myArray  :=[...]int{12,14,26}   // Declaring and assigning an array with ":"
Copy after login

However, when re-assigning values to an existing variable, as attempted in the second statement, the colon should be removed:

myArray = [...]int{11,12,14}   // Re-assignment without ":"
Copy after login

In summary, remember to utilize the colon (:) only during the initial declaration and assignment of a variable. For subsequent re-assignments, rely on the equal sign (=). This modification would rectify the code and resolve the error.

The above is the detailed content of Why Am I Getting a 'no new variables on left side of :=' Error in Go?. 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