douchibu7040 2014-10-01 11:28
浏览 516
已采纳

如何在Go中将接口{}的切片转换为结构类型的切片? [重复]

This question already has an answer here:

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
}

call

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?

</div>
  • 写回答

2条回答 默认 最新

  • douyan8772 2014-10-01 16:20
    关注

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

    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.

    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)
    

    See also: FAQ: Can I convert a []T to an []interface{}?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入