Junior — Middle
Mis vahe on kaardil nullväärtusega ja viilul, mis sisaldab nullväärtust?
sobes.tech AI
Vastus AI-lt
In Go, a map with a zero value is a map that has not been initialized 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 not initialized and cannot accept elements.
- slice == nil means the slice is empty and does not point to an array, but can be used for reading (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
Therefore, a nil map is not suitable for writing, and a nil slice is safe for reading and extension.