In go-tour the offcial guide, the append make the capacity
package main
import "fmt"
func main() {
a := make([]int,0)
printSlice("a", a)
// append works on nil slices.
a = append(a, 0)
printSlice("a", a)
// the slice grows as needed.
a = append(a, 1)
printSlice("a", a)
// we can add more than one element at a time.
a = append(a, 2, 3, 4)
printSlice("a", a)
}
func printSlice(s string, x []int) {
fmt.Printf("%s len=%d cap=%d %v\n",
s, len(x), cap(x), x)
}
finally came out the capacity can be 6 and 8 some times, so check what happened behind the append.
below implement the append.
below implements the capcity
https://github.com/golang/go/blob/5476967b1a3d29fef4061999c00cadbec19ac0e3/src/runtime/slice.go#L82
Then drew the conclusion, the capcity can be the
capacity of append(l1,l2) will be max(2*cap(l1), len(l1)+len(l2))
本文通过一个简单的 Go 语言示例展示了切片的使用及 append 函数的工作原理。探讨了切片在不同情况下的长度与容量变化,并深入分析了容量计算公式:capacity of append(l1,l2) = max(2*cap(l1), len(l1)+len(l2))。
2855

被折叠的 条评论
为什么被折叠?



