How to check the type of a variable - this is a map in Go

map1 := map[string]string{"name":"John","desc":"Golang"}
map2 := map[string]int{"apple":23,"tomato":13}

So, how to check the type of a variable - is it a map in Go?

+4
source share
1 answer

You can use the reflect.ValueOf () function to get the value of these maps, and then get the view from the value that has an entry in the map ( reflect.Map).

http://play.golang.org/p/5AUKxECqNA

http://golang.org/pkg/reflect/#Kind

Here is a more specific example that does a comparison with reflection. Map: http://play.golang.org/p/-qr2l_6TDq

package main

import (
   "fmt"
   "reflect"
)

func main() {
   map1 := map[string]string{"name": "John", "desc": "Golang"}
   map2 := map[string]int{"apple": 23, "tomato": 13}
   slice1 := []int{1,2,3}
   fmt.Printf("%v is a map? %v\n", map1, reflect.ValueOf(map1).Kind() == reflect.Map)
   fmt.Printf("%v is a map? %v\n", map2, reflect.ValueOf(map2).Kind() == reflect.Map)
   fmt.Printf("%v is a map? %v\n", slice1, reflect.ValueOf(slice1).Kind() == reflect.Map)
}

prints:

map[name:John desc:Golang] is a map? true
map[apple:23 tomato:13] is a map? true
[1 2 3] is a map? false

If you want to know a more specific type of map, you can use the reflection.TypeOf () function:

http://play.golang.org/p/mhjAAdgrG4

+7
source

All Articles