How would you declare a slice with an initial capacity of 5 in Go?
- var s []int
- s := make([]int, 5)
- s := new(slice[int, 5])
- s := []int{5}
To declare a slice with an initial capacity of 5 in Go, you can use the make function. The correct way is s := make([]int, 5), where make creates a new slice with the specified capacity and an underlying array of the same size. This preallocates memory for the slice, which can improve performance when appending elements. Misunderstanding this can lead to inefficient memory usage or runtime errors.
Loading...
Related Quiz
- In what situations would a type switch be a preferred choice over traditional switch statements in Go?
- Maps in Go are not _____ by default, which means the order of keys when iterating over a map can change.
- What is the built-in error type in Go and how is it generally used?
- In Go, a Goroutine is a lightweight thread of execution managed by the Go _____ .
- Explain how you would utilize benchmark results to optimize a Go program's performance.