如何为 CRUD 模型创建一个通用接口?

huangapple go评论76阅读模式
英文:

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接口相关的错误。

我的主要目标是为应用程序中的所有模型(实现createupdate)提供统一的接口,以供控制器使用。我该如何解决这个问题?

英文:

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
}

huangapple
  • 本文由 发表于 2017年1月1日 01:32:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/41410459.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定