【问题标题】:find underlying type of custom type in golang在 golang 中查找自定义类型的底层类型
【发布时间】:2017-08-22 12:26:56
【问题描述】:
type M map[string]interface{}
var item M
fmt.Println(reflect.TypeOf(item))

返回main.M

我怎样才能找到作为map[string]interface{}的项目的基础类型。

【问题讨论】:

标签: go typeof


【解决方案1】:

是的,您可以获取类型的精确结构,如果这就是您对“根类型”的意思:

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

test it

从那里您可以随意显示它。

【讨论】:

    【解决方案2】:

    我认为没有开箱即用的方式,但您可以手动构造底层类型:

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

    【讨论】:

      猜你喜欢
      • 2019-10-21
      • 2015-06-02
      • 2018-12-15
      • 2014-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多