普通网友 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条)

报告相同问题?

悬赏问题

  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题