【发布时间】:2017-03-04 10:36:14
【问题描述】:
对不起,如果这个问题有点基本。 我正在尝试使用 Golang 接口使 CRUD 的实现更加动态。 我已经实现了一个接口如下
type Datastore interface {
AllQuery() ([]interface{}, error)
ReadQuery() ([]interface{}, error)
UpdateQuery() ([]interface{}, error)
CreateQuery() ([]interface{}, error)
DestroyQuery() ([]interface{}, error)//Im not sure if the return value implementation is correct
}
这可以与多种模型一起使用category Category,tag Tag.etc
它实现了指示表示应用中模型的结构的方法。
这是简化的处理程序/控制器 func UpdateHandler(c handler.context)错误{ p := new(models.Post) 返回更新(p,c) }
这是实现接口的函数
func Update(data Datastore,c handler.context) error{
if err := c.Bind(data); err != nil {
log.Error(err)
}
d, err := data.UpdateQuery()
//stuff(err checking .etc)
return c.JSON(fasthttp.StatusOK, d)///the returned value is used here
}
这是我用来查询数据库的方法
func (post Post) UpdateQuery() ([]interface{}, error){
//run query using the
return //I dont know how to structure the return statement
}
我如何构造上面的接口和它实现的方法,以便我可以将查询结果返回给实现函数。 如果我需要对问题添加任何内容或改进它,请告诉我,我会尽快这样做。 谢谢!
【问题讨论】:
-
如果你的 CRUD 界面设计成类似于this one
-
你真的应该试着想出一个minimal的例子。并且请:摆脱空界面。无论您尝试做什么,使用
interface {}完成都会出错。