Home  >  Article  >  Backend Development  >  How to Handle an Interface Mismatch When Implementing Interface Methods with Concrete Types?

How to Handle an Interface Mismatch When Implementing Interface Methods with Concrete Types?

Linda Hamilton
Linda HamiltonOriginal
2024-10-27 04:20:02390browse

 How to Handle an Interface Mismatch When Implementing Interface Methods with Concrete Types?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn