Go中接口是如何工作的?

huangapple go评论66阅读模式
英文:

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 CoxIan Lance Taylor's的博客上有一些关于接口的好文章,我建议你去看一下。它们可能会回答你的问题,还有更多...

我认为一个很好的概念性例子是net包。在那里你会找到一个连接接口(Conn),它由TCPConnUnixConnUDPConn实现。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.

huangapple
  • 本文由 发表于 2010年6月27日 14:44:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/3126605.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定