dsgixl5195 2018-12-07 20:22
浏览 38
已采纳

Golang用于范围指针

I'm new to Golang and I recently had the same problem as described in this question: Strange golang "append" behavior

So I'm wondering if it's basically never appropriate to use the object copy in the for range loop in anything outside of the scope of that loop– like passing it to a separate function, appending it (as described in the question), and so on.

Is it almost always more appropriate to access an object like this if you plan on mutating it, adding it to a list outside of the scope of that loop, and so on, because on the next loop the pointer you added will change?

for index := range myList {
    doSomething(&myList[index])
}
  • 写回答

1条回答 默认 最新

  • dongpai6552 2018-12-07 20:40
    关注

    You mostly need to keep in mind that Go is pass by value. IF you are perfectly ok using a copy, fully understanding that mutations won't reflect, and that copies of huge structs can be costly, there are perfectly valid reasons for passing either a copy or a pointer.

    If you need to make modifications, either pass by reference as you show here, or you can also store them as pointers in the slice to start with e.g. []*MyStruct. Actually, that brings to light a design choice where they chose specifically in the spec to pass a struct by copying.

    Under the covers, a slice abstracts an array, but is merely a struct, known as a slice header, with a pointer to the array. When you pass a slice around, the header is passed by value, but the contents basically consist of 3 integers, so it's not expensive to copy it. This is the reason you have to reassign the variable when using append for it to persist, e.g. s = append(s, value). You can pass a slice around in your code by reference, but doing so isn't idiomatic Go.

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

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题