Sobes.tech
Junior — Middle

What built-in functions and operations are permissible for a slice that has not yet been initialized?

sobes.tech AI

Answer from AI

In Go, a slice that has not been initialized (i.e., is nil) can be used for the following operations:

  • Checking for nil: if slice == nil {}
  • Getting length and capacity: len(slice) and cap(slice) will return 0
  • You can perform element addition operations using append, for example:
var s []int // nil slice
s = append(s, 1, 2, 3) // now the slice is initialized and contains elements

However, you cannot access elements by index, for example s[0], if the slice is nil or empty — this will cause a panic.

What built-in functions and operations are… - sobes.tech