【问题标题】:How to return an interface from an method which it has implemented?如何从已实现的方法返回接口?
【发布时间】: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 {} 完成都会出错。

标签: go methods interface crud


【解决方案1】:

我认为您应该将返回值存储到一个变量中。还要确保这个返回值(结果)是接口的切片。 如果不是,则将其转换为

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    • 2011-06-22
    • 1970-01-01
    相关资源
    最近更新 更多