Junior — Middle
What ways are there to modify a slice in programming?
sobes.tech AI
Answer from AI
In Go, a slice is a structure that contains a pointer to an array, a length, and a capacity. There are several ways to modify a slice:
- Changing elements by index — directly assign values to slice elements.
s := []int{1, 2, 3}
s[0] = 10
- Adding elements using the
appendfunction — creates a new slice if the capacity of the original is insufficient.
s = append(s, 4, 5)
- Removing elements — can be implemented by creating a new slice excluding the desired elements.
// removing element at index i
s = append(s[:i], s[i+1:]...)
- Changing the length of a slice through slicing
s = s[:len(s)-1] // reducing length
- Copying slices using
copy
copy(destSlice, sourceSlice)
Thus, modifying a slice can involve changing its contents, length, or capacity using append and slicing.