Construct nil and empty slices
Construct nil and empty slices
A slice describes a segment of an underlying array. Unlike an array, its length is not part of its type. []int describes a slice of integers. A nil slice has length and capacity zero; a non-nil empty slice can also have length zero.
package main
import "fmt"
func main() { var a []int b := []int{} c := []int{12, 18} fmt.Println(a == nil, len(a), cap(a)) fmt.Println(b == nil, len(b), cap(b)) fmt.Println(c)}var a []int uses the zero value nil. The literal []int{} creates a non-nil empty slice. Both can be ranged over or appended to; neither has a valid element index. Test emptiness with len rather than nil unless nil itself matters.
Expected output:
true 0 0false 0 0[12 18]Iterate and compare with nil
package main
import "fmt"
func main() { var items []string for _, v := range items { fmt.Println(v) } items = append(items, "tea") fmt.Println(items, items == nil)}Appending to nil is valid. Slices cannot be compared to one another with ==; only comparison to nil is allowed. Compare elements explicitly when checking contents.
Expected output:
[tea] falseTry it locally
Declare a nil slice of strings and an empty non-nil slice. Print the nil checks and lengths, then append "Go" to the nil slice and print it.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Slices 01: Construct nil and empty slices
Check the lesson objective before moving on.
What is the zero value of []int?
Which test detects any empty slice?