View errors by: Date Added Package/Type

no new variables on left side of :=

go build "no new variables on left side of :="

What causes the error?

This error means that you are trying to use Go’s short form variable declaration (a := "some-value") when the variable has already been declared.

The most common cause of this compilation error is when you have a variable declared via short form declaration and then add a new line of code before that line which adds a new declaration. This is much clearer with an example.

Imagine you started out with this code:

func main() {
	err := doStuff()
	if err != nil {
		// handle err
	}
}

And then later you decided that you needed to add a line of code at the very start of your function that also calls a function that returns an error:

func main() {
	n, err := doMoreStuff()
	if err != nil {
		// handle err
	}
	fmt.Println(n)
	err := doStuff()
	if err != nil {
		// handle err
	}
}

At this point your code will start producing the no new variables on left side of := error because err is already declared when we call doStuff(), but we are still using the := short form declaration.

How can I fix it?

To fix this error you simply need to remove the : from the second declaration of the variable.

func main() {
	n, err := doMoreStuff()
	if err != nil {
		// handle err
	}
	fmt.Println(n)
	err = doStuff()
	if err != nil {
		// handle err
	}
}

Another way to help avoid this error, especially with the err variable which is fairly common, is to declare an err variable at the start of your function and to not use the short form declaration for it.

var err error

Created by Jon Calhoun, but you can check out the source and contribute on GitHub