Home »
Golang »
Golang Reference
Golang cap() Function with Examples
Golang | cap() Function: Here, we are going to learn about the built-in cap() function with its usages, syntax, and examples.
Submitted by IncludeHelp, on October 13, 2021 [Last updated : March 15, 2023]
cap() Function
In the Go programming language, the cap() is a built-in function that is used to get the capacity of the given slice.
It accepts one parameter (v Type) and returns the capacity of v.
Syntax
func cap(v Type) int
Parameter(s)
- v : Slice of type Type whose capacity is to be found.
Return Value
The return type of the cap() function is an int, it returns the capacity of the given slice.
Special cases
- Array: In the case of an array the number of elements in v (same as len(v)).
- Pointer to array: In the case of pointer to an array the number of elements in *v (same as len(v)).
- Slice: In the case of a slice the maximum length the slice can reach when resliced;
- if the v (value of the given parameter) is nil, cap(v) is zero.
- Channel: In the case of a channel the channel buffer capacity, in units of elements;
Example 1
// Golang program to demonstrate the
// example of cap() function
package main
import (
"fmt"
)
func main() {
// Declaring & assigning some slices
a := []int{10, 20, 30}
b := []float32{20.23, 1.234, 10.20}
c := []string{"Hello", "world"}
// Printing their capacities
fmt.Println("cap(a):", cap(a))
fmt.Println("cap(b):", cap(b))
fmt.Println("cap(c):", cap(c))
}
Output
cap(a): 3
cap(b): 3
cap(c): 2
Example 2
// Golang program to demonstrate the
// example of cap() function
package main
import (
"fmt"
)
func main() {
// Creating int and string slices
s1 := []int{10, 20, 30}
s2 := []string{"Hello", "World"}
// Printing types and values of slices
fmt.Printf("%T, %v\n", s1, s1)
fmt.Printf("%T, %q\n", s2, s2)
// Printing the capacity
fmt.Println("Capacity of s1:", cap(s1))
fmt.Println("Capacity of s2:", cap(s2))
// Appending some elements
s1 = append(s1, 40, 50)
s2 = append(s2, "How are you?", "Boys")
// After appending,
// Printing types and values of slices
fmt.Println("After appending...")
fmt.Printf("%T, %v\n", s1, s1)
fmt.Printf("%T, %q\n", s2, s2)
// Printing the capacity
fmt.Println("Capacity of s1:", cap(s1))
fmt.Println("Capacity of s2:", cap(s2))
}
Output
[]int, [10 20 30]
[]string, ["Hello" "World"]
Capacity of s1: 3
Capacity of s2: 2
After appending...
[]int, [10 20 30 40 50]
[]string, ["Hello" "World" "How are you?" "Boys"]
Capacity of s1: 6
Capacity of s2: 4
Golang builtin Package »