如何在Go中将接口{}的切片转换为结构类型的切片? [英] How do I convert from a slice of interface{} to a slice of my struct type in Go?

查看:51
本文介绍了如何在Go中将接口{}的切片转换为结构类型的切片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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
}

致电

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

运行时会让我感到恐慌:

runtime will give me panic:

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

如何将返回值转换为我的结构?

how convert the return value to my struct?

推荐答案

您需要转换对象的整个层次结构:

You need to convert the entire hierarchy of objects:

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值类型上进行一些类型转换和类型切换.

This code is for the simple case where the type returned from mgo matches the type of your struct fields. You may need to sprinkle in some type conversions and type switches on the bson.M value types.

另一种方法是通过将输出切片作为参数传递来利用mgo的解码器:

An alternate approach is to take advantage of mgo's decoder by passing the output slice as an argument:

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)
}

通过此更改,您可以直接获取您的类型:

With this change, you can fetch directly to your type:

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

另请参见:常见问题解答:我可以将[] T转换为[]接口{}吗?a>

这篇关于如何在Go中将接口{}的切片转换为结构类型的切片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆