Zero value of slice
suggest changeZero value of a slice is nil
.
A nil
slice has length and capacity of 0.
A nil
slice has no underlying array.
A non-nil slice can also have length and capacity of 0, like []int{}
or make([]int, 5)[5:]
.
Any type that has nil
values can be converted to nil
slice:
s := []int(nil)
fmt.Printf("s: %#v\n", s)
To test whether a slice is empty, check if len(s)
is 0:
s := []int(nil)
if len(s) == 0 {
fmt.Printf("s is empty: %#v\n", s)
}
var s2 []int
if len(s2) == 0 {
fmt.Printf("s2 is empty: %#v\n", s2)
}
s3 := make([]int, 0)
if len(s2) == 0 {
fmt.Printf("s3 is empty: %#v\n", s3)
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents