英文:
Golang showing different capacities when slicing something differently
问题
我正在尝试理解Go语言中的切片,并遇到了以下代码(Go playground):
package main
import "fmt"
func main() {
s := []int{1, 2, 3, 4, 5, 6}
example1(s)
fmt.Printf("\n")
example2(s)
}
func example1(s []int) {
fmt.Printf("Example 1: \n")
printSlice(s)
s = s[:4]
printSlice(s)
}
func example2(s []int) {
fmt.Printf("Example 2: \n")
printSlice(s)
s = s[2:]
printSlice(s)
}
func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}
输出结果如下:
Example 1:
len=6 cap=6 [1 2 3 4 5 6]
len=4 cap=6 [1 2 3 4]
Example 2:
len=6 cap=6 [1 2 3 4 5 6]
len=4 cap=4 [3 4 5 6]
尽管切片的长度看起来没问题,但我不明白的是为什么在第一个示例中切片后的容量为6
,而在第二个示例中容量为4
。
英文:
I'm trying to understand slices in Go, and have came across the following code ( Go playground ):
package main
import "fmt"
func main() {
s := []int{1, 2, 3, 4, 5, 6}
example1(s)
fmt.Printf("\n")
example2(s)
}
func example1(s []int) {
fmt.Printf("Example 1: \n")
printSlice(s)
s = s[:4]
printSlice(s)
}
func example2(s []int) {
fmt.Printf("Example 2: \n")
printSlice(s)
s = s[2:]
printSlice(s)
}
func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}
For which the output is:
Example 1:
len=6 cap=6 [1 2 3 4 5 6]
len=4 cap=6 [1 2 3 4]
Example 2:
len=6 cap=6 [1 2 3 4 5 6]
len=4 cap=4 [3 4 5 6]
While the length of the slices looks alright, what I don't undertand is why the capacity after slicing is 6
in the first example and 4
in the second example.
答案1
得分: 4
切片的容量是指从切片开始处起,底层数组中可以存储的元素数量。你的底层数组可以存储6个元素。在example1
中,你创建了一个新的切片,从第一个元素开始,延伸到4个元素,但容量仍然是6,因为切片从底层数组的开始处开始。在example2
中,切片从底层数组的第2个元素开始,所以只有4个元素的空间,因此容量是4。
这篇文章对切片的工作原理进行了很好的解释。
英文:
The capacity of the slice is the number of elements that can be stored in the underlying array starting at the beginning of the slice. Your underlying array can store 6 elements. In example1
, you create a new slice starting at the first element and extending for 4 elements, but the capacity is still 6 because your slice starts at the beginning of the underlying array. In example2
, the slice starts at element 2 of the underlying array, so there's only room for 4 more elements, so the capacity is 4.
This article gives a good explanation of how slices work.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论