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()
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.
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With