Go Interface Method Returning Interface Doesn't Match Method Returning Concrete Type
Issue:
An interface method returning an interface only works if the implementing type declares the interface itself, not a concrete type that implements the interface.
Question:
How can we resolve this issue while avoiding modifications to third-party concrete types or interfacing directly against them?
Answer:
To reconcile the interface mismatch, we employ encapsulation techniques:
1. Wrapper Technique:
Create a new type that wraps the third-party concrete type and provides the desired interface:
<code class="go">type MyBar Bar func (b *MyBar) GetStringer() fmt.Stringer { return &Foo{"foo"} }</code>
This approach allows customization to the desired interface without affecting the original concrete type.
2. Embedded Type Technique:
Embed the third-party concrete type into a new type and provide the needed interface implementation:
<code class="go">type MyBar struct{ Bar } func (b *MyBar) GetStringer() fmt.Stringer { return b.Bar.GetStringer() }</code>
Embedding preserves the functionality of the original concrete type while extending it with the desired interface.
These techniques enable the creation of custom types that conform to specified interfaces, even when the original concrete types do not. They provide a flexible approach to integrating third-party types into wider interface-based systems.
The above is the detailed content of How to Handle an Interface Mismatch When Implementing Interface Methods with Concrete Types?. For more information, please follow other related articles on the PHP Chinese website!