Senior
What operations exist on slices in Go?
sobes.tech AI
Answer from AI
In Go, slices are dynamic arrays that support the following operations:
-
Creating a slice:
s := []int{1, 2, 3} s2 := make([]int, 5) // slice of length 5 -
Accessing elements:
x := s[0] // first element s[1] = 10 // assignment -
Changing length with
append:s = append(s, 4, 5) -
Slicing a slice:
sub := s[1:3] // elements with indices 1 and 2 -
Copying slices:
dst := make([]int, len(s)) copy(dst, s) -
Removing an element:
// remove element at index i s = append(s[:i], s[i+1:]...) -
Iterating:
for i, v := range s { fmt.Println(i, v) } -
Getting length and capacity:
length := len(s) capacity := cap(s)
Thus, the main operations on slices include creation, access, resizing with append, slicing, copying, removing elements, and obtaining metadata (length, capacity).