打印Golang地图的键/值类型

时间:2020-02-15 22:42:51

标签: go reflection reflect

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

.loc

所以,如果我这样做:

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

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

2 个答案:

答案 0 :(得分:0)

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

  • 一个reflect.Value值具有一个Type()函数,该函数返回一个reflect.Type值。
  • 如果该类型的Kind()reflect.Map,那么对于某些类型T1和T2,该reflect.Value是类型map[T1]T2的值,其中T1是键类型,T2是元素类型。

因此,在使用reflect时,我们可以像这样拉开碎片:

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

See a more complete example on the Go Playground。 (请注意,两个映射实际上都是nil,因此没有要枚举的键和值。)

答案 1 :(得分:0)

func handleMap(m interface{}) string {
    return fmt.Sprintf("%T", m)
}