1 回答

TA貢獻1831條經(jīng)驗 獲得超4個贊
通過使用接口。兩者兼而有之,并實現(xiàn)一個接口,該接口具有獲取(返回)類型的方法。那么你只需要一個需要這個接口類型值的函數(shù),就可以調(diào)用接口定義的方法。然后,您可以傳遞 值 或 ,或者實現(xiàn)該接口的任何其他類型。A1B1Execute()A1B1
例如:
type HasType interface {
GetType() string
}
func (a A1) GetType() string {
return a.Spec.Type
}
func (b B1) GetType() string {
return b.Spec.Type
}
func Execute(ctx context.Context, foo HasType, Client client.Client) error {
if foo.GetType() == "test" {
}
}
你可以這樣稱呼它:
var a A1 = ...
var b B1 = ...
Execute(ctx, a, client)
Execute(ctx, b, client)
請參閱為什么 Golang 中需要接口?
另請注意,在此特定示例中,您可以只傳遞類型而不是 and ,因此可以省略接口和方法聲明。A1B1
例如,你可以這樣創(chuàng)建:Execute()
func Execute(ctx context.Context, typ string, Client client.Client) error {
if typ == "test" {
}
}
并這樣稱呼它:
var a A1 = ...
var b B1 = ...
Execute(ctx, a.Spec.Type, client)
Execute(ctx, b.Spec.Type, client)
- 1 回答
- 0 關注
- 93 瀏覽
添加回答
舉報