Question about Go pointers

agolangf · · 413 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>If I change a map field of a struct in a method, should I use a pointer or a non-pointer receiver?</p> <pre><code>type Bot struct { Callbacks map[string]func() } func NewBot() Bot { return Bot{ Callbacks: make(map[string]func()), } } func (bot Bot) On(event string, callback func()) { bot.Callbacks[event] = callback } </code></pre> <p>If I use a pointer receiver, then I should change all methods to use pointers right? Thanks for help.</p> <hr/>**评论:**<br/><br/>Bake_Jailey: <pre><p>It won&#39;t matter. Maps are already reference types, just pointers to some header and data elsewhere in memory. If you wanted to reassign the map to a completely different map, then you&#39;d have to use a pointer receiver.</p> <p>That being said, you may end up needing a mutex for that map, which may require you to use a pointer receiver depending on if you choose to put the mutex or a pointer to the mutex in the struct. I would personally put the mutex in the struct (zero value), then use a pointer receiver.</p></pre>frodsan: <pre><p>Thanks for response. Do I need to use a mutex when I plan to use the method on the main function?</p> <pre><code>func main() { bot := NewBot() bot.on(&#34;message&#34;, func() { // .... }) } </code></pre></pre>basically_asleep: <pre><p>Not if you just use it like that. Only if you plan to use it from multiple goroutines.</p></pre>jerf: <pre><p>You can be even more specific, as far as I know. It&#39;s only if you plan on reading and writing from multiple goroutines simultaneously. I fairly frequently have a map that I construct in one goroutine, then &#34;freeze&#34;, which means it can be read by anybody freely but they can&#39;t write to it safely. (Generally a good idea to use private methods here rather than making the map public, to help enforce that.)</p></pre>

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

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