If primitive types had methods, would we ever need generics?

polaris · · 543 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I find most of the boilerplate that generics would solve comes from the builtin types not having any methods.</p> <p>For example, if a map had Get and Delete methods, then we could implement our own map types and T[X] would just be syntactic sugar for T.Get(X).</p> <p>More usefully, if a slice implemented some Iteratable interface, and range would just call .Len and .Get on any slice, then we could implement our own slices.</p> <p>All the primitives, like string, int, etc should also have methods. Numbers should have &#34;Add&#34;, &#34;Compare&#34;, etc so we can write generic sorting algorithms and collections. </p> <p>Thoughts?</p> <hr/>**评论:**<br/><br/>szabba: <pre><p>You seem to confuse some things. If you had a compare method on the builtin ints they would satisfy something like <code>interface { Compare(int) int }</code>, whereas for strings the corresponding interface would be <code>interface { Compare(string) int }</code>. That doesn&#39;t let you write a function that sorts slices of both types - you&#39;d need to be able to specify something like <code>[T] interface { Compare(T) int }</code>.</p> <p>What you&#39;re proposing seems to be a form of operator overloading. It solves a different set of problems than generics, and does have it&#39;s drawbacks/trade-offs.</p></pre>haskell_suxor: <pre><p>If ranges supported Get, what would the type of the value that Get returned?</p></pre>egonelbre: <pre><p>There are several other cases that generics solve (<a href="https://docs.google.com/document/d/1vrAy9gMpMoS3uaVphB32uVXX4pi-HnNjkMEgyAHX4N4/edit#" rel="nofollow">see this</a>).</p></pre>

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

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