To create a slice with a specified capacity in Golang, you can use the make
function with two arguments. The first argument specifies the type of the slice, and the second argument specifies the length and capacity of the slice.
Here is an example:
package main
import "fmt"
func main() {
// Create a slice with a capacity of 5
slice := make([]int, 0, 5)
// Print the length and capacity of the slice
fmt.Println("Length:", len(slice))
fmt.Println("Capacity:", cap(slice))
}
In this example, make([]int, 0, 5)
creates a new integer slice with a length of 0 and a capacity of 5. The length is initially 0 because no elements have been added to the slice yet. The capacity specifies the number of elements the slice can hold before it needs to be resized.
The output of this program will be:
Length: 0
Capacity: 5