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
The Cap
function takes a single mandatory parameter, v
, that can be an array
, slice
, or channel
.
The Cap
function returns one of the following, depending on the type of v
:
v
is an array, then the Cap
function returns the number of elements in v
.v
is a slice
, the Cap
function returns the maximum length v
can reach upon being resliced. If v
is nil
, is returned.Cap
function returns the channel buffer capacity. If v
is nil
, is returned.The code below shows how the Cap
function works in Golang:
package mainimport ("fmt""reflect")func main() {//initializing variablesa := make([]int,1,3)a[0] = 23b := reflect.ValueOf(a)c := [6]int{2, 3, 5, 7, 11, 13}d := reflect.ValueOf(c)//computing capacitiesa_capacity := b.Cap()c_capacity := d.Cap()// //printing resultsfmt.Println("The capacity of a is: ", a_capacity)fmt.Println("The capacity of c is: ", c_capacity)// appending 2 items to aa = append(a, 12, 40)b = reflect.ValueOf(a)fmt.Println("The new capacity of a is: ", b.Cap())// appending another item to aa = append(a, 6)b = reflect.ValueOf(a)fmt.Println("The new capacity of a is: ", b.Cap())}
First, the code initializes a slice (a
) that has a length of and capacity of , and an array (c
) that contains 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 , the Cap
function returns . Similarly, as c
is an array, the Cap
function returns the number of elements it contains, i.e., .
Next, elements are appended to a
, so it now contains elements in total. Since the number of elements in a
is equal to its capacity, the Cap
function still returns 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 .
Free Resources