Explanation on struct pointer assignment

polaris · · 311 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Just wondering why assigning pointers works this way.</p> <p>If you pass a struct pointer to a function, and the function modifies an individual value of the struct (i.e. Person.Name), the struct itself is updated in the parent calling function.</p> <p>However, if you create and assign a new pointer of the same struct type to the passed pointer in that function, the parent calling function does not receive the updated pointer. The only way to solve this seems to dereference both in assignment.</p> <p>See these examples:</p> <p>New pointer assigned without dereference: <a href="http://play.golang.org/p/DoUKsZ2wGQ">http://play.golang.org/p/DoUKsZ2wGQ</a></p> <p>New pointer assigned with dereference: <a href="http://play.golang.org/p/Ikc0LRsc_o">http://play.golang.org/p/Ikc0LRsc_o</a></p> <p>Is this because while you don&#39;t have to dereference a struct pointer to use one of is values, it is actually happening behind the scenes (as if you used an individual variable and had to dereference it), so the dereference here on the pointer keeps the pointer but changes its actual value? What&#39;s happening when the dereference is left out?</p> <hr/>**评论:**<br/><br/>bonafidebob: <pre><p>Arguments in go are passed by value, so the argument is a copy of the pointer itself. Changing p makes the copy point to something new, but doesn&#39;t change what the caller&#39;s pointer references.</p> <p>On the other hand, when you dereference the pointer in the function you&#39;re explicitly modifying the thing the pointer points to. Since both the caller and the function&#39;s pointer point to the same object, naturally the caller also sees the change.</p></pre>beeker1121: <pre><p>Ok that makes sense, thank you!</p></pre>

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

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