Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

interface

go

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?

like image 309
nvcnvn Avatar asked Aug 12 '12 10:08

nvcnvn


People also ask

Can a method have return type as interface?

If an interface is defined to be the return type of a method then instances of classes derived from that interface can be returned. The benefit of doing that is no different from returning objects of classes derived from a class.

How do you implement an interface in Golang?

Implementing an interface in Go To implement an interface, you just need to implement all the methods declared in the interface. Unlike other languages like Java, you don't need to explicitly specify that a type implements an interface using something like an implements keyword.

Can interfaces be used as return types and parameters?

No, it's not possible. The interface serves as a "binding contact" of the signatures that are available. If you want you can have the function return an Object and by that allow different implementations to return values of different types, but: It must be references, not primitives.

Can an interface return?

You can't return an instance of an interface, because an interface is not a type. An interface is not a type because it does not have any associated data. An interface in this context is like a predicate that encapsulates any possible type that defines the methods declared in the interface.


1 Answers

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 } 
like image 51
themue Avatar answered Sep 28 '22 01:09

themue