How to get the total number of elements that an array can hold or the capacity of an array in Go or Golang?

Published September 4, 2022

To get the total number of elements an array can hold or its capacity in Go or Golang, you can use the cap() built-in function and then pass the array or the array variable as an argument to the function.

The method returns an int type value that refers to the total capacity of the array.

TL;DR

package main

import "fmt"

func main() {
    // a simple array
    // that can hold `10` elements.
    // Add 2 elements to the array.
    names := [10]string{"John Doe", "Lily Roy"}

    // get the total capacity of the `names`
    // array using the `cap()` built-in function
    totalCapacity := cap(names)

    // log to the console
    fmt.Println(totalCapacity) // 10 ✅
}

For example, let's say we have a string type array called names that can hold 10 elements like this,

package main

func main() {
    // a simple array
    // that can hold `10` elements
    names := [10]string{}
}

Let's also add 2 elements to the array like this,

package main

func main() {
    // a simple array
    // that can hold `10` elements.
    // Add 2 elements to the array.
    names := [10]string{"John Doe", "Lily Roy"}
}

Now to get the total capacity of the names array, we can use the cap() built-in function and pass the names array as an argument to it like this,

package main

func main() {
    // a simple array
    // that can hold `10` elements.
    // Add 2 elements to the array.
    names := [10]string{"John Doe", "Lily Roy"}

    // get the total capacity of the `names`
    // array using the `cap()` built-in function
    totalCapacity := cap(names)
}

Finally, let's print the totalCapacity value to the console like this,

package main

import "fmt"

func main() {
    // a simple array
    // that can hold `10` elements.
    // Add 2 elements to the array.
    names := [10]string{"John Doe", "Lily Roy"}

    // get the total capacity of the `names`
    // array using the `cap()` built-in function
    totalCapacity := cap(names)

    // log to the console
    fmt.Println(totalCapacity) // 10 ✅
}

As you can see that the value of 10 is printed on the console.

NOTE: The capacity of an array should not be confused with the length of an array. The length of an array refers to the total number of elements currently present in the array.

See the above code live in The Go Playground.

That's all 😃!

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter