Essential Go Basic types  Edit on GitHub      File Issue

Zero values

Variables in Go are always initialized with a known value even if not explicitly assigned in source code.

Each Go type has a zero value.

Variables that are not explicitly initialized (assigned an explicit value) will have a value equal to the zero value for their type.

This is different from C/C++, where variables that are not explicitly assigned have undefined values.

The values of zero type are unsurprising:

typezero value
floating poing numbers0.0
arrayall elements have zero values
structall members set to zero value of their type

Said differently:

var zeroBool bool             // = false
var zeroInt int               // = 0
var zeroF32 float32           // = 0.0
var zeroStr string            // = ""
var zeroPtr *int              // = nil
var zeroSlice []uint32        // = nil
var zeroMap map[string]int    // = nil
var zeroInterface interface{} // = nil
var zeroChan chan bool        // = nil
var zeroArray [5]int          // = [0, 0, 0, 0, 0]
type struc struct {
	a int
	b string
var zeroStruct struc    // = { a: 0, b: ""}
var zeroFunc func(bool) // = nil

fmt.Printf("zeroBool: %v\n", zeroBool)
fmt.Printf("zeroInt: %v\n", zeroInt)
fmt.Printf("zeroF32: %v\n", zeroF32)
fmt.Printf("zeroStr: %#v\n", zeroStr)
fmt.Printf("zeroPtr: %v\n", zeroPtr)
fmt.Printf("zeroSlice: %#v\n", zeroSlice)
fmt.Printf("zeroMap: %#v\n", zeroMap)
fmt.Printf("zeroInterface: %v\n", zeroInterface)
fmt.Printf("zeroChan: %v\n", zeroChan)
fmt.Printf("zeroArray: %v\n", zeroArray)
fmt.Printf("zeroStruct: %#v\n", zeroStruct)
fmt.Printf("zeroFunc: %v\n", zeroFunc)
zeroBool: false
zeroInt: 0
zeroF32: 0
zeroStr: ""
zeroPtr: <nil>
zeroSlice: []uint32(nil)
zeroMap: map[string]int(nil)
zeroInterface: <nil>
zeroChan: <nil>
zeroArray: [0 0 0 0 0]
zeroStruct: main.struc{a:0, b:""}
zeroFunc: <nil>
  ↑ ↓ to navigate     ↵ to select     Esc to close