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 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64