Interface inherit from other interface in golang

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

Interface inherit from other interface in golang

问题

在Go语言中,接口的复用可以通过嵌入其他接口来实现。以下是在Go中重用接口定义的示例:

type IA interface {
    MethodX()
}

type IB interface {
    IA
    MethodY()
}

通过将接口类型嵌入到其他接口类型中,我们可以实现接口的复用。在上述示例中,接口IB嵌入了接口IA,因此IB接口包含了IA接口的所有方法,同时还定义了自己的MethodY方法。这样,我们就可以在实现IB接口时,同时实现IA接口的方法。

希望对你有所帮助!如果你还有其他问题,请随时提问。

英文:

Interface inheritance looks like the following in C#:

interface IA{
    void MethodX();
}

interface IB : IA{
    void MethodY();
}

How can I reuse interface definition in go?

答案1

得分: 35

你可以在接口中嵌入其他接口,这基本上给你带来了相同的好处:

一个很好的例子是io包中的ReadWriteCloser接口:
http://golang.org/pkg/io/#ReadWriteCloser

它嵌入了一个Reader接口、一个Writer接口和一个Closer接口。

英文:

You can embed other interfaces inside an interface, which gives you basicaly the same benefits:

A Good Example is the ReadWriteCloser in the io package:
http://golang.org/pkg/io/#ReadWriteCloser

It embeds a Reader, a Writer and a Closer interface.

答案2

得分: 0

我猜你不需要继承,
Golang会检查你的结构体是否实现了接口中的相关方法,所以一个结构体可以实现多个接口。

英文:

I guess that you don't need inheritance,
Golang tests if your struct implements related method in interface so a struct can implement many interfaces

huangapple
  • 本文由 发表于 2015年9月1日 12:07:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/32323363.html
匿名

发表评论

匿名网友

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

确定