Search⌘ K
AI Features

Variables

Explore the fundamentals of Go variables, data types, and constants, including the impact of unused variables on compilation. Understand variable shadowing and learn how to write cleaner Go programs by following language-specific rules.

We'll cover the following...

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:

Go (1.16.5)
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:

Go (1.16.5)
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:

Go (1.16.5)
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
}