Golang builtin.cap() function example

package builtin

The cap built-in function returns the capacity of the input vector, according to the vector type:

Golang builtin.cap() function usage example

 package main

 import "fmt"

 func main() {

 array := []int{1,2,3,4,5,6,7,8,9,10}

 fmt.Println(array[:]) // print everything

 fmt.Println(array[0:5]) // print element 0 to 5. Remember, array starts counting from zero!

 // there are times we do not know the size of the array during runtime
 // so use cap() function

 fmt.Println(array[:cap(array)]) // cap() returns the capacity/max size of the array
 }

Output :

[1 2 3 4 5 6 7 8 9 10]

[1 2 3 4 5]

[1 2 3 4 5 6 7 8 9 10]

Reference :

http://golang.org/pkg/builtin/#cap

Advertisement