dsgixl5195 2018-12-07 20:22
浏览 38


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 {
  • 写回答

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.

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



    • ¥100 webapi的部署(标签-服务器)
    • ¥20 怎么加快手机软件内部计时的时间(关键词-日期时间)
    • ¥15 C语言除0问题的检测方法
    • ¥15 为什么四分管的内径有的是16mm有的15mm,四分不应该是12.7mm吗
    • ¥15 macos13下 ios交叉编译的问题
    • ¥15 bgz压缩文件怎么打开
    • ¥15 封装dll(引入了pcl的点云设计库)
    • ¥30 关于#开发语言#的问题:我需要在抄板的基础上再抄板抄程序,根据RDA8851CM基础上开发
    • ¥15 oracle 多个括号,怎么删除指定的括号及里面的内容?
    • ¥15 小新14API2019想用bios调风扇