-2

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

so if I do:

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

I want to get "map[int]string"

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

Tiya Jose
  • 1,359
  • 14
  • 24
  • 2
    Any reason why the simple `fmt.Printf("Type: %T\n", m)` is not sufficient? Try it out [here](https://play.golang.org/p/UxxAo-wukKo)! – ifnotak Feb 15 '20 at 22:47
  • yeah I think that should work, thanks! however, see the next comment –  Feb 15 '20 at 23:03
  • since I already have the value `x :=reflect.ValueOf(m)`, it would be nice if there were an api that could accept the Value x instead of the value m, if you follow –  Feb 15 '20 at 23:04
  • I am not sure I get what you mean.. Is it [this](https://play.golang.org/p/ES8omWuA4bf)?. – ifnotak Feb 15 '20 at 23:11
  • 2
    You should aim to avoid reflection whenever possible. – Jonathan Hall Feb 15 '20 at 23:15

2 Answers2

2
func handleMap(m interface{}) string {
    return fmt.Sprintf("%T", m)
}
Andrew W. Phillips
  • 3,254
  • 1
  • 21
  • 24
1

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

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

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

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

torek
  • 448,244
  • 59
  • 642
  • 775