Can someone explain interfaces?

agolangf · · 424 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Im a hobbyist programmer and so sometimes I don&#39;t understand the usefulness and use-cases of things. In this instance, interfaces. Can someone take a stab at making me understand what they&#39;re good for and maybe examples of realworld use cases?</p> <hr/>**评论:**<br/><br/>mm256: <pre><p>A Go newbie here. Does not &#34;interface{}&#34; looks like a bit like &#34;void*&#34; in C language? I see a interface{} as a generic code workaround, useful but dangerous as a fare for use. </p> <p>Please, I&#39;m not criticism the feature, this is not my intention. I&#39;m probably wrong and sure there is an eloquent explanation.</p></pre>atamiri: <pre><p>Well, you are right that interface{} might be &#34;dangerous&#34; since you need a type assertion in order to convert a variable back into what it really is and access its properties and methods. But the typical (and intended) use of interfaces is to declare methods an object provides. The interfaces Reader and Writer, for example, declare the methods Read and Write respectively, and any object providing them can be used as a &#34;reader&#34; or &#34;writer&#34; because it implements the required interface(s). If an object doesn&#39;t implement an interface, it can&#39;t be used in that context and if you try you get a compile-time error (whereas type assertions cause runtime errors if they fail).</p></pre>SteveMcQwark: <pre><p>It&#39;s not &#34;dangerous&#34; in the way a <code>void *</code> is. The danger of a <code>void *</code> is that you have to cast it to a concrete type in order to do anything with it other than pass it around, and there&#39;s no enforcement at compile or run time that you&#39;re casting it to the correct type. This can lead to accessing memory incorrectly, causing difficult to diagnose bugs and security vulnerabilities. With <code>interface{}</code>, you use a type assertion or type switch to extract the value. Worst case, your program panics because you unconditionally asserted the wrong type. At no point are you able to improperly access memory.</p> <p>Also, the question is about interfaces in general, not just empty interfaces (<code>interface{}</code>). Methods allow your code to interact meaningfully with any type of value which satisfies the interface, rather than only certain specific types.</p></pre>joncalhoun: <pre><p>The thread linked likely has some good resources so I would check it out. I also have written about this in a past. It is a rather lengthy subject so rewriting it all here would be tricky so I am just going to leave the link. <a href="https://www.calhoun.io/how-do-interfaces-work-in-go/" rel="nofollow">https://www.calhoun.io/how-do-interfaces-work-in-go/</a></p></pre>dm319: <pre><p>I will give this a go (no pun intended) as I am also a hobbyist and this only just clicked...</p> <p>So <a href="https://www.youtube.com/watch?v=XE4VP_8Y0BU" rel="nofollow">sorting</a> data seems to be actually quite a big deal in computing (it&#39;s used a lot in software for lots of different reasons) and there are lots of ways to perform it - some are faster than others, but some require quite a bit of programming to achieve (see heap sort).</p> <p>So I was trying to solve a maths/programming <a href="https://projecteuler.net/" rel="nofollow">puzzle</a> recently, and to help me solve it, I wanted to sort some interim results so I could see more clearly what was going on. Problem was that I&#39;d create a structure that described the sides of a hexagon (i.e. how long they were), as well as holding the perimeter. I wanted to sort by perimeter.</p> <p>So the sort package has a sort interface. To implement the sort interface your type (i.e. my hexagon) needs to be able to return to it - how many items need sorting, how to swap two items around and how to measure which is larger.</p> <p>So I made sure that I satisfied those methods, and voila! it was very easy to use Go&#39;s optimised sorting method on my data.</p> <p>To summarise: If you have some code that takes a substantial amount of time to write which does a specific job that can be generalised, then interfaces allow you to use that code and apply it to different situations.</p> <p>Without an interface, you would need to have your data stored in a way that the sort package could understand. And then if you wanted to use another package, you might have to rearrange the data to use it. Failing that, you&#39;d simply have to write your own functions/package for your own data.</p></pre>driusan: <pre><p>interfaces are Go&#39;s way of achieving polymorphism. As a hobbyist, are you familiar with OOP programming?</p> <p>If so, imagine a case where you would extend a class and override a method from the parent class. interfaces are how you would accomplish the same thing in Go, where there is no class hierarchy.</p></pre>jimijiim: <pre><p>An interface is just a contract.</p> <pre><code>type Reader interface { Read() } func AcceptReader(r Reader){ r.Read() } </code></pre> <p>means than AcceptReader will accept any value as argument that has a Read() method associated with it.</p> <p>you can now accept different implementations of reader</p> <pre><code>type ReaderA struct {} func(r ReaderA)Read(){ print(&#34;reader A&#34;)} type ReaderB struct {} func(r ReaderB) Read(){ print(&#34;reader B&#34;)} </code></pre> <p>both ReaderA and ReaderB values can be passed to AcceptReader as argument. It is called polymorphis .</p> <p>What the point? the point is the same as when you write functions, code reuse. </p> <p>Whatever logic contained in AcceptReader is self contained and the Read() method can take many forms.</p></pre>Sythe2o0: <pre><p>I&#39;ve given an answer to this before, so I&#39;ll link you to where I (and several others) answered a similar question: <a href="https://www.reddit.com/r/golang/comments/56lj2v/yet_another_confused_gopher_about_interfaces/" rel="nofollow">https://www.reddit.com/r/golang/comments/56lj2v/yet_another_confused_gopher_about_interfaces/</a></p></pre>

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

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