Vitamin C

Go Zero values


One thing to note - types that have a non-nil zero value like strings, ints, floats, bools and structs can't be set to nil.

Basic Zero Values

Variables in Go are always initialized whether you give them a starting value or not. Each type, including custom types, has a zero value they are set to if not given a value.

var myString string      // "" - an empty string
var myInt int64          // 0 - applies to all types of int and uint
var myFloat float64      // 0.0 - applies to all types of float and complex
var myBool bool          // false
var myPointer *string    // nil
var myInter interface{}  // nil

This also applies to maps, slices, channels and function types. These types will initialize to nil. In arrays, each element is initialized to the zero value of its respective type.

More Complex Zero Values

In slices the zero value is an empty slice.

var myIntSlice []int    // [] - an empty slice

Use make to create a slice populated with values, any values created in the slice are set to the zero value of the type of the slice. For instance:

myIntSlice := make([]int, 5)    // [0, 0, 0, 0, 0] - a slice with 5 zeroes
// Prints 0

In this example, myIntSlice is a int slice that contains 5 elements which are all 0 because that's the zero value for the type int.

You can also create a slice with new, this will create a pointer to a slice.

myIntSlice := new([]int)        // &[] - a pointer to an empty slice
*myIntSlice = make([]int, 5)    // [0, 0, 0, 0, 0] - a slice with 5 zeroes
// Prints 0

Note: Slice pointers don't support indexing so you can't access the values using myIntSlice[3], instead you need to do it like (*myIntSlice)[3].

Struct Zero Values

When creating a struct without initializing it, each field of the struct is initialized to its respective zero value.

type ZeroStruct struct {
    myString string
    myInt    int64
    myBool   bool

func main() {
    var myZero = ZeroStruct{}
    fmt.Printf("Zero values are: %q, %d, %t\n", myZero.myString, myZero.myInt, myZero.myBool)
    // Prints "Zero values are: "", 0, false"

Array Zero Values

As per the Go blog:

Arrays do not need to be initialized explicitly; the zero value of an array is a ready-to-use array whose elements are themselves zeroed

For example, myIntArray is initialized with the zero value of int, which is 0:

var myIntArray [5]int     // an array of five 0's: [0, 0, 0, 0, 0]

Got any Go Question?