对戈朗片帽感到困惑

我有一个关于切片帽的问题,代码:


var slice []int

list := []int{1,2,3,4,5}

for _,item := range list {

    slice = append(slice, item)

}

fmt.Println(len(slice),cap(slice))

如果项目 == 1:len(切片)=1,帽(切片)=1


如果项目 == 2:len(切片)=2,帽(切片)= 1*2


如果项目 ==3: len(切片) = 3,帽(切片) = 2*2


如果项目 == 4:len(切片) = 4,帽(切片) = 4


如果项目 == 5:len(切片) = 5,帽(切片) = 4*2


所以输出:


len(切片) = 5,帽(切片) = 8


没问题,但是当我更改代码时:


var slice []int

slice = append(slice,1,2,3,4,5)

fmt.Println(len(slice),cap(slice))

输出:


len(切片) = 5,帽(切片) = 6


为什么帽(切片) = 6 ?


芜湖不芜
浏览 73回答 1
1回答

慕妹3146593

您可以在 src/运行时/切片中追加时看到容量计算的算法.go - 第 162 行func growslice(et *_type, old slice, cap int)&nbsp; &nbsp; newcap := old.cap&nbsp; &nbsp; doublecap := newcap + newcap&nbsp; &nbsp; if cap > doublecap {&nbsp; &nbsp; &nbsp; &nbsp; newcap = cap&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; if old.cap < 1024 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newcap = doublecap&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Check 0 < newcap to detect overflow&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // and prevent an infinite loop.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for 0 < newcap && newcap < cap {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newcap += newcap / 4&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Set newcap to the requested cap when&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // the newcap calculation overflowed.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if newcap <= 0 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newcap = cap&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }首先将旧切片容量乘以 2。如果乘以 2 后的容量仍小于新切片容量,则取新切片容量(追加多个 elem)如果新片小于旧片容量的两倍,请将旧片容量乘以 2如果旧片容量大于或等于 1024,则新片容量乘以旧片容量乘以 1.25
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go