Zero values of slices and maps

September 29, 2023

Composite literals

Note that the zero value for a slice or map type is not the same as an initialized but empty value of the same type.

Let’s look at examples so we can understand exactly what is being stated here.

Recall that when you declare a variable of a given type, the default value is the zero value for the type:

var s1 []string       // Zero value for slice
var m1 map[string]int // Zero value for map

What the spec is telling us is that the zero value of a slice or map is not the same as an initialized, but empty, slice or map:

var s2 = []string{}       // Initialized, empty slice
var m2 = map[string]int{} // Initialized, empty map

Consequently, taking the address of an empty slice or map composite literal does not have the same effect as allocating a new slice or map value with new.

p1 := &[]int{}    // p1 points to an initialized, empty slice with value []int{} and length 0
p2 := new([]int)  // p2 points to an uninitialized slice with value nil and length 0

Beyond this difference called out in the spec, there is a further restriction when dealing with uninitialized maps: While you can (attempt to) read from them, you cannot add keys to them!

var m1 map[string]int
fmt.Println(m1["x"]) // Valid: prints 0, the zero value of the key type
m1["x"] = 3          // panic: assignment to entry in nil map

Quotes from The Go Programming Language Specification Version of August 2, 2023

Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .