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 }
We wish to have both structs implement interface A:
type A interface { PrintStr() // Print First.str or Second.str }
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) }
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) }
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) }
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", }, }
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!