Middle
How is a slice in Go structured and how does it differ from an array?
sobes.tech AI
Answer from AI
In Go, a slice is a structure that describes a sequence of elements of the same type but does not contain data itself; it only points to an array in memory.
A slice consists of three components:
- a pointer to the underlying array,
- length (the number of elements accessible through the slice),
- capacity (the maximum number of elements that can be stored starting from the pointer).
Differences between a slice and an array:
- An array is a fixed-size sequence of elements, with size defined at declaration and not changeable.
- A slice is a dynamic structure that can change its length (through append and other operations).
- An array is passed by value, whereas a slice is passed by reference to the array, making it more flexible and efficient to work with.
Example:
arr := [5]int{1, 2, 3, 4, 5} // fixed-size array
slice := arr[1:4] // slice with elements {2, 3, 4}
slice = append(slice, 6) // slice can expand, possibly allocating a new array
Thus, a slice is a convenient and flexible way to work with sequences in Go, hiding the details of memory management.