<p>I'm sure there's gotta be some golang spec or design explanation somewhere, but it seems as if it doesn't matter if I call a method with the data struct directly or if it'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's not the question here. I understand that part just fine. I'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'm the first golang user who is unhappy when something works. Actually, I'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 &x's method set contains m, x.m() is shorthand for(&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
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传