The Zero Value vs nil Confusion for Slices and Maps

In Go, a slice or map with a zero value is `nil`, which is distinct from an empty but initialized collection and will panic if you attempt to write to it. You must explicitly initialize them with `make` or a literal to use them safely.

The Zero Value vs nil Confusion for Slices and Maps

In Go, a slice or map with a zero value is nil, which is distinct from an empty but initialized collection and will panic if you attempt to write to it. You must explicitly initialize them with make or a literal to use them safely.

package main

func main() {
	// Zero value (nil): panics on write
	var s []int
	// s[0] = 1 // panic: index out of range

	// Initialized (empty but not nil): safe to use
	s = make([]int, 0)
	s = append(s, 1)

	// Same for maps
	var m map[string]int
	// m["key"] = 1 // panic: assignment to entry in nil map

	m = make(map[string]int)
	m["key"] = 1
}