What is the Cap function in Golang?

The Cap function of the reflect module in Golang returns the capacity of a provided parameter, depending on the parameter’s type.

To use the Cap function, you will need to include the reflect library, as shown below:

import(
   "reflect"
)

The prototype of the Cap function is shown below:

func (v Value) Cap() int

Parameters

The Cap function takes a single mandatory parameter, v, that can be an array, slice, or channel.

Return value

The Cap function returns one of the following, depending on the type of v:

  • Array: If v is an array, then the Cap function returns the number of elements in v.
  • Slice: If v is a slice, the Cap function returns the maximum length v can reach upon being resliced. If v is nil, 00 is returned.
  • Channel: The Cap function returns the channel buffer capacity. If v is nil, 00 is returned.

Code

The code below shows how the Cap function works in Golang:

package main
import (
"fmt"
"reflect"
)
func main() {
//initializing variables
a := make([]int,1,3)
a[0] = 23
b := reflect.ValueOf(a)
c := [6]int{2, 3, 5, 7, 11, 13}
d := reflect.ValueOf(c)
//computing capacities
a_capacity := b.Cap()
c_capacity := d.Cap()
// //printing results
fmt.Println("The capacity of a is: ", a_capacity)
fmt.Println("The capacity of c is: ", c_capacity)
// appending 2 items to a
a = append(a, 12, 40)
b = reflect.ValueOf(a)
fmt.Println("The new capacity of a is: ", b.Cap())
// appending another item to a
a = append(a, 6)
b = reflect.ValueOf(a)
fmt.Println("The new capacity of a is: ", b.Cap())
}

Explanation

First, the code initializes a slice (a) that has a length of 11 and capacity of 33, and an array (c) that contains 66 elements.

The ValueOf method is used on both the slice and the array to obtain concrete values that will allow the Cap function to be used.

The Cap function proceeds to compute the capacities of each of these variables and outputs the results accordingly.

Since a was initialized with a capacity of 33, the Cap function returns 33. Similarly, as c is an array, the Cap function returns the number of elements it contains, i.e., 66.

Next, 22 elements are appended to a, so it now contains 33 elements in total. Since the number of elements in a is equal to its capacity, the Cap function still returns 33 for a. However, upon the addition of another element, the capacity of a is exceeded, so a is resliced, and its capacity doubles. Therefore, the Cap function now returns 66.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved