CodeBlanks Logo Icon CodeBlanks

len and cap

Learn the length and capacity of a slice.

len and cap

len(s) is the number of elements in the slice; cap(s) is the total room available in the underlying array from the slice's start. Length can't exceed capacity.

s := make([]int, 2, 5)
fmt.Println(len(s), cap(s))  // 2 5
s = append(s, 1, 2, 3)
fmt.Println(len(s), cap(s))  // 5 5
s = append(s, 9)
fmt.Println(len(s), cap(s))  // 6 10 (new array)

When capacity fills up, Go usually doubles it (large slices grow by less).

The cost of growth

On every growth all elements are copied to a new array. Appending 1 million elements one by one means about 20 growths; starting with make([]T, 0, 1_000_000) avoids all of these copies. If you keep a small sub-slice of a large slice, the large underlying array stays in memory too; copy the small piece with slices.Clone if needed.

Practice Watch the growth

Append the numbers 1 to 5 one by one to an empty []int; after each append print len and cap with fmt.Println(len(s), cap(s)).

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func main() {
    var s []int
    for i := 1; i <= 5; i++ {
        s = append(s, i)
        fmt.Println(len(s), cap(s))
    }
}

Expected output

1 1
2 2
3 4
4 4
5 8

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 For <code>s := []int{1, 2, 3, 4, 5}</code>, what is <code>cap(s[2:])</code>?

  • 2
  • 0
  • 3 Correct answer
  • 5

Explanation: A sub-slice's capacity is the room from its start to the end of the underlying array: 5 - 2 = 3.

2 Capacity

Question
s := make([]int, 0, 8)
fmt.Println(____(s))  // 8
Answer
s := make([]int, 0, 8)
fmt.Println(cap(s))  // 8

Explanation: cap gives the slice's total capacity in the underlying array.

3 Slice and len/cap

Term Meaning
make([]int, 3) 3 / 3
make([]int, 0, 4) 0 / 4
[]int{1, 2}[1:] 1 / 1
var s []int 0 / 0

All lessons in Beginner