Complete reference for Go built-in constants including true, false, nil, and iota
Go provides several predeclared constants that are available in all packages without import. These constants are fundamental to Go’s type system and control flow.
Predeclared identifier representing the zero value for reference types.Can only be used with: pointer, channel, func, interface, map, or slice types.
Pointers
Slices
Maps
Channels
Interfaces
Functions
var p *int = nilif p == nil { fmt.Println("Pointer is nil")}// Dereferencing nil pointer panics// fmt.Println(*p) // panic: runtime error// Check before dereferencingif p != nil { fmt.Println(*p)}
var s []int = nilif s == nil { fmt.Println("Slice is nil")}// Safe operations on nil slicesfmt.Println(len(s)) // 0fmt.Println(cap(s)) // 0s = append(s, 1) // Creates new slice// Iterating over nil slice is safefor _, v := range s { fmt.Println(v) // Never executes}
var m map[string]int = nilif m == nil { fmt.Println("Map is nil")}// Reading from nil map returns zero valuev := m["key"] // 0v, ok := m["key"] // 0, false// Writing to nil map panics// m["key"] = 42 // panic: assignment to nil map// Must initialize before writingm = make(map[string]int)m["key"] = 42
var ch chan int = nilif ch == nil { fmt.Println("Channel is nil")}// Operations on nil channels block forever// <-ch // Blocks forever// ch <- 1 // Blocks forever// close(ch) // Panics// Must initialize before usech = make(chan int)
var err error = nilif err == nil { fmt.Println("No error")}// Nil interface is different from interface holding nil valuevar p *int = nilvar i interface{} = pfmt.Println(i == nil) // false! Interface holds typed nil
var f func() = nilif f == nil { fmt.Println("Function is nil")}// Calling nil function panics// f() // panic: runtime error// Check before callingif f != nil { f()}
Attempting to use nil values incorrectly can cause runtime panics. Always check for nil before dereferencing pointers, writing to maps, or calling functions.
Starting in Go 1.21, calling panic(nil) causes a run-time error. The GODEBUG setting panicnil=1 can disable this check.
While not predeclared constants, Go’s zero values are important to understand:
Type
Zero Value
bool
false
int, int8, int16, int32, int64
0
uint, uint8, uint16, uint32, uint64, uintptr
0
float32, float64
0.0
complex64, complex128
0+0i
string
"" (empty string)
pointer, function, interface, slice, channel, map
nil
array, struct
All fields/elements set to their zero values
var b bool // falsevar i int // 0var f float64 // 0.0var s string // ""var p *int // nilvar slice []int // nilvar m map[string]int // niltype Point struct { X, Y int}var pt Point // {0, 0}
Go automatically initializes all variables to their zero value. This ensures variables are always in a defined state.