Go - slice length and capacity example

In this example, we will show you how to get slice length and capacity in Go with an example.

The len function returns the number of elements in the slice.

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

Go - slice length and capacity example

In the example, we print the size and the capacity of two slices:


package main

import "fmt"

func main() {

    vals := make([]int, 10, 15)

    n := len(vals)
    c := cap(vals)

    fmt.Printf("The size is: %d\n", n)
    fmt.Printf("The capacity is: %d\n", c)

    vals2 := vals[0:8]
    n2 := len(vals2)
    c2 := cap(vals2)

    fmt.Printf("The size is: %d\n", n2)
    fmt.Printf("The capacity is: %d\n", c2)
}

Output:

The size is: 10
The capacity is: 15
The size is: 8
The capacity is: 15

Comments