打印Golang地图的键/值类型 [英] Print the key/value types of a Golang map

查看:60
本文介绍了打印Golang地图的键/值类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试打印地图的类型,例如:map [int] string

I am trying to print the type of a map, eg: map[int]string

func handleMap(m reflect.Value) string {

    keys := m.MapKeys()
    n := len(keys)

    keyType := reflect.ValueOf(keys).Type().Elem().String()
    valType := m.Type().Elem().String()

    return fmt.Sprintf("map[%s]%s>", keyType, valType)
}

所以,如果我这样做:

log.Println(handleMap(make(map[int]string)))

我想获取"map [int] string"

但是我找不到正确的拨打电话的电话.

but I can't figure out the right calls to make.

推荐答案

尽量不要使用 reflect .但是,如果您必须使用 reflect :

Try not to use reflect. But if you must use reflect:

  • reflect.Value 值具有 Type()函数,该函数返回 reflect.Type 值.
  • 如果该类型的 Kind() reflect.Map ,则该 reflect.Value 是类型为 map [T1]的值] T2 用于某些类型T1和T2,其中T1是键类型,T2是元素类型.
  • A reflect.Value value has a Type() function, which returns a reflect.Type value.
  • If that type's Kind() is reflect.Map, that reflect.Value is a value of type map[T1]T2 for some types T1 and T2, where T1 is the key type and T2 is the element type.

因此,当使用 reflect 时,我们可以将这些片段分开:

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

在Go Playground上查看更完整的示例.(请注意,两个映射实际上都是nil,因此没有要枚举的键和值.)

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

这篇关于打印Golang地图的键/值类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆