Home >Backend Development >Golang >How to Avoid Code Duplication When Implementing Identical Methods on Structs with Shared Fields?
Best Practices for Utilizing a Common Function Across Structs with Identical Fields
In scenarios where two structs possess identical fields, it is desirable to prevent code duplication when defining methods that operate on those fields.
Custom Type as Method Receiver
The recommended approach is to introduce a custom type (e.g., Version) that serves as the method receiver. Since all custom types can be utilized as method receivers, this technique enables the creation of a single method that can be applied to multiple structs.
Composition
Once the custom type is defined, it can be incorporated into the structs using composition. This involves embedding the custom type within the structs, essentially creating a nested structure.
Example
Consider the following code snippet:
<code class="go">type Version string func (v Version) PrintVersion() { fmt.Println("Version is", v) } type Game struct { Name string MultiplayerSupport bool Genre string Version } type ERP struct { Name string MRPSupport bool SupportedDatabases []string Version }</code>
Here, the Version type serves as the method receiver, and its PrintVersion method can be accessed by both the Game and ERP structs due to their embedded Version fields.
Usage
The embedded Version field can be used and modified just like any other field:
<code class="go">main() { g := Game{ "Fear Effect", false, "Action-Adventure", "1.0.0", } g.PrintVersion() // Version is 1.0.0 e := ERP{ "Logo", true, []string{"ms-sql"}, "2.0.0", } e.PrintVersion() // Version is 2.0.0 }</code>
By employing this approach, code repetition associated with duplicate methods is eliminated while maintaining flexibility and type safety.
The above is the detailed content of How to Avoid Code Duplication When Implementing Identical Methods on Structs with Shared Fields?. For more information, please follow other related articles on the PHP Chinese website!