Convert Value type to Map in Golang?

前端 未结 2 2205
刺人心
刺人心 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:50

    Most reflect Value objects can be converted back to a interface{} value using the .Interface() method.

    After obtaining this value, you can assert it back to the map you want. Example (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
    

    In the example above, m is your original map and v is the reflected value. The interface value i, acquired by the Interface method is asserted to be of type map[string]int and this value is used as such in the last line.

提交回复
热议问题