<p>Hi !
Just wanted to share how i hate that any type matches interface{}, but as soon as you go a bit more complex it doesn't.
Example:</p>
<pre><code>func() <whatever_type>
</code></pre>
<p>doesn't match</p>
<pre><code>func() interface{}
</code></pre>
<hr/>**评论:**<br/><br/>singron: <pre><p>It's called <a href="https://en.m.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)" rel="nofollow">Covarience</a>, and yes go doesn't have it. </p></pre>natefinch: <pre><p><a href="https://npf.io/2014/05/intro-to-go-interfaces/#interfaces-are-types" rel="nofollow">https://npf.io/2014/05/intro-to-go-interfaces/#interfaces-are-types</a></p>
<blockquote>
<p>Interfaces are types, just like string is a type or Camel is a type. They aren’t aliases, they’re not magic hand-waving, they’re real types and real values which are distinct from the type and value that gets assigned to them.</p>
</blockquote>
<p>The problem most newbies have is that they think of interfaces as pattern matching, but they're not. They're types. Go helps you out by doing some auto-wrapping of values that get assigned to interfaces, but <code>func interface{}</code> is not an interface itself. It's a function type. </p></pre>dilap: <pre><p>The way code has to handle and call for example</p>
<pre><code>func() [20]int
</code></pre>
<p>is different than how it has to handle and call</p>
<pre><code>func() interface{}
</code></pre>
<p>The amount and type of data being returned is different. Code that is expecting an interface{} cannot just be straight-up handed a [20]int, it needs some wrapping to happen.</p>
<p>You could imagine a language that does something fancy and automatically creates a small adapter function for you when you assign the former to the latter, but Go doesn't try to be fancy, it tries to be simple.</p>
<p>Of course, you can always do it yourself easily:</p>
<pre><code>func() interface{} { return someConcreteFunc() }
</code></pre></pre>hell_0n_wheel: <pre><blockquote>
<p>Just wanted to share how i hate</p>
</blockquote>
<p>Internet is chock full of hate. Don't need your help adding to it, thanks.</p>
<p>If there's something you don't understand, how about you ask a question, instead of getting all "incomfortable" about it?</p></pre>Loves_Portishead: <pre><p>I'm sleep deprived right now, but what's your point? I don't get it...?</p></pre>kardianos: <pre><p>There is no inheritance in Go, thus <whatever_type> cannot "descend" from interface. Go requires types to match.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传