Sobes.tech
Senior

Can we add an element to a nil slice?

sobes.tech AI

Answer from AI

Yes, in Go, a nil slice can have an element added using the append function. When adding an element to a nil slice, Go automatically allocates memory and creates a new slice with that element.

Example:

var s []int // s == nil
s = append(s, 42) // now s contains one element: 42
fmt.Println(s) // Output: [42]

Thus, a nil slice behaves like an empty slice when adding elements, and this is safe and correct.

Can we add an element to a nil slice? — Golang - sobes.tech