Why is the content of slice not changed in GO?

不问归期 提交于 2019-12-01 19:47:56

问题


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)
}

The result printed is:

[0] [0 1] [0]

while I was expecting

[0] [0 1] [0 1]


回答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.

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.




回答2:


Go is always pass by value. Certain types are reference types, like pointers, maps, channels; or partially reference types, like slices (which consists of a reference to the underlying array and also the values of the length and capacity). But regardless of type everything is passed by value. Thus assigning to a local variable never affects anything outside.



来源:https://stackoverflow.com/questions/12274167/why-is-the-content-of-slice-not-changed-in-go

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!