Length and capacity
suggest changeSlices have both length and capacity. The length of a slice is the number of elements currently in the slice, while the capacity is the number of elements the slice can hold before needing to be reallocated.
When creating a slice using the built-in make()
function, you can specify its length, and optionally its capacity. You can check capacity and length with len()
and cap()
:
var s = make([]int, 3, 5)
fmt.Printf("Length: %d\n", len(s))
fmt.Printf("Capacity: %d\n", cap(s))
Length: 3
Capacity: 5
If the capacity is not explicitly specified, it will default to the value of the specified length.
var s = make([]int, 4)
fmt.Printf("Length: %d\n", len(s))
fmt.Printf("Capacity: %d\n", cap(s))
Length: 4
Capacity: 4
Elements created by make()
are set to the zero value for the element type of the slice:
var s = make([]int, 3)
for idx, val := range s {
fmt.Println(idx, val)
}
0 0
1 0
2 0
You cannot access elements beyond the length of a slice, even if the index is within capacity:
s := make([]int, 3, 20)
fmt.Println(s[5])
panic: runtime error: index out of range [5] with length 3
goroutine 1 [running]:
main.main()
/tmp/src679752982/main.go:9 +0x1d
exit status 2
Capacity allow us to optimize performance.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents