ugurozgen
ugurozgen

Reputation: 81

find underlying type of custom type in golang

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{}.

Upvotes: 1

Views: 2116

Answers (2)

bereal
bereal

Reputation: 34281

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

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382150

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.

Upvotes: 3

Related Questions