Variables

Learn about variables in Go.

Unused variables

Go programs with unused variables do not compile:

“The presence of an unused variable may indicate a bug […] Go refuses to compile programs with unused variables or imports, trading short-term convenience for long-term build speed and program clarity.”
https://golang.org/doc/faq

Exceptions to that rule are global variables and function arguments:

Press + to interact
package main
var unusedGlobal int // this is ok
func f1(unusedArg int) {// unused function arguments are also ok
// error: a declared but not used
a, b := 1,2
// b is used here, but a is only assigned to, doesn't count as “used”
a = b
}

Short variable declaration

Short variable declarations only work inside functions:

Press + to interact
package main
v1 := 1 // error: non-declaration statement outside function body
var v2 = 2 // this is ok
func main() {
v3 := 3 // this is ok
fmt.Println(v3)
}

They also don’t work when setting field values:

Press + to interact
package main
type myStruct struct {
Field int
}
func main() {
var s myStruct
// error: non-name s.Field on the left side of :=
s.Field := 1
var newVar int
s.Field, newVar = 1, 2 // this is actually ok
}