(Newb Question) Why do you return the address of a struct when it is a struct literal in the function return argument?

xuanbao · · 314 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Here&#39;s an example of what I mean:</p> <pre><code>type person struct { name string age int } func example() *person { return &amp;person{&#34;Frank&#34;, 15} } func main() { frank := example() fmt.Println(frank.name) } </code></pre> <p>So what I mean is why would the function have *person (literal), when you are returning &amp;person (address).</p> <p>Edit:</p> <p>Furthermore, when changed to this code:</p> <pre><code>func example() *person { p := &amp;person{&#34;Frank&#34;, 15} fmt.Printf(&#34;%x\n&#34;, p) fmt.Printf(&#34;%v\n&#34;, *p) return p } </code></pre> <p>The output is:</p> <pre><code>&amp;{4672616e6b f} {Frank 15} Frank </code></pre> <p>The pointer being returned CLEARLY does not equal the struct literal when using *p, (effectively *(&amp;person{&#34;Frank&#34;, 15}).</p> <hr/>**评论:**<br/><br/>gtarget: <pre><p>The syntax <code>*person</code> means a pointer to a <code>person</code>. When you return <code>&amp;person{&#34;Frank&#34;, 15}</code> you are saying return the address of the struct <code>person</code> you just created. A pointer is really just a variable holding the address of something else.</p></pre>Franke123: <pre><p>Got it! That makes sense now :) Thank you.</p></pre>dmikalova: <pre><p>Thanks, that cleared things up for me too.</p></pre>DualRearWheels: <pre><p>Quick tip: why would anyone use pointers anyway? 2 reasons:</p> <ol> <li><p>You can change struct using pointer from any place (loops, other functions etc.)</p></li> <li><p>Performance difference can be huge compared to not using pointer. With pointer program only copies address (4 or 8 bytes depending on your architecture). With struct as value program must copy much more (sum of all sizes of all fields, this can go to 100+ bytes depending on fields).</p></li> </ol></pre>Franke123: <pre><p>Thanks! As a pretty new programmer who learned JS first, pointers can be kind of confusing! But I do see the advantages.</p></pre>

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

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