Zero value of slice

suggest change

Zero 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:

main.go

	s := []int(nil)
	fmt.Printf("s: %#v\n", s)

Output:

s: []int(nil)

To test whether a slice is empty, check if len(s) is 0:

main.go

	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)
	}

Output:

s  is empty: []int(nil)
s2 is empty: []int(nil)
s3 is empty: []int{}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents