Junior — Middle
How to correctly create and initialize slices in Go?
sobes.tech AI
Answer from AI
In Go, slices are dynamic data structures that represent a reference to an array with a specified length and capacity.
Slices can be created and initialized in several ways:
- Declaration of a slice without initialization (nil slice):
var s []int // nil slice, length and capacity 0
- Initialization of a slice using a literal:
s := []int{1, 2, 3} // slice of length 3
- Creating a slice using the make function:
s := make([]int, 5) // slice of length 5, filled with zeros
s2 := make([]int, 3, 10) // length 3, capacity 10
The make function allocates an array under the hood and returns a slice pointing to it.
- Creating a slice from an array:
arr := [5]int{1, 2, 3, 4, 5}
s := arr[1:4] // slice of elements with indices 1, 2, 3
It is important to remember that slices are references to arrays, so modifying slice elements also modifies the original array.
Example usage:
package main
import "fmt"
func main() {
s := make([]int, 3, 5)
fmt.Println(s) // [0 0 0]
fmt.Println(len(s)) // 3
fmt.Println(cap(s)) // 5
s = append(s, 4, 5)
fmt.Println(s) // [0 0 0 4 5]
fmt.Println(len(s)) // 5
fmt.Println(cap(s)) // 5
}
This approach allows efficient work with dynamic arrays in Go.