切片的容量是怎样增长的
func append(slice []Type, elems ...Type) []Typeslice = append(slice, elem1, elem2)
slice = append(slice, anotherSlice...)append(slice, elem1, elem2)
append(slice, anotherSlice...)package main
import "fmt"
func main() {
s := make([]int, 0)
oldCap := cap(s)
for i := 0; i < 2048; i++ {
s = append(s, i)
newCap := cap(s)
if newCap != oldCap {
fmt.Printf("[%d -> %4d] cap = %-4d | after append %-4d cap = %-4d\n", 0, i-1, oldCap, i, newCap)
oldCap = newCap
}
}
}Last updated
Was this helpful?