Sobes.tech
Senior

Is it possible to add an element to a nil slice?

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 0. Despite this, you can add an element to a nil slice using the append function. When adding an element, Go automatically allocates a new array and returns a new slice containing the added element.

Example:

var s []int // nil slice
s = append(s, 10)
fmt.Println(s) // Output: [10]

Thus, a nil slice can be considered as an empty slice, and append works correctly with it.

Is it possible to add an element to a nil slice… - sobes.tech