Junior — Middle
How is the insertion of elements into a dynamic array (slice) implemented in programming languages?
sobes.tech AI
Answer from AI
In Go language, dynamic arrays are represented as slices. Inserting elements into a slice is usually done with the append function, which adds new elements to the end of the slice. If the internal array of the slice is not large enough, append will allocate a new larger array, copy the data there, and return a new slice.
Example of inserting an element:
s := []int{1, 2, 3}
s = append(s, 4) // s is now [1 2 3 4]
To insert an element into the middle of a slice, you can use a combination of slices and append:
s := []int{1, 2, 4, 5}
index := 2
value := 3
s = append(s[:index], append([]int{value}, s[index:]...)...)
// s is now [1 2 3 4 5]
Thus, inserting elements into a slice involves creating a new slice with the desired elements, using append and slice operations.