Junior — Middle
Mis juhtub, kui luua nullväärtusega lõik ja millised toimingud on sellega lubatud?
sobes.tech AI
Vastus AI-lt
In Go, a slice with a zero value is a nil slice. It does not point to any array and has length and capacity equal to zero.
Operations allowed with such a slice:
- Getting length and capacity (
len(slice) == 0,cap(slice) == 0) - Iterating over the slice (the loop simply will not run)
- Adding elements via
append, which creates a new slice with allocated memory
Example:
var s []int // nil slice
fmt.Println(s == nil) // true
fmt.Println(len(s)) // 0
s = append(s, 1) // now s is not nil, contains one element
It is not possible to access elements by index, as the slice is empty and this will cause a panic.