Junior — Middle
What does a zero value for a slice mean in a programming language?
sobes.tech AI
Answer from AI
In Go language, a slice is a dynamic array that contains a reference to an array, along with its length and capacity.
The zero value of a slice is nil. Such a slice does not point to any array, and its length and capacity are zero.
Features of a zero slice:
- It can be checked with
slice == nil. - Attempting to access elements of such a slice will cause a panic.
- It can be used as an empty slice, for example, to indicate the absence of data.
Example:
var s []int // s == nil
fmt.Println(s == nil) // true
fmt.Println(len(s)) // 0
fmt.Println(cap(s)) // 0
// You can safely initialize an empty slice:
s = []int{}
fmt.Println(s == nil) // false
fmt.Println(len(s)) // 0
Thus, the zero value of a slice is nil, which is different from an empty but non-nil slice.