Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于切片作为函数参数有一点问题 #3

Closed
FelixSeptem opened this issue Jun 12, 2019 · 4 comments
Closed

关于切片作为函数参数有一点问题 #3

FelixSeptem opened this issue Jun 12, 2019 · 4 comments

Comments

@FelixSeptem
Copy link
Contributor

https://github.com/qcrao/Go-Questions/blob/master/%E6%95%B0%E7%BB%84%E5%92%8C%E5%88%87%E7%89%87/%E5%88%87%E7%89%87%E4%BD%9C%E4%B8%BA%E5%87%BD%E6%95%B0%E5%8F%82%E6%95%B0.md
这里第一段代码给出的例子里,f函数内部对元素的+1影响到了外部的s,这是什么原因?不是很理解

@fguby
Copy link

fguby commented Jun 12, 2019

Slice这个结构体其实只有三个字段,指向底层数组元素的指针,len,cap,函数参数传递虽然是值传递,但实际操作的还是底层的数组元素,所以在f函数里的操作才会看起来像影响到了外部吧,个人理解。

@FelixSeptem
Copy link
Contributor Author

似乎理解了,在函数内部的是s的一个副本,底层指向是同一个array,所以修改赋值会影响到其他slice,如果只修改则不会影响 https://play.golang.org/p/M8BHj_fE0D3

@qcrao
Copy link
Member

qcrao commented Jun 12, 2019

似乎理解了,在函数内部的是s的一个副本,底层指向是同一个array,所以修改赋值会影响到其他slice,如果只修改则不会影响 https://play.golang.org/p/M8BHj_fE0D3

对的

@FelixSeptem
Copy link
Contributor Author

问题解决

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants