Try not to use reflect. But if you must use reflect:
- A
reflect.Valuevalue has aType()function, which returns areflect.Typevalue. - If that type’s
Kind()isreflect.Map, thatreflect.Valueis a value of typemap[T1]T2for some types T1 and T2, where T1 is the key type and T2 is the element type.
Therefore, when using reflect, we can pull apart the pieces like this:
func show(m reflect.Value) {
t := m.Type()
if t.Kind() != reflect.Map {
panic("not a map")
}
kt := t.Key()
et := t.Elem()
fmt.Printf("m = map from %s to %s\n", kt, et)
}
See a more complete example on the Go Playground. (Note that both maps are actually nil, so there are no keys and values to enumerate.)
solved Print the key/value types of a Golang map