How can I implement interface methods for dissimilar types in Golang?

DDD
Release: 2024-11-24 05:04:13
Original
453 people have browsed it

How can I implement interface methods for dissimilar types in Golang?

Implementing Interface Methods in Dissimilar Types Using Golang Interfaces

In Go, it's often desirable to have different types of data structures implement the same interface to provide a common set of behaviors. For instance, consider two structs:

type First struct {
    str string
}
type Second struct {
    str string
}
Copy after login

We wish to have both structs implement interface A:

type A interface {
    PrintStr() // Print First.str or Second.str
}
Copy after login

However, implementing PrintStr() for each struct separately seems redundant:

func (f First) PrintStr() {
    fmt.Print(f.str)
}

func (s Second) PrintStr() {
    fmt.Print(s.str)
}
Copy after login

It would be ideal to have a single implementation for all structs implementing A. Attempting to do this directly doesn't work:

func (a A) PrintStr() {
    fmt.Print(a.str)
}
Copy after login

The reason for this is that a doesn't have a str field. Instead, a more elegant solution involves creating a base type and embedding it into our two structs:

type WithString struct {
    str string
}

type First struct {
    WithString
}

type Second struct {
    WithString
}

type A interface {
    PrintStr() // Print First.str or Second.str
}

func (w WithString) PrintStr() {
    fmt.Print(w.str)
}
Copy after login

Here, WithString serves as the base type, and First and Second embed it. This gives us a centralized implementation for PrintStr().

Example usage:

a := First{
    WithString: WithString{
        str: "foo",
    },
}
Copy after login

Note that we can create an instance of First by embedding an instance of WithString. This technique allows us to achieve our goal of having one implementation for multiple different types that implement the same interface.

The above is the detailed content of How can I implement interface methods for dissimilar types in Golang?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template