Slice length and capacity

A slice has both a length and a capacity.

The length of a slice is the number of elements it contains.

The capacity of a slice is the number of elements in the underlying array, counting from the first element in the slice.

The length and capacity of a slice s can be obtained using the expressions len(s) and cap(s).

You can extend a slice's length by re-slicing it, provided it has sufficient capacity. Try changing one of the slice operations in the example program to extend it beyond its capacity and see what happens.

slice-len-cap.go

  1. package main
  2. import "fmt"
  3. func main() {
  4. s := []int{2, 3, 5, 7, 11, 13}
  5. printSlice(s)
  6. // Slice the slice to give it zero length.
  7. s = s[:0]
  8. printSlice(s)
  9. // Extend its length.
  10. s = s[:4]
  11. printSlice(s)
  12. // Drop its first two values.
  13. s = s[2:]
  14. printSlice(s)
  15. }
  16. func printSlice(s []int) {
  17. fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
  18. }