英文:
How do I declare a composite interface in Go?
问题
以下接口定义了一组由哞哞对象实现的方法:
type Mooing interface {
Moo() string
}
以下定义了一组由吃草对象实现的方法:
type Grazing interface {
EatGrass()
}
我有一个操作奶牛的函数:
func Milk(cow *Cow)
但它不一定是奶牛,只要符合 Mooing
和 Grazing
接口的任何对象都可以。在Go语言中,是否可以指定一个 Mooing
和 Grazing
的参数?换句话说,类似以下伪代码的方式:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论