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?
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.
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.
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.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With