[Update] Ok. Again, Why I cannot mutate a slice inside another function?

xuanbao · 2016-04-26 03:36:22 · 497 次点击    
这是一个分享于 2016-04-26 03:36:22 的资源,其中的信息可能已经有所发展或是发生改变。

On the code I'm working on I'm experiencing this behavior where I mutate the element of a Struct and the element seems changed but the value of the element changed, in the struct, is not!

I'm obviously missing something as I assumed that iterating over the element of the structure mutating it, the structure will reflect this as well. Is Go copying the element of the structure and passing it's value to my function, which in turn mutates the copy and not the original, right?

Worst thing is that I have to run the function that mutates the element of the structure concurrently, I'm afraid that what I want to achieve is possible but only it wouldn't be "thread safe".

If you down vote this post, please explain at least why. Thank you!


评论:

binaryblade:

because the local in the for loop is a copy of the object in your slice of slices. When you modify the copy it does not modify the object in your slice of slices

edit: here

shackra:

Silly me, thank you!

bscharm:

when performing range you are working with a copy of the values from your struct Prueba. you can see this by logging the address of n versus the address of p.Lista[i] where i is the current index in your iteration.

shackra:

ah! my suspicion was confirmed then, thanks!

tgulacsi:

See https://play.golang.org/p/K6o7gT5YfB What do you write concurrently?


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

497 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传