打印 Golang 映射的 key/value 类型
Print the key/value types of a Golang map
我正在尝试打印地图类型,例如: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"
但我想不出正确的调用方式。
尽量不要使用reflect
。但是如果你必须使用 reflect
:
- 一个
reflect.Value
值有一个Type()
函数,returns一个reflect.Type
值。
- 如果该类型的
Kind()
是 reflect.Map
,则 reflect.Value
是某些类型 T1 和 T2 的类型 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,因此没有要枚举的键和值。)
func handleMap(m interface{}) string {
return fmt.Sprintf("%T", m)
}
我正在尝试打印地图类型,例如: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"
但我想不出正确的调用方式。
尽量不要使用reflect
。但是如果你必须使用 reflect
:
- 一个
reflect.Value
值有一个Type()
函数,returns一个reflect.Type
值。 - 如果该类型的
Kind()
是reflect.Map
,则reflect.Value
是某些类型 T1 和 T2 的类型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,因此没有要枚举的键和值。)
func handleMap(m interface{}) string {
return fmt.Sprintf("%T", m)
}