在 Golang 中重新切片切片 [英] Re-slicing slices in Golang
问题描述
最近学了 Go 语言,现在对下面的代码很困惑:
I recently picked up the Go language, and now I am 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]
推荐答案
c
是取自数组 b
的切片.这不是副本,而是 b
的第 2 个元素上方的窗口.
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 只是 b 上的窗口:
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屋!