Zero Values
In this page:
Zero Values for Basic Types
When you declare a variable with var and no initializer, Go automatically sets it to that type's zero value: numeric types get 0, bool gets false, and string gets "" (empty string). This guarantees every variable starts in a predictable, safe state.
Example: Zero Values for Basic Types
package main
import "fmt"
func main() {
var count int
var price float64
var active bool
var label string
fmt.Println(count, price, active, label)
}
Login to try C/C++/Java/PHP code in the editor
Zero Values for Structs
A struct's zero value is a struct where every field is set to its own type's zero value -- so a zero-value Person struct has an empty Name and a 0 Age, ready to use without a panic.
Example: Zero Values for Structs
package main
import "fmt"
type Person struct {
Name string
Age int
}
func main() {
var p Person
fmt.Println("name:", p.Name, "age:", p.Age)
}
Login to try C/C++/Java/PHP code in the editor
nil as a Zero Value
Reference-like types -- pointers, slices, maps, channels, functions, and interfaces -- have nil as their zero value, representing 'not yet pointing at anything'. Understanding which types zero to nil versus a concrete empty value avoids a whole class of beginner bugs.
Note: Reading from a nil map or nil slice is safe; only writing to a nil map panics.
Example: nil as a Zero Value
package main
import "fmt"
func main() {
var s []int
var m map[string]int
fmt.Println("nil slice:", s, "is nil:", s == nil)
fmt.Println("nil map:", m, "is nil:", m == nil)
}
Login to try C/C++/Java/PHP code in the editor
Why Zero Values Matter
Because every variable is automatically usable from the moment it's declared, Go code can skip a lot of defensive null-checking that other languages require -- an int is always a real number, never a special undefined marker.
Example: Why Zero Values Matter
package main
import "fmt"
func main() {
var total int
amounts := []int{10, 20, 30}
for _, a := range amounts {
total += a // total starts safely at 0
}
fmt.Println("total:", total)
}
Login to try C/C++/Java/PHP code in the editor
- Assuming an uninitialized variable is nil/undefined for all types, when numeric and boolean types actually get 0 and false, not nil.
- Forgetting that a zero-value struct still has usable (zeroed) fields, rather than being an error to access.
- Treating a zero-value slice or map the same -- a nil slice is safe to append to, but a nil map panics on write.
- Every type in Go has a well-defined zero value used when a variable is declared without an initializer.
- Numeric types default to 0, bool defaults to false, and string defaults to an empty string.
- Pointers, slices, maps, channels, funcs, and interfaces default to nil.
- Zero values mean Go variables are always in a valid, predictable state -- never undefined.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: