Convert Value type to Map in Golang?

前端 未结 2 2201
刺人心
刺人心 2021-02-19 11:24

I\'m getting this return value from a function call in the \"reflect\" package:

< map[string]string Value >.

Wondering if I can access the ac

2条回答
  •  臣服心动
    2021-02-19 11:48

    To turn the value in a reflect.Value into an interface{}, you use iface := v.Interface(). Then, to access that, you use a type assertion or type switch.

    If you know you're getting a map[string]string the assertion is simply m := iface.(map[string]string). If there's a handful of possibilities, the type switch to handle them all looks like:

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

    Of course, that only works if you can write out all the concrete types you're interested out in the code. If you don't know the possible types at compile time, you have to use methods like v.MapKeys() and v.MapIndex(key) to work more with the reflect.Value, and, in my experience, that involves a long time looking at the reflect docs and is often verbose and pretty tricky.

提交回复
热议问题