2016-10-22 47 views
0

对不起,如果这个问题有点基本。 我正在尝试使用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)错误{ 号码:=新的(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 
} 
方法3210

如何构造上面的接口及其实现的方法,以便我可以将查询结果返回给实现函数。 请让我知道如果我需要添加任何问题或改进它,我会尽力做到这一点。 谢谢!

+1

如果设计类似于你的CRUD接口,可以更好[这一个](https://godoc.org/github.com/sauerbraten/crudapi#Storage) –

+2

你真的应该尝试并提出一个_minimal_例子。并请:摆脱空的界面。无论您尝试做什么,使用'interface {}'完成时都会出错。 – Volker

回答

4

我想你应该将返回值存储到一个变量。还要确保这个返回值(结果)是界面切片。 如果它不是那么受

v := reflect.ValueOf(s) 
intf := make([]interface{}, v.Len()) 

将其转换你的情况,你的UpdateQuery功能可能看起来像

func (post Post) UpdateQuery() (interface{}, bool) { 

    result,err := []Struct{} 

    return result, err 
} 

演示: https://play.golang.org/p/HOU56KibUd

相关问题