I'm getting this return value from a function call in the "reflect" package:
< map[string]string Value >
.
Wondering if I can access the actual map inside the return value and if so, how?
EDIT:
So this is where I'm making the call which returns the Value object.
It returns [< map[string]string Value >]
to which I grab the first object in that array. However, I'm not sure how to convert [< map[string]string Value >]
into a regular map.
view_args := reflect.ValueOf(&controller_ref).MethodByName(action_name).Call(in)
To turn the value in a
reflect.Value
into aninterface{}
, you useiface := 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 simplym := iface.(map[string]string)
. If there's a handful of possibilities, the type switch to handle them all looks like: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()
andv.MapIndex(key)
to work more with thereflect.Value
, and, in my experience, that involves a long time looking at thereflect
docs and is often verbose and pretty tricky.Most reflect
Value
objects can be converted back to ainterface{}
value using the.Interface()
method.After obtaining this value, you can assert it back to the map you want. Example (play):
In the example above,
m
is your original map andv
is the reflected value. The interface valuei
, acquired by theInterface
method is asserted to be of typemap[string]int
and this value is used as such in the last line.