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?