<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't access any of the type's built-in operations such as addition, and embedding is not inheritance so you can'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 "house number", perhaps you don'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'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
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传