Go 中的接口到底是如何工作的?
在阅读了规范以及其中的“Effective Go”部分之后,我仍然不太明白 Go 中的接口是如何工作的。
比如,你在哪里定义它们?接口执行如何工作?有没有一种方法可以在某个地方指定对象实现接口,而不是简单地在接口中定义方法?
对初学者的问题表示歉意;但我真的很难理解这一点。
After reading the spec, and the "Effective Go" section on them, I still don't quite understand how interfaces work in Go.
Like, where do you define them? How does interface enforcement work? And is there a way to specify somewhere that an object implements an interface, as opposed to simply defining the methods in the interface?
Apologies for the beginner question; but I really am struggling to understand this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Russ Cox 和 Ian Lance Taylor 的 博客,我建议您查看一下。他们可能会涵盖您的问题等等......
我认为一个很好的概念性示例是 net包裹。在那里你会找到一个连接接口(Conn),它是由 TCPConn 实现,UnixConn 和 UDPConn 。 Go pkg 源代码可能是 Go 语言的最佳文档。
There are some good posts on interfaces over at Russ Cox and Ian Lance Taylor's blog which i recommend checking out. They'll probably cover your questions and more ...
I think a good conceptual example is the net package. There you'll find a connections interface(Conn), which is implemented by the TCPConn, the UnixConn, and the UDPConn. The Go pkg source is probably the best documentation for the Go language.
基本上,您定义一个这样的接口:
该特定接口定义要求任何实现该接口的方法都具有采用 2 个参数的
MethodA
方法和采用 2 个参数的MethodB
方法。 1 论证。一旦你定义了它,当你尝试使用需要特定接口的东西时,Go 会自动检查你正在使用的东西是否满足该接口。您不必明确声明给定的事物满足给定的接口,当您尝试在预期满足该接口的场景中使用某些事物时,它只会自动检查。
Basically, you define an interface like this:
That particular interface definition requires anything which implements the interface to have both a
MethodA
method that takes 2 arguments, and aMethodB
method that takes 1 argument.Once you've defined it, Go will automatically check when you try to use something where a certain interface is required, whether the thing you're using satisfies that interface. You don't have to explicitly state that a given thing satisfies a given interface, it's just automatically checked when you try to utilize something in a scenario where it's expected to satisfy it.