Senior
What is the difference between slice and array in Go, and how does append work?
sobes.tech AI
Answer from AI
In Go, an array is a fixed-size structure, with its size specified at declaration and cannot be changed. For example:
var arr [3]int // array of 3 elements
A slice is a dynamic, resizable type that represents a reference to a part of an array. It contains a pointer to the array, length, and capacity.
var s []int // slice, can grow
The append function adds elements to a slice. If the current capacity of the slice is insufficient, a new array with increased capacity is created, data is copied, and a new slice is returned:
s := []int{1, 2}
s = append(s, 3, 4)
Thus, append allows for dynamic expansion of slices, unlike arrays with fixed size.