How to use the cap function in Go

The cap() function in Golang takes an input and returns its capacity depending on the input type.

Prototype

Parameters and return value

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.

Examples

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 main
import "fmt"
func main() {
// create an array of 6 elements
var arr [6] int
// call the cap function
capArr := cap(arr)
fmt.Println("The capacity of the array is:")
fmt.Println(capArr)
// create a slice of length 0 and capactiy 10
slice := make([]string, 0, 10)
capSlice := cap(slice)
fmt.Println("The capacity of the slice is:")
fmt.Println(capSlice)
// create a channel of capacity 5
channel := 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 elements
var pointer *[20]string
capPointer := cap(pointer)
fmt.Println("The capacity of the pointer is:")
fmt.Println(capPointer)
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved