Middle+
Tell us about slices in Go. What are they and what should be considered when working with them?
sobes.tech AI
Answer from AI
Slices in Go are dynamic, mutable sequences of elements of the same type, which are wrappers over arrays.
Key points:
- A slice contains a pointer to an array, a length (len), and a capacity (cap).
- Length is the number of elements available in the slice.
- Capacity is the maximum number of elements that can be stored without allocating new memory.
- When adding elements using
append, if the capacity is exceeded, a new array is created, and data is copied. - Slices can be created from arrays or other slices, which creates a reference to the same array (it's important to consider that modifying a slice can affect the original array).
Example:
arr := [5]int{1, 2, 3, 4, 5}
slice := arr[1:4] // elements with indices 1,2,3
slice = append(slice, 6) // if cap allows, adds 6 to the original array
Important to remember:
- Changes to a slice can affect the original array and other slices referencing the same array.
- When passing a slice to a function, the slice structure is copied, but not the data, so changes to elements inside the function reflect on the original data.
- To avoid unexpected effects, control capacity and copy slices when necessary.