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.
Loading...
Related Quiz
- A _____ is a situation where a program continuously uses more memory over time and does not release it.
- Mock objects in Go testing should implement the same _____ as the real objects they are replacing.
- How can you format your code automatically every time you save a file in your editor?
- The _____ file in a Go module contains the exact version of dependencies used in a project.
- How would you handle a situation where multiple Goroutines are attempting to access a shared resource?