1
type M map[string]interface{}
var item M
fmt.Println(reflect.TypeOf(item))

returns main.M.

How can I find underlying type of item as map[string]interface{}.

peterSO
  • 158,998
  • 31
  • 281
  • 276
ugurozgen
  • 81
  • 9
  • What is the root type? I've never heard such term. – lofcek Aug 22 '17 at 12:34
  • Related / Possible duplicate of [Identify non builtin-types using reflect](https://stackoverflow.com/questions/36310538/identify-non-builtin-types-using-reflect/37292523#37292523). – icza Aug 22 '17 at 12:36

2 Answers2

3

Yes, you can fetch the precise structure of the type, if that's what you mean with "root type":

var item M
t := reflect.TypeOf(item)
fmt.Println(t.Kind()) // map
fmt.Println(t.Key())  // string
fmt.Println(t.Elem()) // interface {}

test it

From there you're free to display it as you want.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

I don't think there's an out-of-the-box way, but you can construct the underlying type by hand:

type M map[string]interface{}
...
var m M
t := reflect.TypeOf(m)
if t.Kind() == reflect.Map {
    mapT := reflect.MapOf(t.Key(), t.Elem())
    fmt.Println(mapT)
}
bereal
  • 32,519
  • 6
  • 58
  • 104