Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang reflect, how to get map value type?

Tags:

reflection

go

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()
like image 594
navins Avatar asked Jul 31 '16 07:07

navins


People also ask

Is Golang map value type?

What map types exist in Go? There's no specific data type in Golang called map ; instead, we use the map keyword to create a map with keys of a certain type, and values of another type (or the same type). In this example, we declare a map that has string s for its keys, and float64 s for its values.

What is reflect value?

The reflect. ValueOf() Function in Golang is used to get the new Value initialized to the concrete value stored in the interface i. To access this function, one needs to imports the reflect package in the program.

How do you check for the existence of a key in a map in go?

When we execute the call to mymap['key'] we get back two distinct values, the first of which is the value of the key and the second is a bool value which represents whether or not the given key exists within the map. This second value is what we use to check if a given key exists in the if statement on line 13.

What is reflect indirect?

The reflect. Indirect() Function in Golang is used to get the value that v points to, i.e., If v is a nil pointer, Indirect returns a zero Value. If v is not a pointer, Indirect returns v. To access this function, one needs to imports the reflect package in the program.


2 Answers

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
like image 198
Not_a_Golfer Avatar answered Oct 14 '22 07:10

Not_a_Golfer


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

like image 34
Pioz Avatar answered Oct 14 '22 05:10

Pioz