Implementing Interface Method with Interface Return Type in Go
In Go, one may encounter a situation where an interface method has an interface as its return type. This raises the question of how to implement such a method.
Consider the example code provided:
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!" }
When attempting to compile this code, an error occurs because the A struct's FB method returns a *B concrete type instead of the required IB interface type.
To resolve this issue, simply modify the FB method in the A struct to return the IB interface type:
func (a *A) FB() IB { return a.b }
Now, the A struct correctly implements the IA interface and can be used as an IA type.
In cases where the interfaces are defined in different packages, it is still possible to implement the method appropriately. For example, if IA and IB are defined in package foo and the implementations are in package bar, the declaration and implementation would be as follows:
Declaration (in foo package):
type IA interface { FB() IB }
Implementation (in bar package):
func (a *A) FB() foo.IB { return a.b }
By casting the returned value to the required interface type, the implementation can conform to the required interface and compile successfully.
The above is the detailed content of How to Implement Interface Methods with Interface Return Types in Go?. For more information, please follow other related articles on the PHP Chinese website!