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.
Add your answer
Loading...

Leave a comment

Your email address will not be published. Required fields are marked *