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

Linda Hamilton
Release: 2024-10-27 04:20:02
Original
401 people have browsed it

 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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!