如何从已实现的方法返回接口?

时间:2016-10-22 03:47:03

标签: go methods interface crud

很抱歉,如果这个问题有点基础。 我正在尝试使用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 Categorytag Tag等一起使用 它实现了表示应用程序中模型的结构的方法。

这是简化的处理程序/控制器     func UpdateHandler(c handler.context)error {         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
}

如何构造上面的接口及其实现的方法,以便我可以将查询结果返回给实现函数。 如果我需要在问题中添加任何内容或改进它,请告诉我。我会尽快这样做。 谢谢!

1 个答案:

答案 0 :(得分: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

相关问题