<p>Hi,
I'm having a hard time wrapping my head around pointers, I understand the theory about passing memory addresses and referencing the data in the address.</p>
<p>The issue comes with the syntax, mainly with the & and declaring variables. I.e.</p>
<pre><code>joe := &person{ Name: "Joe", Age: 20, }
fmt.Println(joe.Name) //Works if struct defined with &
john := person{ Name: "John", Age: 24, }
fmt.Println(john.Name) //Works if struct defined without &
</code></pre>
<p>I just don't understand how you can declare a struct with & in the front of it and just reference it as normal (joe.Name). Doesn't & say you want to store the address not the actual value?</p>
<p>Does Go just know when it needs to pass the address vs when to pass the value? I guess when you define methods you explicitly say you are expecting a pointer with *.</p>
<hr/>**评论:**<br/><br/>matryer: <pre><p>Go automatically looks up what pointers are pointing to. So <code>joe.Name</code> looks up the struct that the <code>joe</code> pointer is pointing to, and then gets the <code>Name</code>. For <code>john</code>, it goes straight to the <code>Name</code>.</p>
<p>In C++, I think you did <code>joe->Name</code> for pointers, and <code>john.Name</code> for values... but in Go, they're both dot.</p></pre>traitoriroh: <pre><p>Ohh, yeah I just got confused trying to compare it to C++/C. </p>
<p>Thank you</p></pre>ardanstudios: <pre><p>Read this series. </p>
<p><a href="https://www.goinggo.net/2017/05/language-mechanics-on-stacks-and-pointers.html" rel="nofollow">https://www.goinggo.net/2017/05/language-mechanics-on-stacks-and-pointers.html</a></p></pre>matryer: <pre><p>You decide whether you take a pointer or a struct in the signature.</p>
<p>So <code>func (p *Person)</code> takes a pointer, but <code>func (p Person)</code> copies the whole struct.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传