Related Tags

golang

# What is the Cap function in Golang?

Talha Ashar

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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, $0$ is returned.
• Channel: The Cap function returns the channel buffer capacity. If v is nil, $0$ is returned.

## Code

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

package mainimport (	"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 $1$ and capacity of $3$, and an array (c) that contains $6$ 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 $3$, the Cap function returns $3$. Similarly, as c is an array, the Cap function returns the number of elements it contains, i.e., $6$.

Next, $2$ elements are appended to a, so it now contains $3$ elements in total. Since the number of elements in a is equal to its capacity, the Cap function still returns $3$ 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 $6$.

RELATED TAGS

golang

CONTRIBUTOR

Talha Ashar