关于go:为什么切片的容量不随 `[:0]`而减少

why the slice's capacity does not decrease with `[:0]`

我在看《围棋之旅》,对一个切片箱感到困惑。

1
s = s[:0]

手术后,slen()变为0,而cap()不变为0。为什么容量没有减少?什么时候使用这个"功能"?


(P)You can actually use the three-index slicing to get the Zero-Capped slice:(p)字母名称(P)Playground:https://play.golang.org/p/yetcdjvwrb。(p)


(P)The choice to not modify the capacity is like a performance优化.Slices are basically'dynamic array s',they intend to provide the abstraction that the array's capacity is unlimited.In reality,capacity is of course limited by system memory,however if a slice is at capacity and you EDOCX1 pental 0.An item to it,go will allocate new memory for the array to provide that capacity(assuming it's available,if it's not your app will ofc panic).(p)(P)The Length represents the actual indexible item count in the slice,while the capacity tells you how much underlying memory is there.When you do those reslicing operations,there is no immediate need to free the memory and therefor it remains allocated,that is why the slices capacity remains unchanged but the length goes to零.(p)(P)总的来说,这一类似的领导层要更好地应用性能,因为备忘录仍然是可以使用的,它应该随后的声明附录于Slice项目。在实践中,你一般不需要讨论能力问题。I would recommend keeping it in the back of your mind however.(p)(P)The Times where it's most relevant,IMO,is when you're reading data from some source and you know the size of that data,or at least have a rough idea,and you're putting that into a slice.在一个循环中,如果你以适当的能力开始实施隔离墙,那么你的应用将更为有效。如果你提供的不是Length或Capacity Arguments(Capacity Defaults to Length,if only length is provided),那么,你可能会发现,衰败的滑坡是没有效率的,或者在《最新情况》中,你会引入没有效率的做法,而这种做法可以消除易受伤害的现象。(p)