The cap()
function in Golang takes an input and returns its capacity depending on the input type.
The following table describes the types of a single input v
that the cap()
function accepts. The return value is of type int
.
v | Description |
---|---|
array | The cap() function returns the number of elements in the array. |
pointer to the array | The cap() function returns the number of elements in the array. |
slice | The cap() function returns the number of elements in the underlying array. |
channel | The cap() function returns the channel buffer capacity in units of elements. |
The following code demonstrates how to use the cap()
function in Go.
The program creates an array, slice, pointer, and channel, then runs the cap()
function on them.
The make()
function creates the slice and the channel, which takes the type, length, and an optional capacity as inputs.
package mainimport "fmt"func main() {// create an array of 6 elementsvar arr [6] int// call the cap functioncapArr := cap(arr)fmt.Println("The capacity of the array is:")fmt.Println(capArr)// create a slice of length 0 and capactiy 10slice := make([]string, 0, 10)capSlice := cap(slice)fmt.Println("The capacity of the slice is:")fmt.Println(capSlice)// create a channel of capacity 5channel := make(chan string, 5)capChannel := cap(channel)fmt.Println("The capacity of the channel is:")fmt.Println(capChannel)// create a pointer to an array of 20 elementsvar pointer *[20]stringcapPointer := cap(pointer)fmt.Println("The capacity of the pointer is:")fmt.Println(capPointer)}
Free Resources