one thing in Go that makes me incomfortable most of all

xuanbao · · 528 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<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&#39;t. Example:</p> <pre><code>func() &lt;whatever_type&gt; </code></pre> <p>doesn&#39;t match</p> <pre><code>func() interface{} </code></pre> <hr/>**评论:**<br/><br/>singron: <pre><p>It&#39;s called <a href="https://en.m.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)" rel="nofollow">Covarience</a>, and yes go doesn&#39;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&#39;re not. They&#39;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&#39;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&#39;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&#39;t need your help adding to it, thanks.</p> <p>If there&#39;s something you don&#39;t understand, how about you ask a question, instead of getting all &#34;incomfortable&#34; about it?</p></pre>Loves_Portishead: <pre><p>I&#39;m sleep deprived right now, but what&#39;s your point? I don&#39;t get it...?</p></pre>kardianos: <pre><p>There is no inheritance in Go, thus &lt;whatever_type&gt; cannot &#34;descend&#34; from interface. Go requires types to match.</p></pre>

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

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