V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
hcyg

问个 Golang 的问题~~

  •  
  •   hcyg · Jan 11, 2020 · 4846 views
    This topic created in 2310 days ago, the information mentioned may be changed or developed.
    aData := make([]GateData,len(add))
    ArrayToStruct(add,aData) 
    

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

    10 replies    2020-01-12 09:17:23 +08:00
    joyme
        1
    joyme  
       Jan 11, 2020
    数组类型是比较特殊的,传参的话是数组的内存首地址,
    qingsonghe
        2
    qingsonghe  
       Jan 11, 2020   ❤️ 1
    是引用,但是如果切片在 ArrayToStruct 函数内增长,那么 ArrayToStruct 函数调用结束后,aData 指向的切片数据“不是最新的”
    qingsonghe
        3
    qingsonghe  
       Jan 11, 2020
    当然传指针当然是最保险的,可以防止切片在 ArrayToStruct 函数内部增长的问题。
    di1012
        4
    di1012  
       Jan 11, 2020
    @joyme 这个是切片吧,切片传参的确是地址传递。数组是值传递
    LancerEvo
        5
    LancerEvo  
       Jan 11, 2020 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  
       Jan 11, 2020
    @di1012 是切片。。。我说错了
    hcyg
        7
    hcyg  
    OP
       Jan 11, 2020
    感谢各位的解答~~
    cheneydog
        8
    cheneydog  
       Jan 11, 2020
    在 go 里数据传递就是拷贝吧,你的代码就是数组传递吧,所以代码错了吧,难道我哪里看错了?
    cheneydog
        9
    cheneydog  
       Jan 11, 2020
    确实是切片,糊涂了。
    alexliux
        10
    alexliux  
       Jan 12, 2020 via Android
    不推荐这样搞。另外,go 没有引用,只有值传递
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3051 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 545ms · UTC 14:14 · PVG 22:14 · LAX 07:14 · JFK 10:14
    ♥ Do have faith in what you're doing.