interface vs struct with the function pointers

blov · · 332 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Probably a noobie question. What are the differences between an interface and a struct with function pointers? They look the same to me.</p> <hr/>**评论:**<br/><br/>arrans: <pre><p>TL;DR the struct approach would result in spaghetti code, be more error prone, and require implementing logic that is essentially already handled by the compiler.</p> <p>Although you could probably achieve almost the same outcome with both, the struct approach will end up being more cumbersome. In addition to having to piece together your function-pointer-holding structs rather than simply passing a value, it won&#39;t play nicely with all of the existing Go infrastructure (other packages, standard library...).</p> <p>There will also be a decoupling of values from methods so you&#39;d have to figure out, for example, some sort of closure approach whereby each function contains a pointer to the value with which it&#39;s associated. These are things that are handled by the language rather than the engineer so don&#39;t reinvent the wheel.</p> <p>You also won&#39;t be able to use type switches with the struct approach.</p> <p>As for what&#39;s happening under the hood, this isn&#39;t something I&#39;m familiar with but would guess that it would be much less efficient even if negligibly so for most intents and purposes.</p></pre>chewxy: <pre><p>An interface is a struct with 2 fields. The first field is typically implemented as a pointer to the table of function pointers. The second field typically points to the data. </p> <p>In a way, you are correct, that structurally they are similar. But semantically, interfaces are checked at compile time. This gives the compiler the ability to tell you that something is not right (for example, your types that do not fulfil an interface)</p></pre>

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

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