Go语言中的嵌套接口(Nested Interfaces)

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

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 来实现接口 IT 的方法集必须包含 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

Also see: Why does Go not have covariant result types?

huangapple
  • 本文由 发表于 2021年10月19日 01:06:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/69619958.html
匿名

发表评论

匿名网友

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

确定