How do you declare and initialize a slice in Go?

  • var s []int
  • s := make([]int, 10)
  • s := []int{1, 2, 3}
  • s := new([]int)
To declare and initialize a slice in Go, you can use the shorthand s := []T{elements}, where T is the type of the elements you want to store in the slice, and elements is a comma-separated list of values enclosed in curly braces. This syntax creates a new slice and initializes it with the specified elements. You can also use make([]T, length, capacity) to create a slice with a specified length and capacity. Understanding how to declare and initialize slices is fundamental for working with collections of data in Go.
Add your answer
Loading...

Leave a comment

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