Implementing Common Methods with Interfaces in Go
In Go, interfaces provide a mechanism for different types to implement the same set of methods, allowing for polymorphism in your code. However, sometimes you may encounter a situation where you want two distinct types to implement a common method but avoid redundant code.
Consider the following scenario:
type First struct { str string } type Second struct { str string } type A interface { PrintStr() }
To implement the PrintStr method for both First and Second structs, you would typically write the following separate methods:
func (f First) PrintStr() { fmt.Print(f.str) } func (s Second) PrintStr() { fmt.Print(s.str) }
While this approach is functional, it can lead to code duplication if you have multiple types that need to implement the same method. To overcome this, Go offers an elegant solution known as type embedding.
Type Embedding
Type embedding allows you to compose new types by embedding existing types into them. In this case, we can create a base type that contains the common str field and the PrintStr method.
type WithString struct { str string } func (w WithString) PrintStr() { fmt.Print(w.str) }
Now, we can embed the WithString type into our First and Second structs:
type First struct { WithString } type Second struct { WithString }
By doing so, both First and Second structs inherit the PrintStr method from the embedded WithString type. This eliminates the need for separate method implementations for each struct.
Example
Here's an example of how to use type embedding to implement a common method for two different types:
package main import "fmt" type WithString struct { str string } func (w WithString) PrintStr() { fmt.Print(w.str) } type First struct { WithString } type Second struct { WithString } func main() { a := First{ WithString: WithString{ str: "foo", }, } a.PrintStr() // Outputs: foo }
This approach allows you to maintain a single implementation for the common method while enabling it to be used by different types, promoting code reusability and reducing code duplication.
The above is the detailed content of How can I reuse code when implementing a common method for different types in Go?. For more information, please follow other related articles on the PHP Chinese website!