Make slices with length and capacity
Make slices with length and capacity
make([]T, length, capacity) allocates an underlying array and returns a slice with the requested length and capacity. The length counts accessible elements; the capacity counts how far the slice can extend from its starting position in that array. Capacity must be at least length.
package main
import "fmt"
func main() { s := make([]int, 2, 5) s[1] = 7 fmt.Println(s, len(s), cap(s))}The two visible elements start at zero. Index 2 is not accessible merely because capacity is 5. Indexing uses length, not capacity. Reslicing can expose more elements up to capacity.
Expected output:
[0 7] 2 5Reserve room without adding elements
package main
import "fmt"
func main() { s := make([]int, 0, 3) s = append(s, 8, 9) fmt.Println(s, len(s), cap(s)) t := make([]int, 2) fmt.Println(t, len(t), cap(t))}An initial length of zero avoids unwanted zeros when building a list with append. If capacity is omitted it equals length. Negative sizes or length greater than capacity are invalid; dynamic invalid sizes panic.
Expected output:
[8 9] 2 3[0 0] 2 2Try it locally
Reserve capacity 4 with length zero. Append 3 and 6, then print the slice, length and capacity.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Slices 02: Make slices with length and capacity
Check the lesson objective before moving on.
Which makes a slice of length 0 and capacity 10?
Which determines valid element indexes?