Golang : How to get capacity of a slice or array?
Problem :
You have a slice and you need to find out the capacity of the slice.
Solution :
Use the builtin function cap()
to determine the slice's maximum length or the number of elements inside the array.
For example :
package main
import (
"fmt"
)
var a = make([]int, 7, 8)
func main() {
for i := 0; i < 7; i++ {
a[i] = i
}
fmt.Println(a)
fmt.Printf("Size of slice a is : %d", cap(a))
}
References :
See also : Golang : Delete duplicate items from a slice/array
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.1k Golang : How to convert strange string to JSON with json.MarshalIndent
+13.5k Golang : How to determine if a year is leap year?
+5.9k Golang : Measure execution time for a function
+29.5k Golang : Get time.Duration in year, month, week or day
+17.9k Golang : How to remove certain lines from a file
+21.9k Golang : Securing password with salt
+19.6k Golang : How to run your code only once with sync.Once object
+6.6k Golang : How to solve "too many .rsrc sections" error?
+19.5k Golang : Measure http.Get() execution time
+21.4k Golang : Convert string slice to struct and access with reflect example
+12.6k Golang : Convert IPv4 address to packed 32-bit binary format