create a slice with a length and capacity in go

In Go, a slice can be created with a desired length and capacity using the built-in make() function. The make() function takes three arguments: the type of the slice, its length, and its capacity.

Here is an example of creating a slice with a length of 5 and a capacity of 10:

main.go
mySlice := make([]int, 5, 10)
30 chars
2 lines

This creates a slice that has five elements, but with an underlying array that has a capacity of 10. This means that the slice can be increased in length up to 10 without having to allocate a new array.

It's important to note that the length and capacity of a slice are not interchangeable. The len() function returns the current length of a slice, while the cap() function returns its capacity.

gistlibby LogSnag