英文:
Why isn't caller seeing new data in slice?
问题
在下面的代码中,为什么fmt.Println(len(people))
两次都打印出0
呢?正如在这里指出的https://stackoverflow.com/a/2441112/315445以及其他地方所提到的,切片是引用类型。为什么调用者(main函数)没有看到更新后的数据呢?
package main
import "fmt"
type Person struct {
name string
age string
}
func main() {
var people = make([]Person, 0)
fmt.Println(len(people))
getList(people)
fmt.Println(len(people))
}
func getList(people []Person) {
people = append(people, Person{"Foo", "1"})
people = append(people, Person{"Bar", "2"})
}
但是下面的代码可以正常工作。所以它实际上不是按引用传递
吗?
package main
import "fmt"
type Person struct {
name string
age string
}
func main() {
var people = make([]Person, 0)
fmt.Println(len(people))
people = getList(people)
fmt.Println(len(people))
}
func getList(people []Person) []Person {
people = append(people, Person{"Foo", "1"})
people = append(people, Person{"Bar", "2"})
return people
}
英文:
In the below code, why are both fmt.Println(len(people))
printing 0
?
As pointed out here, https://stackoverflow.com/a/2441112/315445, and elsewhere, slice is reference type. Why isn't caller (main) seeing the updated data?
package main
import "fmt"
type Person struct {
name string
age string
}
func main() {
var people = make([]Person, 0)
fmt.Println(len(people))
getList(people)
fmt.Println(len(people))
}
func getList(people []Person) {
people = append(people, Person {"Foo", "1"})
people = append(people, Person {"Bar", "2"})
}
But this works. So its not actually a pass-by-reference
?
package main
import "fmt"
type Person struct {
name string
age string
}
func main() {
var people = make([]Person, 0)
fmt.Println(len(people))
people = getList(people)
fmt.Println(len(people))
}
func getList(people []Person) []Person {
people = append(people, Person {"Foo", "1"})
people = append(people, Person {"Bar", "2"})
return people
}
答案1
得分: 1
一个切片包含指向支持数组的指针、长度和容量。内置的append
函数返回一个新的切片,具有新的长度和可能指向重新分配的支持数组的新指针。
切片是按值传递的。在getList
函数中对切片的更改对调用者不可见。对支持数组的更改对调用者可见。
切片被称为引用类型,因为切片包含指向支持数组的指针。
英文:
A slice contains a pointer to the backing array, length and capacity. The append built-in returns a new slice with a new length and possibly a new pointer to a reallocated backing array.
Slices are passed by value. Changes to the slice in getList
are not visible in the caller. Changes to the backing array are visible to the caller.
A slice is called a reference type because a slice contains a pointer to the backing array.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论