英文:
How to create a generic interface for a CRUD model?
问题
我正在尝试为我在API中使用的模型创建一个通用的Go接口。
type Model interface {
Create(interface{}) (int64, error)
Update(string, interface{}) error
}
我有一个实现了该接口的personModel
:
type Person struct {
Id int `json:"id"`
FirstName string `json:"firstName"`
}
type PersonModel struct {
Db *sql.DB
}
func (model *PersonModel) Create(personStruct Person) (int64, error) {
// 执行与数据库相关的操作,从结构体创建人员
}
func (model *PersonModel) Update(id string, personStruct Person) error {
// 执行与数据库相关的操作,更新人员模型
}
然而,我无法使其正常工作,因为出现了与PersonModel
未实现Model
接口相关的错误。
我的主要目标是为应用程序中的所有模型(实现create
和update
)提供统一的接口,以供控制器使用。我该如何解决这个问题?
英文:
I'm trying to create a generic interface in go for models I wish to use in my api.
type Model interface {
Create(interface{}) (int64, error)
Update(string, interface{}) (error)
}
And I have a personModel which implements it:
type Person struct {
Id int `json:"id"`
FirstName string `json:"firstName"`
}
type PersonModel struct {
Db *sql.DB
}
func (model *PersonModel) Create(personStruct person) (int64, error) {
// do database related stuff to create the person from the struct
}
func (model *PersonModel) Update(id string, personStruct person) (error) {
// do database related stuff to update the person model from the struct
}
However, I can't get this to work, as I'm getting errors related to how the PersonModel
does not implement the Model
interface.
My main goal is to have a unified interface for all models in my application (implementing create
and update
) that can be used by the controllers. How would I go about overcoming this problem?
答案1
得分: 1
你应该尝试按照以下方式实现你的方法,这是因为你在函数Create和Update中将一个空接口作为参数传入:
func (model *PersonModel) Create(v interface{}) (int64, error) {
// 执行与数据库相关的操作,从结构体中创建人员
}
func (model *PersonModel) Update(id string, v interface{}) error {
// 执行与数据库相关的操作,从结构体中更新人员模型
}
这样实现可以让你在函数中接收任意类型的参数。
英文:
You should try to implement your method like this, it's just because you ask in your func Create and Update an empty interface as params :
func (model *PersonModel) Create(v interface{}) (int64, error) {
// do database related stuff to create the person from the struct
}
func (model *PersonModel) Update(id string, v interface{}) (error) {
// do database related stuff to update the person model from the struct
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论