重新切片切片Golang [英] Re-slicing slices in Golang
问题描述
我最近有回暖的围棋,现在我用下面的code困惑:
I recently has pick up the Go, and now I confused with the following code:
package main
import "fmt"
func main() {
a := make([]int, 5)
printSlice("a", a)
b := make([]int, 0, 5)
printSlice("b", b)
c := b[:2]
printSlice("c", c)
d := c[2:5]
printSlice("d", d)
}
func printSlice(s string, x []int) {
fmt.Printf("%s len=%d cap=%d %v\n",
s, len(x), cap(x), x)
}
和结果:
a len=5 cap=5 [0 0 0 0 0]
b len=0 cap=5 []
c len=2 cap=5 [0 0] //why the capacity of c not 2 but 5 instead
d len=3 cap=3 [0 0 0]
任何帮助将感谢。
Any help would thanks.
推荐答案
C
是从阵列中采取了分片 B
。这不是一个拷贝,而只是一个窗口超过的2第一元素中,b
。
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
.
由于 B
拥有5的容量, C
可以扩展到取3其他地方(其实它使一个新的片但在内存中的同一个地方)。
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 --->
也许这一计划将使其更清楚,C和D都只是窗户乙级以上:
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)
}
输出:
c len=2 cap=5 [0 1] // modifying d has modified c
d len=4 cap=4 [1 0 0 0]
这篇关于重新切片切片Golang的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!