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:
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
}
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:
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
}
By employing this approach, code repetition associated with duplicate methods is eliminated while maintaining flexibility and type safety.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3