2016-10-22 48 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

相關問題