Sobes.tech
Junior — Middle

What actions are permissible when working with a slice in Go if it was not explicitly initialized?

sobes.tech AI

Answer from AI

In Go, if a slice has not been explicitly initialized (i.e., it has the value nil), you can perform the following actions:

  • Check for nil (for example, if slice == nil), which is useful for determining whether the slice has been initialized.
  • Get the length and capacity using len(slice) and cap(slice). For a nil slice, both length and capacity are 0.
  • Use the append operator to add elements. append will automatically create a new slice with allocated memory if the original slice is nil.

However, you cannot access elements of the slice by index if it is nil or empty, as this will cause a panic.

Example:

var s []int // s == nil
fmt.Println(s == nil) // true
fmt.Println(len(s))   // 0
s = append(s, 1)      // now s is initialized and contains [1]