c
is a slice taken from the array b
. This isn't a copy, but just a window over the 2 first elements of b
.
As b
has a capacity of 5, c
could be extended to take the 3 other places (in fact it makes a new slice but over the same place in memory).
The maximal capacity of the slice is the capacity of the underlying array minus the position of the start of the slice in the array :
array : [0 0 0 0 0 0 0 0 0 0 0 0]
array : <---- capacity --->
slice : [0 0 0 0]
slice : <---- capacity --->
Maybe this program will make it more clear that c and d are just windows over b :
func main() {
b := make([]int, 0, 5)
c := b[:2]
d := c[1:5] // this is equivalent to d := b[1:5]
d[0] = 1
printSlice("c", c)
printSlice("d", d)
}
Output :
c len=2 cap=5 [0 1] // modifying d has modified c
d len=4 cap=4 [1 0 0 0]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…