为什么GO中切片的内容未更改? [英] Why is the content of slice not changed in GO?
问题描述
我认为在GO语言中,切片是通过引用传递的.但是,为什么下面的代码不更改切片c的内容?我想念什么吗?谢谢你.
I thought that in GO language, slices are passed by reference. But why the following code doesn't change the content of slice c? Am I missing something? Thank you.
package main
import (
"fmt"
)
func call(c []int) {
c = append(c, 1)
fmt.Println(c)
}
func main() {
c := make([]int, 1, 5)
fmt.Println(c)
call(c)
fmt.Println(c)
}
打印的结果是:
[0] [0 1] [0]
[0] [0 1] [0]
在我期待的时候
[0] [0 1] [0 1]
[0] [0 1] [0 1]
推荐答案
切片的长度保留在切片标头中,该标头未通过引用传递.您可以将切片视为包含指向数组的指针,长度和容量的结构.
The length of the slice is kept in the slice header which is not passed by reference. You can think of a slice as a struct containing a pointer to the array, a length, and a capacity.
当附加到切片时,您修改了数据数组中的索引1,然后增加了切片标头中的长度.返回时,主函数中的c
的长度为1,因此打印了相同的数据.
When you appended to the slice, you modified index 1 in the data array and then incremented the length in the slice header. When you returned, c
in the main function had a length of 1 and so printed the same data.
切片以这种方式工作的原因是,您可以使多个切片指向同一数据.例如:
The reason slices work this way is so you can have multiple slices pointing to the same data. For example:
x := []int{1,2,3}
y := x[:2] // [1 2]
z := x[1:] // [2 3]
所有这三个切片都指向同一基础数组中的重叠数据.
All three of those slices point to overlapping data in the same underlying array.
这篇关于为什么GO中切片的内容未更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!