问个 Golang 的问题~~

2020 年 1 月 11 日
 hcyg
aData := make([]GateData,len(add))
ArrayToStruct(add,aData) 

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

5323 次点击
所在节点    Go 编程语言
10 条回复
joyme
2020 年 1 月 11 日
数组类型是比较特殊的,传参的话是数组的内存首地址,
qingsonghe
2020 年 1 月 11 日
是引用,但是如果切片在 ArrayToStruct 函数内增长,那么 ArrayToStruct 函数调用结束后,aData 指向的切片数据“不是最新的”
qingsonghe
2020 年 1 月 11 日
当然传指针当然是最保险的,可以防止切片在 ArrayToStruct 函数内部增长的问题。
di1012
2020 年 1 月 11 日
@joyme 这个是切片吧,切片传参的确是地址传递。数组是值传递
LancerEvo
2020 年 1 月 11 日
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
2020 年 1 月 11 日
@di1012 是切片。。。我说错了
hcyg
2020 年 1 月 11 日
感谢各位的解答~~
cheneydog
2020 年 1 月 11 日
在 go 里数据传递就是拷贝吧,你的代码就是数组传递吧,所以代码错了吧,难道我哪里看错了?
cheneydog
2020 年 1 月 11 日
确实是切片,糊涂了。
alexliux
2020 年 1 月 12 日
不推荐这样搞。另外,go 没有引用,只有值传递

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://v2ex.ih06.com/t/637078

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX