Junior — Middle
Can you explain what a slice is in Go language and how it works?
sobes.tech AI
Answer from AI
A slice in Go is a dynamic, resizable sequence type that represents a reference to an array. It contains three main components: a pointer to the first element of the array, the length (number of elements in the slice), and the capacity (the maximum number of elements the slice can hold without reallocating).
Slices are convenient because they allow working with sequences of data without needing to specify a fixed size in advance, as with arrays. When adding elements using the append function, a slice can automatically expand, creating a new array if necessary.
Example of using a slice:
package main
import "fmt"
func main() {
s := []int{1, 2, 3} // creating a slice
fmt.Println(s) // [1 2 3]
s = append(s, 4, 5) // adding elements
fmt.Println(s) // [1 2 3 4 5]
}
Thus, slices are a convenient and efficient way to work with sequences in Go, combining flexibility and performance.