可以通过类型断言和类型转换来将结果转换为期望的类型。

首先,我们需要进行类型断言,判断结果是否为'map[interface{}][]interface{}'类型:

if res, ok := result.(map[interface{}][]interface{}); ok {
    // 转换类型
}

接着,我们可以定义一个新的'map'变量,将其类型设置为'map[int][]Person',然后遍历结果'map',将其中的键和值转换为期望的类型,存入新的'map'中:

newRes := make(map[int][]Person)
for k, v := range res {
    // 转换键类型
    intKey, ok := k.(int)
    if !ok {
        continue
    }

    // 转换值类型
    var personList []Person
    for _, person := range v {
        p, ok := person.(Person)
        if !ok {
            continue
        }
        personList = append(personList, p)
    }

    // 存入新的'map'中
    newRes[intKey] = personList
}

最终,我们就可以得到一个类型为'map[int][]Person'的结果了。完整的代码如下:

type Person struct {
    Name string
    Age  int
}

func main() {
    m := make(map[int]interface{})
    m[1] = []Person{
        {"Tom", 18},
        {"Jerry", 20},
    }
    m[2] = []Person{
        {"Alice", 22},
        {"Bob", 25},
    }

    result := make(map[interface{}][]interface{})
    for k, v := range m {
        result[k] = []interface{}{v}
    }

    if res, ok := result.(map[interface{}][]interface{}); ok {
        newRes := make(map[int][]Person)
        for k, v := range res {
            intKey, ok := k.(int)
            if !ok {
                continue
            }

            var personList []Person
            for _, person := range v {
                p, ok := person.(Person)
                if !ok {
                    continue
                }
                personList = append(personList, p)
            }

            newRes[intKey] = personList
        }
        fmt.Println(newRes)
    }
}
Go 语言类型转换:将 map[interface{}][]interface{} 转换为 map[int][]Person

原文地址: https://www.cveoy.top/t/topic/na5z 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录