dsdukbc60905239 2018-01-05 18:27
浏览 41
已采纳

将切片传递给函数

I have some confusion regarding passign slices to function. Here is what I have readed:

enter image description here

Here are what I have understood: slice is a structure with a pointer to real data; when we are passing a slice to a function, we just copy a pointer, but the function is working with the same data as original function.

Here is my code:

type Example struct {
    A int
    B string
}

func foo(d []Example) {
    for _, e := range d {
        e.B = "bye"
    }
}

func main() {

    a := Example{}
    a.A = 10
    a.B = "hello"

    b := Example{}
    b.A = 10
    b.B = "hello"

    var c []Example
    c = append(c, a)
    c = append(c, b)

    foo(c)

    for _, e := range c {
        fmt.Println(e.B)
    }
}

I have passed slice of structs to a function and have changed the struct in the function. Why I have old values in the main function ?

  • 写回答

1条回答 默认 最新

  • douzhan8303 2018-01-05 18:29
    关注

    Because it's a slice of structs, not a slice of pointers to structs. When you execute:

    for _, e := range d
    

    Inside the loop, e is a copy of the element from the slice; modifying it does not modify what's in the slice. If d were a []*Example, it would work as you expected: https://play.golang.org/p/4ZgLETpq6d0

    Note in particular that this has nothing at all to do with slices. If it were:

    func foo(d Example) {
        d.B = "bye"
    }
    

    You would run into the same problem: the function is modifying a copy of the struct, so the caller's copy is unaffected by what happens inside the function.

    Another potential solution without using pointers would be to modify the values inside the slice, rather than in a copy of the element:

    func foo(d []Example) {
        for i := range d {
            d[i].B = "bye"
        }
    }
    

    Working example of this style: https://play.golang.org/p/_UJGU0XqaUO

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于c语言代码的问题
  • ¥15 c51单片机控制步进电机
  • ¥20 Visual studio无法检测到设备
  • ¥15 为什么我通过html绘制的SVG折线图插入到word中坐标轴不显示出来
  • ¥30 vue 页面窗口放大或者缩小元素会变化
  • ¥15 questasim仿真报错
  • ¥15 寻找电脑攻防的导师,有问题请教一下。
  • ¥20 微信同是win11,我的电脑安装不了pageoffice,一直无法打开
  • ¥15 这个界面我通过postman请求不到,但是通过浏览器可以正常访问
  • ¥15 多目标优化算法在与其他算法数据对比结果判断