Is there any use to embedding a built-in type other than error?

agolangf · · 300 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>It is legal to write</p> <pre><code>type T struct { int } </code></pre> <p>But is there any point to it or situation in which doing so could be useful? You can&#39;t access any of the type&#39;s built-in operations such as addition, and embedding is not inheritance so you can&#39;t assign a <code>T</code> to an <code>int</code>.</p> <p>Obviously, <code>error</code> is the exception because it has a method, so you will see it embedded fairly often.</p> <hr/>**评论:**<br/><br/>ratatask: <pre><p>There might be situations where you want to hide the implementation detail of your thing only being an int.</p> <p>You might want to disallow the usual arithmetic operations if they do not make sense for your type. If your struct T represents a &#34;house number&#34;, perhaps you don&#39;t want or need people to add or divide house numers.</p> <p>Otherwise, you are probably better off doing just</p> <pre><code>type T int </code></pre></pre>adonovan76: <pre><p>No, it is equivalent to <code>struct{int int}</code> because type <code>int</code> has neither fields nor methods. (Of course, <code>struct{int}</code> and <code>struct{int int}</code> are distinct types.)</p></pre>cs-guy: <pre><p>There doesn&#39;t seem to be much reason to do it. It <em>might</em> be useful when creating a type with a limited set of values (an enum) because unlike</p> <pre><code>type T int </code></pre> <p>the embedded form does not allow assignment of a constant without an explicit type conversion. This extra restriction on creating values of the enum type could prevent a bug, maybe, on occasion. See <a href="https://play.golang.org/p/v-1OMOrjaZ" rel="nofollow">https://play.golang.org/p/v-1OMOrjaZ</a></p></pre>

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

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