V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
hcyg
V2EX  ›  Go 编程语言

问个 Golang 的问题~~

  •  
  •   hcyg · 2020-01-11 14:43:12 +08:00 · 3876 次点击
    这是一个创建于 1538 天前的主题,其中的信息可能已经有所发展或是发生改变。
    aData := make([]GateData,len(add))
    ArrayToStruct(add,aData) 
    

    这个是引用的吗。。不用接收返回值,aData 就变了

    10 条回复    2020-01-12 09:17:23 +08:00
    joyme
        1
    joyme  
       2020-01-11 14:59:39 +08:00
    数组类型是比较特殊的,传参的话是数组的内存首地址,
    qingsonghe
        2
    qingsonghe  
       2020-01-11 14:59:49 +08:00   ❤️ 1
    是引用,但是如果切片在 ArrayToStruct 函数内增长,那么 ArrayToStruct 函数调用结束后,aData 指向的切片数据“不是最新的”
    qingsonghe
        3
    qingsonghe  
       2020-01-11 15:01:46 +08:00
    当然传指针当然是最保险的,可以防止切片在 ArrayToStruct 函数内部增长的问题。
    di1012
        4
    di1012  
       2020-01-11 15:10:07 +08:00
    @joyme 这个是切片吧,切片传参的确是地址传递。数组是值传递
    LancerEvo
        5
    LancerEvo  
       2020-01-11 15:17:57 +08:00 via iPhone
    This is slice not array, and this is how slice looks:

    type slice struct {
    Length int
    Capacity int
    ZerothElement *byte
    }

    A slice contains the length, capacity and a pointer to the zeroth element of the array. When a slice is passed to a function, even though it's passed by value, the pointer variable will refer to the same underlying array. Hence when a slice is passed to a function as parameter, changes made inside the function are visible outside the function too.
    joyme
        6
    joyme  
       2020-01-11 15:39:56 +08:00
    @di1012 是切片。。。我说错了
    hcyg
        7
    hcyg  
    OP
       2020-01-11 15:40:24 +08:00
    感谢各位的解答~~
    cheneydog
        8
    cheneydog  
       2020-01-11 15:53:06 +08:00
    在 go 里数据传递就是拷贝吧,你的代码就是数组传递吧,所以代码错了吧,难道我哪里看错了?
    cheneydog
        9
    cheneydog  
       2020-01-11 15:55:41 +08:00
    确实是切片,糊涂了。
    alexliux
        10
    alexliux  
       2020-01-12 09:17:23 +08:00 via Android
    不推荐这样搞。另外,go 没有引用,只有值传递
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3347 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 13:38 · PVG 21:38 · LAX 06:38 · JFK 09:38
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.