-2

我正在尝试打印地图的类型,例如: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"

但我想不出正确的电话。

4

2 回答 2

2
func handleMap(m interface{}) string {
    return fmt.Sprintf("%T", m)
}
于 2020-02-16T06:40:00.247 回答
1

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

  • 一个reflect.Value值有一个Type()函数,它返回一个reflect.Type值。
  • 如果该类型Kind()reflect.Map,那reflect.Valuemap[T1]T2某些类型 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)
}

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

于 2020-02-15T23:33:10.027 回答