在Golang中将值类型转换为Map?

15

我从“reflect”包中的函数调用中获取到以下返回值:

< map[string]string Value >

想知道是否可以访问返回值内部的实际映射,如果可以,如何访问?

编辑:

这里是我进行调用并返回Value对象的地方。 它返回[< map[string]string Value >],我从其中抓取了第一个对象。但是,我不知道如何将[< map[string]string Value >]转换为常规映射。

view_args := reflect.ValueOf(&controller_ref).MethodByName(action_name).Call(in)

1
你能给我们提供更多的代码示例吗? - Eve Freeman
2个回答

21

大多数反射Value对象可以使用.Interface()方法转换回interface{}值。

获得此值后,您可以将其断言回到所需的地图上。 示例(play):

m := map[string]int{"foo": 1, "bar": 3}
v := reflect.ValueOf(m)
i := v.Interface()
a := i.(map[string]int)

println(a["foo"]) // 1
在上面的示例中,m是您的原始映射,v是反射值。通过使用Interface方法获取的接口值i被断言为map[string]int类型,并且该值在最后一行中用作这样的值。

1
太好了,我相信下面这个也可以用,这正是我需要的。非常感谢 :) - user1493543

8
reflect.Value 中的值转换为 interface{},您可以使用 iface := v.Interface()。然后,要访问它,可以使用类型断言类型开关
如果您知道正在获取的是 map[string]string,则断言只需m := iface.(map[string]string)。 如果有几种可能性,则处理它们的类型开关如下:
switch item := iface.(type) {
case map[string]string:
    fmt.Println("it's a map, and key \"key\" is", item["key"])
case string:
    fmt.Println("it's a string:", item)
default:
    // optional--code that runs if it's none of the above types
    // could use reflect to access the object if that makes sense
    // or could do an error return or panic if appropriate
    fmt.Println("unknown type")
}

当然,这仅适用于您可以在代码中写出所有感兴趣的具体类型。如果您不知道可能的类型,则必须使用像v.MapKeys()v.MapIndex(key)这样的方法更多地使用reflect.Value,在我的经验中,这需要花费很长时间来查看反射文档,并且通常会很冗长和棘手。

感谢您的回答! - user1493543

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接