3 回答

TA貢獻1752條經驗 獲得超4個贊
如果您嘗試完全繞過為每個 DAO 編寫方法,則唯一的解決方案是從此方法返回 a。然而,這種方法會產生兩個問題:Get()
interface{}
您需要手動將所有內容都強制轉換。
interface{}
你正在破壞安全型。
我認為最好的解決方案是通過使用結構嵌入來共享大部分代碼,并為每個DAO編寫輕量級包裝器,以將不安全的值轉換為類型安全值。interface{}
例
首先使用泛型方法創建基本 DAO。Go 中沒有類型泛型,因此應在此處返回 。Get()interface{}
type BaseDAO struct {}
func (*BaseDAO) Get(id uint64) (interface{}, error) {}
然后,對于每種類型的數據,創建一個特定的DAO實現,嵌入:BaseDAO
type FooModel = string
type FooDAO struct {
// Embbeding BaseDAO by not specifying a name on this field
// BaseDAO methods can be called from FooDAO instances
BaseDAO
}
func (foo *FooDAO) Get(id uint64) (FooModel, error) {
// Call the shared Get() method from BaseDAO.
// You can see this just like a `super.Get()` call in Java.
result, _ := foo.BaseDAO.Get(id)
return result.(FooModel), nil
}

TA貢獻1869條經驗 獲得超4個贊
type BaseDao struct {
FirstDao
SecondDao
}
func (dao *BaseDao) Get(id uint64) (*model.SecondModel, error) {
}
只是寫下我的想法。也許這將有助于您解決您的解決方案

TA貢獻1818條經驗 獲得超11個贊
也許不能。因為圍棋劑量不支持1.18之前的genrics。
我認為提取層可能是一個反模式,如果你想使用鉤子。dao
想象一下:
// pkg models
type User
type UserChangeLog
func (user *User) afterUpdate(tx) error () {
// if you want to record user changes
userChangeLogDao().insert(user)
}
// pkg dao
func (userDao) update() {}
func (userChangeLogDao) insert(User){}
它導致道和模型之間import cycle
- 3 回答
- 0 關注
- 117 瀏覽
添加回答
舉報