Lookup by value or by reference makes no difference

agolangf · · 453 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I&#39;m sure there&#39;s gotta be some golang spec or design explanation somewhere, but it seems as if it doesn&#39;t matter if I call a method with the data struct directly or if it&#39;s a pointer... I know that if I modify things, it needs to be the pointer if I want to change the original object, but that&#39;s not the question here. I understand that part just fine. I&#39;ve explained this badly, so here is an example:</p> <p><a href="https://play.golang.org/p/crgezmdAXY">https://play.golang.org/p/crgezmdAXY</a></p> <p>Why does this work? Why <em>should</em> it work? I guess I&#39;m the first golang user who is unhappy when something works. Actually, I&#39;m not unhappy, but I would like to understand the why.</p> <p>Thanks!</p> <hr/>**评论:**<br/><br/>ctcherry: <pre><p><a href="https://golang.org/ref/spec#Calls">https://golang.org/ref/spec#Calls</a></p> <p>A method call x.m() is valid if the method set of (the type of) x contains m and the argument list can be assigned to the parameter list of m. If x is addressable and &amp;x&#39;s method set contains m, x.m() is shorthand for(&amp;x).m()</p></pre>singron: <pre><p>See <a href="https://golang.org/doc/effective_go.html#pointers_vs_values">https://golang.org/doc/effective_go.html#pointers_vs_values</a></p> <p>The gist is that Go will convert from a pointer to a value to call a method with a value receiver. It will also covert the other way if the value is addressable.</p></pre>sandokan1572: <pre><p>It will make a difference once you start changing the receiver. It also makes a difference when considering whether given type implements an interface.</p></pre>

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

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