Junior — Middle
What is the difference between a map with a null value and a slice containing a null value?
sobes.tech AI
Answer from AI
In Go, a map with a zero value is an uninitialized map and is equal to nil. Attempting to write to such a map will cause a panic.
A slice with a zero value is a nil slice, which does not point to an array and has length and capacity 0. It can be safely used, for example, for reading or passing to functions.
Key differences:
- map == nil means the map is uninitialized and cannot accept elements.
- slice == nil means the slice is empty and does not point to an array, but it can be used for reading (it will be empty) and passing.
Example:
var m map[string]int // m == nil
// m["key"] = 1 // panic: assignment to entry in nil map
var s []int // s == nil
fmt.Println(len(s)) // 0
s = append(s, 1) // now the slice is initialized
Thus, a nil map is not suitable for writing, while a nil slice is safe for reading and extension.