package main
import "fmt"
func main() {
var numbers []int
printSlice(numbers)
/* 允许追加空切片 */
numbers = append(numbers, 0, 100)
printSlice(numbers)
/* 向切片添加一个元素 */
numbers = append(numbers, 1)
printSlice(numbers)
/* 同时添加多个元素 */
numbers = append(numbers, 2, 3, 4)
printSlice(numbers)
/* 创建切片 numbers1 是之前切片的两倍容量*/
numbers1 := make([]int, len(numbers), (cap(numbers))*2)
/* 拷贝 numbers 的内容到 numbers1 */
copy(numbers1, numbers)
printSlice(numbers1)
}
func printSlice(x []int) {
fmt.Printf(“len=%d cap=%d slice=%v\n”, len(x), cap(x), x)
}
运行结果:
len=0 cap=0 slice=[]
len=2 cap=2 slice=[0 100]
len=3 cap=4 slice=[0 100 1] #这里的cap 为啥是4不是3吗?
len=6 cap=8 slice=[0 100 1 2 3 4]
len=6 cap=16 slice=[0 100 1 2 3 4]
JasondeMacBook-Pro:golearing jason$