1 回答

TA貢獻1772條經驗 獲得超6個贊
你不能嵌入相同的接口,即使有不同的類型參數。不管它是如何實例化的,您都試圖將b兩個具有相同名稱GetList 和不同簽名的方法提升到接口中——由DB.
嵌入到結構中的情況類似,盡管在技術上并不相同。在結構體中,嵌入字段的名稱是類型的名稱—— DB,一個結構體不能有兩個同名的非空白字段。
關于如何解決這個問題,這取決于你想要完成什么。
如果您想傳達“使用任一類型參數a實現DB”,您可以嵌入DB[T]并使其成為a通用的,并限制a其類型參數:
type a[T int64 | string] struct {
DB[T]
}
// illustrative implementation of the DB[T] interface
// if you embed DB[T] you likely won't use `a` itself as receiver
func (r *a[T]) GetList(query string) ([]T, error) {
// also generic method
}
這沒關系,因為DB的類型參數被限制為any,并且a的類型參數更具限制性。這允許您在其他泛型方法中使用a,或在實例化時選擇特定類型,但 的實現GetList也必須參數化。
否則,如果你需要a有返回or的分離方法,你必須給它不同的名字。int64string
最后,您可以將 的實例嵌入DB到兩個具有不同名稱的接口中,然后將它們嵌入到ainstead 中。
type a struct {
DBStr
DBInt
}
type DBStr interface {
DB[string]
}
type DBInt interface {
DB[int64]
}
這樣雖然頂級選擇器不可用,因為方法名稱仍然相同。該程序可以編譯,但您必須明確選擇要在哪個字段上調用該方法:
myA := a{ /* init the two fields */ }
res, err = myA.DBStr.GetList(query)
// res is type []string
// or
res, err = myA.DBInt.GetList(query)
// res is type []int64
- 1 回答
- 0 關注
- 123 瀏覽
添加回答
舉報