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 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集