What is the method for expanding a slice in Go?
In Go language, the append() function can be used to expand a slice.
Here is the syntax of the append() function:
append(s []T, x ...T) []T
In this case, ‘s’ represents the slice that needs to be expanded, and ‘x’ represents the element to be appended.
The append() function adds the elements to the existing slice, automatically expanding its capacity if needed by creating a new underlying array and copying the original elements into it before appending the new elements.
It should be noted that the append() function returns a new slice, so when using append() to expand, the return value needs to be reassigned to the original slice variable.
Here is an example code:
package main
import "fmt"
func main() {
s := []int{1, 2, 3}
fmt.Printf("原始slice:%v,容量:%d\n", s, cap(s))
s = append(s, 4, 5, 6)
fmt.Printf("扩容后的slice:%v,容量:%d\n", s, cap(s))
}
Output result:
原始slice:[1 2 3],容量:3
扩容后的slice:[1 2 3 4 5 6],容量:6
The original slice had a capacity of 3, but after adding 3 elements using the append() function, the slice automatically expanded to 6.