Nil Slices

Learn about nil slices in Go.

Nil slices

Slices don’t have to be checked for nil values and don’t always need to be initialized. Functions such as len, cap, and append work fine on a nil slice:

Press + to interact
package main
import "fmt"
func main() {
var s []int // nil slice
fmt.Println(s, len(s), cap(s)) // [] 0 0
s = append(s, 1)
fmt.Println(s, len(s), cap(s)) // [1] 1 1
}

An empty slice is not the same thing as a nil slice:

Press + to interact
package main
import "fmt"
func main() {
var s []int // this is a nil slice
s2 := []int{} // this is an empty slice
// looks like the same thing here:
fmt.Println(s, len(s), cap(s)) // [] 0 0
fmt.Println(s2, len(s2), cap(s2)) // [] 0 0
// but s2 is actually allocated somewhere
fmt.Printf("%p %p", s, s2) // 0x0 0x65ca90(any address)
}

If you care very ...

Get hands-on with 1400+ tech skills courses.