navins
navins

Reputation: 3459

Golang reflect, how to get map value type?

For a map m in golang, we can get simply the key type using t.Key().

But I wonder how to get the map value type?

When the map is empty, we can not even use v.MapIndex, any idea?

m := map[string]int{}
t := reflect.TypeOf(m)
v := reflect.ValueOf(m)
t.Key()
v.MapIndex()

Upvotes: 16

Views: 16770

Answers (2)

Pioz
Pioz

Reputation: 6321

Here an example to get the type of the map keys and map elements:

package main

import (
    "fmt"
    "reflect"
)

func main() {
    fmt.Println("Hello, playground")
    var m map[string]int
    fmt.Println(reflect.TypeOf(m).Key())
    fmt.Println(reflect.TypeOf(m).Elem())
}

Playground here

Doc is here https://golang.org/pkg/reflect/#Type

Upvotes: 9

Not_a_Golfer
Not_a_Golfer

Reputation: 49187

Elem() of a map type will give you the element's type:

var m map[string]int
fmt.Println(reflect.TypeOf(m).Elem())
// output: int

Upvotes: 21

Related Questions