nvcnvn
nvcnvn

Reputation: 5175

How to implement interface method with return type is an interface in Golang

Here is my code:

type IA interface {
    FB() IB
}

type IB interface {
    Bar() string
}

type A struct {
    b *B
}

func (a *A) FB() *B {
    return a.b
}

type B struct{}

func (b *B) Bar() string {
    return "Bar!"
}

I get an error:

cannot use a (type *A) as type IA in function argument:
    *A does not implement IA (wrong type for FB method)
        have FB() *B
        want FB() IB

Here is the full code: http://play.golang.org/p/udhsZgW3W2
I should edit the IA interface or modifi my A struct?
What if I define IA, IB in a other package (so I can share these interface), I must import my package and use the IB as returned type of A.FB(), is it right?

Upvotes: 35

Views: 23788

Answers (1)

themue
themue

Reputation: 7850

Just change

func (a *A) FB() *B {
    return a.b
}

into

func (a *A) FB() IB {
    return a.b
}

Surely IB can be defined in another package. So if both interfaces are defined in package foo and the implementations are in package bar, then the declaration is

type IA interface {
    FB() IB
}

while the implementation is

func (a *A) FB() foo.IB {
    return a.b
}

Upvotes: 21

Related Questions