DEV Community

Cover image for How to get the total number of elements that an array can hold or the capacity of an array in Go or Golang?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

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

#go

Originally posted here!

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 ✅
}
Enter fullscreen mode Exit fullscreen mode

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{}
}
Enter fullscreen mode Exit fullscreen mode

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"}
}
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

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 ✅
}
Enter fullscreen mode Exit fullscreen mode

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 😃.


Top comments (0)