我剛剛看到 Go 在其最新版本中加入了泛型,我正在嘗試創建一個小專案來了解它是如何作業的。除了現在通用的非常簡單的功能之外,我似乎不知道它是如何作業的。我希望能夠做這樣的事情:
type Dao[RT any] interface {
FindOne(id string) *RT
}
type MyDao struct {
}
type ReturnType struct {
id int
}
func (m *MyDao) FindOne(id string) *ReturnType {
panic("implement me")
}
// how should this look like?
func NewMyDao() *Dao[ReturnType] {
return &MyDao[ReturnType]{}
}
這甚至可能嗎?我似乎沒有以這種方式實作介面,并且我嘗試了許多相同的組合。
有沒有辦法實作通用介面?如果不是,是否只能回傳interface{}型別?
非常感謝。
uj5u.com熱心網友回復:
該型別*MyDao實作了介面Dao[ReturnType]。因此,該函式應如下所示:
func NewMyDao() Dao[ReturnType] {
return &MyDao{}
}
請注意,回傳型別是泛型介面的一個實體,回傳值只是該*MyDao型別的一個實體。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/466886.html
上一篇:GOENV只能使用OS環境設定
