I don't understand why these pointers don't work as I'm expecting

xuanbao · · 398 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I am the most confused.</p> <p>I pass a pointer of an int to a function. I dereference it into another variable, increment variable and assign the address of that variable to the original pointer.</p> <p>But the change is lost.</p> <p><a href="https://play.golang.org/p/b5cAMv1hIG" rel="nofollow">https://play.golang.org/p/b5cAMv1hIG</a></p> <p>I have the dumb today and I don&#39;t see where this is failing</p> <p>*EDIT: I didn&#39;t understand pointers, I get it now. Thanks to <a href="/u/chrj" rel="nofollow">/u/chrj</a> </p> <hr/>**评论:**<br/><br/>janderssen: <pre><p>Also, you could simply do the following :</p> <pre><code>func alter(a *int) { *a++ } </code></pre> <p>Basically deferences the pointer to its value and increments it.</p></pre>chrj: <pre><p>Change the last line to:</p> <pre><code>*a = b </code></pre> <p>You want to change what <code>a</code> is pointing to.</p></pre>Smokey_Circles: <pre><p>Oh...</p> <p>I don&#39;t know why I thought I could change the address of the pointer. Evidently I hadn&#39;t internalised what was going on under the scenes of things like <code>json.Unmarshal</code> and it felt like I was re-assigning the address.</p> <p>Thanks though, this clears up a lot of uncertainties I had :) </p></pre>

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

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