Sobes.tech
Junior — Middle

What happens if you create a slice with a null value and what operations are permissible with it?

sobes.tech AI

Answer from AI

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 include:

  • Getting length and capacity (len(slice) == 0, cap(slice) == 0)
  • Iterating over the slice (the loop will not execute)
  • 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

Accessing elements by index is not allowed, as the slice is empty and will cause a panic.

What happens if you create a slice with a null value… - sobes.tech