2014-10-01 38 views
0
func GetFromDB(tableName string, m *bson.M) interface{} { 
    var (
     __session *mgo.Session = getSession() 
    ) 

    //if the query arg is nil. give it the null query 
    if m == nil { 
     m = &bson.M{} 
    } 

    __result := []interface{}{} 
    __cs_Group := __session.DB(T_dbName).C(tableName) 
    __cs_Group.Find(m).All(&__result) 

    return __result 
} 

呼叫如何從一片界面{}轉換爲Go中的一個結構類型片段?

GetFromDB(T_cs_GroupName, &bson.M{"Name": "Alex"}).([]CS_Group) 

運行時將會給我恐慌:

panic: interface conversion: interface is []interface {}, not []mydbs.CS_Group 

如何返回值轉換爲我的結構?

+0

可能重複的[類型轉換中的接口切片](http://stackoverflow.com/questions/12753805/type-converting-slices-of-interfaces-in-go) – kostix 2014-10-01 17:20:51

回答

-1

您需要的對象的整個層次結構轉換:

rawResult := GetFromDB(T_cs_GroupName, &bson.M{"Name": "Alex"}).([]interface{}) 
var result []CS_Group 
for _, m := range rawResult { 
    result = append(result, 
     CS_Group{ 
     SomeField: m["somefield"].(typeOfSomeField), 
     AnotherField: m["anotherfield"].(typeOfAnotherField), 
     }) 
} 

該代碼可用於其中由MgO匹配返回類型的簡單情況你的struct字段的類型。您可能需要在bson.M值類型中進行某些類型轉換和類型切換。

另一種方法是通過將輸出切片作爲參數傳遞給利用氧化鎂的解碼器:

func GetFromDB(tableName string, m *bson.M, result interface{}) error { 
    var (
     __session *mgo.Session = getSession() 
    ) 
    //if the query arg is nil. give it the null query 
    if m == nil { 
     m = &bson.M{} 
    } 
    __result := []interface{}{} 
    __cs_Group := __session.DB(T_dbName).C(tableName) 
    return __cs_Group.Find(m).All(result) 
} 

隨着這一變化,您可以直接獲取到您的類型:

var result []CS_Group 
err := GetFromDB(T_cs_GroupName, bson.M{"Name": "Alex"}, &result) 

見也可能是:FAQ: Can I convert a []T to an []interface{}?

2

您不能在兩種不同類型的切片之間自動轉換 - 包括[]interface{}[]CS_Group。在任何情況下,你需要每個元素分別轉換:

s := GetFromDB(T_cs_GroupName, &bson.M{"Name": "Alex"}).([]interface{}) 
g := make([]CS_Group, 0, len(s)) 
for _, i := range s { 
    g = append(g, i.(CS_Group)) 
} 
+0

非常感謝。[] interface {} {}是鍵入的類型。我之前想過去只能將數組類型轉換一步。我錯了。 – qwe520liao 2014-10-01 13:32:59

+0

但我使用該方法。會顯示錯誤:[panic:interface conversion:interface is bson.M,not mydbs.CS_Group] – qwe520liao 2014-10-01 14:14:30

相關問題