Nil Slices
Learn about nil slices in Go.
We'll cover the following...
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 mainimport "fmt"func main() {var s []int // nil slicefmt.Println(s, len(s), cap(s)) // [] 0 0s = 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 mainimport "fmt"func main() {var s []int // this is a nil slices2 := []int{} // this is an empty slice// looks like the same thing here:fmt.Println(s, len(s), cap(s)) // [] 0 0fmt.Println(s2, len(s2), cap(s2)) // [] 0 0// but s2 is actually allocated somewherefmt.Printf("%p %p", s, s2) // 0x0 0x65ca90(any address)}
If you care very ...