Zero Values
In Go, a "zero value" is automatically assigned to a variable when it is declared, based on its type. This is one of Go's safety features that prevents bugs caused by forgetting to initialize variables.
Syntax list
| Type | Zero value | Description |
|---|---|---|
| int, int8, int16, int32, int64 | 0 | The zero value for all integer types is 0. |
| uint, uint8 (byte), uint16, uint32, uint64 | 0 | The zero value for all unsigned integer types is also 0. |
| float32, float64 | 0.0 | The zero value for floating-point types is 0.0. |
| complex64, complex128 | 0+0i | The zero value for complex types is 0 for both the real and imaginary parts. |
| string | "" | The zero value for strings is an empty string. |
| bool | false | The zero value for booleans is false. |
| pointer (*T) | nil | The zero value for pointers is nil. |
| slice ([]T) | nil | A nil slice has a length of 0, and you can use append on it. |
| map (map[K]V) | nil | Writing to a nil map causes a panic. |
| channel (chan T) | nil | Sending to or receiving from a nil channel blocks forever. |
| function (func) | nil | The zero value for function types is nil. |
| interface | nil | The zero value for interfaces is nil. |
| struct | each field's zero value | All fields of a struct are initialized to their respective zero values. |
| array ([N]T) | each element's zero value | All elements of an array are initialized to the zero value of their type. |
Sample code
package main
import "fmt"
type Person struct {
Name string
Age int
Active bool
}
func main() {
// Zero values for basic types
var n int
var f float64
var s string
var b bool
fmt.Printf("int: %d, float64: %f, string: %q, bool: %v\n", n, f, s, b)
// Zero values for pointer, slice, and map
var p *int
var sl []int
var m map[string]int
fmt.Println(p, sl, m) // <nil> [] map[]
fmt.Println(p == nil, sl == nil, m == nil) // true true true
// Appending to a nil slice is safe
sl = append(sl, 1, 2, 3)
fmt.Println(sl) // [1 2 3]
// Zero value for a struct
var person Person
fmt.Println(person) // { 0 false}
// Using zero values for condition checks
if person.Name == "" {
fmt.Println("Name is not set")
}
}
Overview
Thanks to zero values, Go lets you safely use uninitialized variables. For example, a counter variable has a zero value of 0, so you can increment it immediately after declaration without any issues.
A nil slice and an empty slice ([]int{}) both have a len() of 0, but they differ in whether they are nil. Writing to a nil map causes a panic, so always initialize a map before using it.
Designing with zero values in mind is a Go idiom known as the "useful zero value." When structuring a struct so that its zero-value state represents a meaningful initial state, you can keep your code concise.
If you find any errors or copyright issues, please contact us.