Ask r/golang: what I do not understand about maps

agolangf · · 793 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I stumbled on something that I do not understand. I hope somebody here cares to explain. I created a small piece of test code on play.golang but the essence is below. I expected both situations to be identical, but its not ?</p> <pre><code> // test 1 f := &#34;test1&#34; d := detailsStruct{details: map[string]string{}} d.add(&#34;{}&#34;) // this works todo.list[f] = d // test 2 f = &#34;test2&#34; todo.list[f] = detailsStruct{details: map[string]string{}} todo.list[f].add(&#34;{}&#34;) // this gives runtime error </code></pre> <p>Basically there is a small difference between test1 and test2 in the sample code. In test1 the .add() works fine. For test2 I get a runtime error:</p> <pre><code>prog.go:30: cannot call pointer method on todo.list[f] prog.go:30: cannot take the address of todo.list[f] </code></pre> <p>Full example: <a href="http://play.golang.org/p/8D3-72mzsK">http://play.golang.org/p/8D3-72mzsK</a></p> <hr/>**评论:**<br/><br/>bbrazil: <pre><p><a href="http://stackoverflow.com/questions/13101298/calling-a-pointer-method-on-a-struct-in-a-map" rel="nofollow">http://stackoverflow.com/questions/13101298/calling-a-pointer-method-on-a-struct-in-a-map</a></p></pre>1Gijs: <pre><p>Yes, so it has a very clear explanation:</p> <p>&#39;A map indexing operation is not addressable. This was decided so that map implementations would not need to guarantee that the addresses of values would not change. As more data is added to the map, it may relocate data for efficiency reasons.&#39;</p></pre>yiyus: <pre><p><a href="http://play.golang.org/p/zov9m5OrXZ" rel="nofollow">http://play.golang.org/p/zov9m5OrXZ</a></p></pre>1Gijs: <pre><p>Thank you :-)</p></pre>mdmd136: <pre><p>That&#39;s a compile time error, not a runtime error</p></pre>1Gijs: <pre><p>True. With all the tools running on every save I come to expect that everything works after that from a compiler point of view. On top of that I use a script to to build and run in one command.</p></pre>mimighost: <pre><p>the value type of todo is a detailStruct struct, but the add method is declared its pointer type.</p> <p><a href="https://golang.org/ref/spec#Method_sets" rel="nofollow">https://golang.org/ref/spec#Method_sets</a></p></pre>

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

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