普通网友 2017-11-12 07:54
浏览 476
已采纳

我如何有golang接口实现返回另一个接口的实现?

Specific example is here: https://play.golang.org/p/ZNmviKWLwe

I have an interface A. I expect all implementations of A to have a certain signature (hence the interface). I expect one of those to return something useful that implements another interface.

type Box interface {
    GetToy(int) (*Toy, error)
}
type Toy interface{
    Play()
}


type CarBox struct {
   Length int
   Width int
   Height int
   toys []*Matchbox
}
type Matchbox struct {}

func (b *CarBox) Size () int {
    return b.Length*b.Width*b.Height
}
func (b *CarBox) GetToy(j int) (*Matchbox, error) {
    return b.toys[j], nil
}
func (m *Matchbox) Play() {
    fmt.Println("Zoom!")
}

But of course, it doesn't work, because GetToy() returns *Matchbox and not *Toy, even though Matchbox is a perfectly acceptable implementation of Toy. And, no, it isn't because of the pointers; it gives the same result whether I return *Toy in GetToy or just Toy:

tmp/sandbox721971102/main.go:33:15: cannot use CarBox literal (type CarBox) as type Box in return argument:
    CarBox does not implement Box (wrong type for GetToy method)
        have GetToy(int) (*Matchbox, error)
        want GetToy(int) (*Toy, error)

Obviously my pattern doesn't match how go works. What is the "correct" way to go about doing this?

  • 写回答

2条回答 默认 最新

  • dongzhangji4824 2017-11-12 08:09
    关注

    First of all you almost never need a pointer to an interface type. So GetToy method signature should be changed to:

    type Box interface {
        GetToy(int) (Toy, error) // use Toy, not *Toy
    }
    

    Now, note that interfaces are satisfied by types implicitly. As a result, by implementing the Play() method, *Matchbox implicitly satisfies the Toy interface (note the *, the type implementing the Toy interface is pointer to Matchbox and not Matchbox).

    This means a value of type *Matchbox can be substituted for type Toy. So what remains is to fix the GetToy method defined on *CarBox:

    func (b *CarBox) GetToy(j int) (Toy, error) {
        return b.toys[j], nil
    }
    

    Now GetToy above will return a *Matchbox which does implement the Toy interface.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 解决websocket跟c#客户端通信
  • ¥30 Python调用dll文件输出Nan重置dll状态
  • ¥15 浮动div的高度控制问题。
  • ¥66 换电脑后应用程序报错
  • ¥50 array数据同步问题
  • ¥15 pic16F877a单片机的外部触发中断程序仿真失效
  • ¥15 Matlab插值拟合差分微分规划图论
  • ¥15 keil5 target not created
  • ¥15 C/C++数据与算法请教
  • ¥15 怎么找志同道合的伙伴