How do I declare a composite interface in Go?

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

How do I declare a composite interface in Go?

问题

以下接口定义了一组由哞哞对象实现的方法:

type Mooing interface {
    Moo() string
}

以下定义了一组由吃草对象实现的方法:

type Grazing interface {
    EatGrass()
}

我有一个操作奶牛的函数:

func Milk(cow *Cow)

但它不一定是奶牛,只要符合 MooingGrazing 接口的任何对象都可以。在Go语言中,是否可以指定一个 MooingGrazing 的参数?换句话说,类似以下伪代码的方式:

func Milk(cow {Mooing, Grazing})

换言之,只有同时满足这两个接口的参数才会被接受。

英文:

The following interface defines a set of methods to be implemented by mooing objects:

type Mooing interface {
    Moo() string
}

The following defines a set of methods to be implemented by grazing objects:

type Grazing interface {
    EatGrass()
}

I have a function that operates on cows:

func Milk(cow *Cow)

It doesn't have to be a cow, though--anything that conforms to Mooing and Grazing is close enough. In Go, is it possible to specify a parameter of Mooing and Grazing? In pseudocode, something like the following?

func Milk(cow {Mooing, Grazing})

In other words, only parameters that satisfy both of these interfaces will be accepted.

答案1

得分: 28

你可以按照以下方式在Go中组合接口:

type MooingAndGrazing interface {
    Mooing
    Grazing
}

如果你不想声明一个新的命名类型,你可以内联地写成:

func Milk(cow interface{Mooing; Grazing})

你可以在这里尝试这个例子:http://play.golang.org/p/xAODkd85Zq

英文:

You can compose interfaces in Go as follows:

type MooingAndGrazing interface {
    Mooing
    Grazing
}

If you don't want to declare a new named type, you could inline this as:

func Milk(cow interface{Mooing; Grazing})

You can experiment with this example here: http://play.golang.org/p/xAODkd85Zq

huangapple
  • 本文由 发表于 2014年5月8日 12:18:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/23532653.html
匿名

发表评论

匿名网友

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

确定