Any consequences to wrapping simple data types in a struct?

blov · · 407 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Here&#39;s the scenario: I&#39;m defining an type for a function that I want to pass into another function. This type is called Worker. Currently, a Worker function accepts a single argument that is a byte slice.</p> <p>Now, as we know, thing change over time, so I&#39;m thinking that if I create a new type that, for now, is a struct that just contains a byte slice. Now, this lets me add additional fields in the future without having to change the implementation of functions. However, I don&#39;t know if this will happen, so I won&#39;t want to cause any stupid little issues by doing this. I don&#39;t think performance will be an issue or it will at least be minimal.</p> <p>Any other potential gotchas that I&#39;m not thinking of?</p> <hr/>**评论:**<br/><br/>ammarbandukwala: <pre><p>If you&#39;re passing around this struct by value, there will be zero difference in performance from passing around just the <code>[]byte</code></p> <p>Structs contain no special data in addition to their members when represented in memory, so the wrapper struct with a single <code>[]byte</code> is for performance sake equivalent to a pure <code>[]byte</code></p></pre>sybrandy: <pre><p>Thanks. That&#39;s what I thought. I just had one of those nagging feelings that I may be missing something.</p></pre>adonovan76: <pre><p>Even if you don&#39;t add fields in future, the struct may serve as an encapsulation mechanism because it hides the representation of its unexported fields from clients&#39; prying eyes.</p></pre>sybrandy: <pre><p>Understood and fully agree. In this case, it&#39;s just a message being passed between goroutines, so I&#39;m not concerned about that at the moment.</p></pre>

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

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