"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Manage Functions for Similar Go Structs with Shared Fields?

How to Manage Functions for Similar Go Structs with Shared Fields?

Published on 2024-11-08
Browse:563

How to Manage Functions for Similar Go Structs with Shared Fields?

Go Best Practice: Managing Functions for Similar Structs with Shared Fields

In Go, it's common to encounter multiple structs with similar fields, and there is a need to perform identical operations on them. To avoid code repetition while maintaining flexibility, consider the following strategies:

Creating a Custom Type for the Shared Field:

If the shared field is a simple data type (e.g., string), consider defining a custom type for it. This allows you to attach methods to the custom type, which can then be used by any struct that embeds that type.

type Version string

func (v Version) PrintVersion() {
    fmt.Println("Version is", v)
}

Then, embed the Version type in the structs:

type Game struct {
    Name               string
    MultiplayerSupport bool
    Genre              string
    Version
}

type ERP struct {
    Name               string
    MRPSupport         bool
    SupportedDatabases []string
    Version
}

This allows you to print the version using the PrintVersion method on the Version field:

g.PrintVersion()
e.PrintVersion()

Using Reflection:

If the shared field can be different types or if you want more flexibility, you can use reflection to dynamically invoke the appropriate method. This approach is more complex and has some performance implications, but it provides greater flexibility.

type Printer interface {
    PrintVersion() error
}

func PrintVersion(p Printer) error {
    t := reflect.TypeOf(p)
    method, ok := t.MethodByName("PrintVersion")
    if !ok {
        return fmt.Errorf("object doesn't have a PrintVersion method")
    }

    return method.Func.Call([]reflect.Value{reflect.ValueOf(p)})[0].Interface().(error)
}

You can then use the PrintVersion function to invoke the PrintVersion method on any object that implements the Printer interface:

var game Game
var erp ERP

PrintVersion(game)
PrintVersion(erp)
Latest tutorial More>

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