英文:
Go And Nested Interfaces
问题
希望有一个基于另一个接口的属性的接口,这种情况是否可能?
虚构的例子:
type interface cheese {
GetId() string
}
type interface cheeses {
GetCheeses() []cheese
}
type CheeseStruct struct {
GetId() string
}
type BowlOfCheeses struct {
GetCheeses() []*CheeseStruct
}
func doSomething(thing cheeses) {
}
bowlOfCheeses := BowlOfCheeses{
[]*CheeseStruct{
&CheeseStruct{}
}
}
doSomething(bowlOfCheeses) # 看起来无法匹配
英文:
Hoping to have an interface that has attributes based on another interface. Is that possible?
Contrived Example:
type interface cheese {
GetId() string
}
type interface cheeses {
GetCheeses() []cheese
}
type CheeseStruct struct {
GetId() string
}
type BowlOfCheeses struct {
GetCheeses() []*CheeseStruct
}
func doSomething(thing cheeses) {
}
bowlOfCheeses := BowlOfCheeses{
[]*CheeseStruct{
&CheeseStruct{}
}
}
doSomething(bowlOfCheeses) # the match doesn't seem to be recognized
答案1
得分: 2
对于类型 T
来实现接口 I
,T
的方法集必须包含 I
的方法集中的所有方法,并且这些方法的签名必须完全匹配,即方法的名称、输入和输出参数的数量、顺序和类型都必须完全匹配。
GetCheeses() []cheese
!= GetCheeses() []*CheeseStruct
另请参阅:为什么 Go 语言没有协变的结果类型?
英文:
For a type T
to implement an interface I
, T
's method set must contain all methods of I
's method set, and the signatures of these methods must match verbatim, i.e. the name of the method, the input & output parameter count, order, and types must all match exactly.
GetCheeses() []cheese
!= GetCheeses() []*CheeseStruct
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论