Variables
Learn about variables in Go.
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:
package mainvar unusedGlobal int // this is okfunc f1(unusedArg int) {// unused function arguments are also ok// error: a declared but not useda, 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:
package mainv1 := 1 // error: non-declaration statement outside function bodyvar v2 = 2 // this is okfunc main() {v3 := 3 // this is okfmt.Println(v3)}
They also don’t work when setting field values:
package maintype myStruct struct {Field int}func main() {var s myStruct// error: non-name s.Field on the left side of :=s.Field := 1var newVar ints.Field, newVar = 1, 2 // this is actually ok}