Sobes.tech
Junior — Middle

What operations are permissible when working with a nil slice in a programming language?

sobes.tech AI

Answer from AI

In Go, a nil slice is a slice that does not point to any array and has a length and capacity of zero. The following operations are permissible:

  • Reading length and capacity: len(nilSlice) == 0, cap(nilSlice) == 0.
  • Adding elements using append, which creates a new slice with allocated memory.
  • Iterating over a nil slice with a for range loop — the loop simply does not execute.

Not allowed:

  • Accessing elements by index, for example nilSlice[0] will cause a panic.

Example:

var s []int // nil slice
fmt.Println(len(s)) // 0
s = append(s, 1)    // now s is not nil
fmt.Println(s)      // [1]