你能解释一下Go语言的接口吗?

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

Can you explain Go Interfaces?

问题

我不太理解整个类型+接口模型(它取代了其他语言中的类)。如果你能简单地解释一下它们的含义,我会非常感激。

英文:

I dont get the whole types + Interfaces model(that replaces classes in other languages). If theres a simple way you could explain what they are about, it will be really appreciated.

答案1

得分: 5

这是一个相当好的概述:

http://research.swtch.com/2009/12/go-data-structures-interfaces.html

英文:

This is a pretty good overview:

http://research.swtch.com/2009/12/go-data-structures-interfaces.html

答案2

得分: 4

Go接口是静态检查的鸭子类型。

C++中的纯虚类或Java中的接口的区别在于,你不是在实现接口的类上声明接口,而是在接收接口的方法上声明接口。

例如,我可以创建一个带有ReadWrite方法的接口,并将其命名为ThingsDustinReadsAndWrites,然后有一个名为doReadsAndWrites(rr ThingsDustinReadsAndWrites的函数。这个函数可以接收一个内置的http.ClientConn,它从未听说过我的接口,但是它实现了这个接口,因为它恰好有这些方法。

英文:

Go interfaces are statically checked duck typing.

The difference between pure virtual classes in C++ or interfaces in java is that you don't declare the interface on the class that implements the interface, but on the method that receives the interface.

For example, I can create an interface with a Read and a Write method and call it ThingsDustinReadsAndWrites and have a function called doReadsAndWrites(rr ThingsDustinReadsAndWrites. That can, in turn, receive a built-in http.ClientConn which has never heard of my interface, but implements it because it happens to have those methods.

huangapple
  • 本文由 发表于 2011年10月11日 13:43:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/7721824.html
匿名

发表评论

匿名网友

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

确定