英文:
How exactly do interfaces work in 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.
答案1
得分: 4
在Russ Cox和Ian Lance Taylor's的博客上有一些关于接口的好文章,我建议你去看一下。它们可能会回答你的问题,还有更多...
我认为一个很好的概念性例子是net包。在那里你会找到一个连接接口(Conn),它由TCPConn、UnixConn和UDPConn实现。Go语言的包源代码可能是最好的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
得分: 3
基本上,你可以像这样定义一个接口:
type InterfaceNameHere interface {
MethodA(*arg1, *arg2)
MethodB(*arg3)
}
这个特定的接口定义要求实现该接口的任何东西都必须有一个接受2个参数的MethodA
方法和一个接受1个参数的MethodB
方法。
一旦你定义了它,当你尝试使用某个需要特定接口的东西时,Go会自动检查你使用的东西是否满足该接口。你不需要明确声明某个东西满足某个接口,当你尝试在期望满足该接口的情况下使用某个东西时,它会自动进行检查。
英文:
Basically, you define an interface like this:
type InterfaceNameHere interface {
MethodA(*arg1, *arg2)
MethodB(*arg3)
}
That particular interface definition requires anything which implements the interface to have both a MethodA
method that takes 2 arguments, and a MethodB
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论