dqwh1219
2017-08-22 12:26
浏览 166
已采纳

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

图片转代码服务由CSDN问答提供 功能建议

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

返回 main.M

如何找到基础类型 项作为 map [string] interface {}

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanduan1993 2017-08-22 12:36
    已采纳

    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.

    点赞 打赏 评论
  • dousao9569 2017-08-22 12:37

    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)
    }
    
    点赞 打赏 评论

相关推荐