我想构建一个可以针对系统的不同应用进行扩展的系统。
在域包中,我有一个如下界面:
package main
type CardInterface interface {
GetName()string
}
type DeckInterface interface {
GetCards()[]CardInterface
}
在应用程序包中,我有以下实现:
package implementation
//Implementing CardInterface
type Card struct {
Name string
}
func (c Card) GetName() string {
return c.Name
}
type Deck struct {
Cards []Card
}
func (d Deck) GetCards() []CardInterface {
return d.Cards[]
}
但它给出了一个错误,说不能返回
[]Card
的实例而不是 []CardInterface
.有没有办法在 Go 中实现这种 OOP 结构?如果不是,我怎样才能实现这种扩展能力?
最佳答案
如果要保留 Deck
类型定义(如果没有,请查看 Shadowchaser's answer ),您可以尝试以下操作:
func (d Deck) GetCards() []CardInterface {
var res []CardInterface
for _ , card := range d.Cards {
res = append(res, card)
}
return res
}
您需要重新 slice
Deck
因为,而 Card
是 CardInterface
, 一个 []Card
不是 []CardInterface
.
关于go - 有没有办法返回实现结构而不是 Go 中的接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61301528/