Junior — Middle
Can you explain the mechanism of adding an element to the end of a data structure, such as a list or array?
sobes.tech AI
Answer from AI
In Go, to add an element to the end of a slice, the built-in append function is used. Slices are dynamic structures that can change size.
Example:
package main
import "fmt"
func main() {
nums := []int{1, 2, 3}
nums = append(nums, 4) // add 4 to the end
fmt.Println(nums) // [1 2 3 4]
}
If the slice does not have enough capacity, append will create a new array with increased size, copy the old elements, and add the new one. Arrays in Go have a fixed size, so slices are used for dynamic addition.