We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
除了常规的按现有容量×2或×1.25倍,有个特殊情况是如果append新加入的元素超过了按倍数扩容的容量,其实际扩容容量会满足append的需求,经过测试貌似是实际需求容量向上取偶数,测试代码如下:
s:=[]int{1,2,3,4,5,6,7,8} fmt.Println(len(s),cap(s)) // 8 8 s1:=append(s,9,10,11,12,13,14,15,16) fmt.Println(len(s1),cap(s1)) // 16 16 s2:=append(s,9,10,11,12,13,14,15,16,17) fmt.Println(len(s2),cap(s2)) // 17 18 s3:=append(s,9,10,11,12,13,14,15,16,17,18) fmt.Println(len(s3),cap(s3)) // 18 18 s4:=append(s,9,10,11,12,13,14,15,16,17,18,19) fmt.Println(len(s4),cap(s4)) // 19 20 s5:=append(s,9,10,11,12,13,14,15,16,17,18,19,20) fmt.Println(len(s5),cap(s5)) // 20 20 s6:=append(s,9,10,11,12,13,14,16,16,17,18,19,20,21) fmt.Println(len(s6),cap(s6)) // 21 22 s7:=append(s,9,10,11,12,13,14,17,17,17,18,19,20,21,22) fmt.Println(len(s7),cap(s7)) // 22 22
The text was updated successfully, but these errors were encountered:
是的。Go在计算最终分配容量时,会先按2倍或1.25倍预估,然后再跟据具体的类型进行调整。具体调整算法在这里。
实际使用中,会发现几乎没有必要去追究切片的容量到底增长了多少。
Sorry, something went wrong.
话说,你觉得书中内容需要相应地调整吗?
可能顺带提一下就好了吧,毕竟具体实现中的差异无伤大雅。
No branches or pull requests
除了常规的按现有容量×2或×1.25倍,有个特殊情况是如果append新加入的元素超过了按倍数扩容的容量,其实际扩容容量会满足append的需求,经过测试貌似是实际需求容量向上取偶数,测试代码如下:
The text was updated successfully, but these errors were encountered: