Golang将一个项目追加到一个切片 [英] Golang append an item to a slice
问题描述
为什么 a
保持不变? append()
是否生成新的分片?
package main
导入(
fmt
)
var a = make([] int,7,8)
func Test(slice [] int){
slice = append(slice,100)
fmt.Println(slice)
}
func main(){
for i:= 0;我< 7; i ++ {
a [i] = i
}
测试(a)
fmt.Println(a)
}
$在您的示例中,切片
Test
函数的参数在调用者的作用域中接收变量 a
的副本。
由于slice变量包含一个slice描述符,它只是引用一个底层数组,在 Test code>函数可以连续多次修改 slice
变量中保存的切片描述符,但这不会影响调用者及其一个
变量。
在 Test
函数中,第一个 append
重新分配 slice
变量下的backing数组,将其原始内容复制到 100
就可以了,这就是你正在观察的。从 Test
退出时, slice
变量超出范围,并且切片引用的(新)底层数组。
如果您想使 Test
的行为类似于 append
,您必须从中返回新片 —就像追加
一样 - —并要求 Test
的调用者以与他们使用 append
相同的方式使用它: func Test(slice [] int)[] int {
slice = append(slice,100)
fmt.Println(slice)
return slice
}
a =测试(a)
请详细阅读这篇文章基本上向您展示了如何在解释slice如何在内部工作之后,手动实现 append
。然后阅读这个。
Why does a
remain the same? Does append()
generate a new slice?
package main
import (
"fmt"
)
var a = make([]int, 7, 8)
func Test(slice []int) {
slice = append(slice, 100)
fmt.Println(slice)
}
func main() {
for i := 0; i < 7; i++ {
a[i] = i
}
Test(a)
fmt.Println(a)
}
解决方案 In your example the slice
argument of the Test
function receives a copy of the variable a
in the caller's scope.
Since a slice variable holds a "slice descriptor" which merely references an underlying array, in your Test
function you modify the slice descriptor held in the slice
variable several times in a row, but this does not affect the caller and its a
variable.
Inside the Test
function, the first append
reallocates the backing array under the slice
variable, copies its original contents over, appends 100
to it, and that's what you're observing. Upon exiting from Test
, the slice
variable goes out of scope and so does the (new) underlying array that slice references.
If you want to make Test
behave like append
, you have to return the new slice from it — just like append
does — and require the callers of Test
to use it in the same way they would use append
:
func Test(slice []int) []int {
slice = append(slice, 100)
fmt.Println(slice)
return slice
}
a = Test(a)
Please read this article thoroughly as it basically shows you how to implement append
by hand, after explaining how slices are working internally. Then read this.
这篇关于Golang将一个项目追加到一个切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!