」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何管理具有共用欄位的類似 Go 結構的函數?

如何管理具有共用欄位的類似 Go 結構的函數?

發佈於2024-11-08
瀏覽:329

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

Go 最佳實踐:管理具有共享字段的相似結構體的函數

在Go 中,經常會遇到具有相似字段的多個結構體,並且需要對它們執行相同的操作。為了在保持靈活性的同時避免程式碼重複,請考慮以下策略:

為共享欄位建立自訂類型:

如果共用欄位是簡單資料類型(例如,字串),考慮為其定義自訂類型。這允許您將方法附加到自訂類型,然後嵌入該類型的任何結構都可以使用該方法。

type Version string

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

然後,將 Version 型嵌入結構體中:

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

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

這允許您使用 Version 欄位上的 PrintVersion 方法列印版本:

g.PrintVersion()
e.PrintVersion()

使用反射:

如果共享欄位可以是不同的類型或如果您想要更大的靈活性,您可以使用反射來動態呼叫適當的方法。這種方法比較複雜,並且會產生一些效能影響,但它提供了更大的靈活性。

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)
}

然後您可以使用 PrintVersion 函數在任何實作 Printer 介面的物件上呼叫 PrintVersion 方法:

var game Game
var erp ERP

PrintVersion(game)
PrintVersion(erp)
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3