Variables
A variable’s value is retrieved by referring to the variable in an expression; it is the most recent value assigned to the variable. If a variable has not yet been assigned a value, its value is the zero value for its type.
The zero value is covered in greater detail near the end of the spec, but it’s an important concept, so let’s discuss it a bit here.
In contrast to some languages, where declaring a new variable results in an “undefined” value, Go is explicit that every declared variable is immediately usable, by declaring that it is set to its “zero value”.
This generally means the value 0, or the closest aproximation appropriate for the type. The zero value of numeric types is therefore 0
(or 0.0
for floats), the zero value for a string is the empty string. The zero value for a slice is an empty slice, etc.
It’s thanks to this zero value concept that the following code is predictable, and neither crashes, nor produces non-deterministic output:
var x int // x is initialized to the zero value for an integer, which is 0
var y string // y is set to the empty string, ""
fmt.Println(x, y) // Printing these variables is perfectly valid, though
// perhaps a bit boring.
Quotes from The Go Programming Language Specification, Version of January 19, 2023