Question: Some help with pointers & structs

xuanbao · · 373 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hi, I&#39;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 &amp; and declaring variables. I.e.</p> <pre><code>joe := &amp;person{ Name: &#34;Joe&#34;, Age: 20, } fmt.Println(joe.Name) //Works if struct defined with &amp; john := person{ Name: &#34;John&#34;, Age: 24, } fmt.Println(john.Name) //Works if struct defined without &amp; </code></pre> <p>I just don&#39;t understand how you can declare a struct with &amp; in the front of it and just reference it as normal (joe.Name). Doesn&#39;t &amp; 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-&gt;Name</code> for pointers, and <code>john.Name</code> for values... but in Go, they&#39;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

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