Golang在对不同的切片进行切片时显示不同的容量。

huangapple go评论82阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年4月16日 02:59:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76024215.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定