emitle
emitle

Reputation: 343

How to check variable type is map in Go language

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

so,How to check variable type is map in Go language?

Upvotes: 14

Views: 15335

Answers (2)

Knoxy
Knoxy

Reputation: 157

You can use fmt and avoid using reflection.

func isMap(x interface{}) bool {
    t := fmt.Sprintf("%T", x)
    return strings.HasPrefix(t, "map[")
}

map1 := map[string]string{"name": "John", "desc": "Golang"}
fmt.Printf("map1 is a map? %t", isMap(map1))

Produces:

map1 is a map? true

https://play.golang.org/p/OVm-_jgz33r

Reflection is discouraged in Go. To quote Rob Pike, "Clear is better than clever" and "Reflection is never clear."

Upvotes: 1

Eve Freeman
Eve Freeman

Reputation: 33185

You can use the reflect.ValueOf() function to get the Value of those maps, and then get the Kind from the Value, which has a Map entry (reflect.Map).

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

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

Here's a more specific example that does the comparison with reflect.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 the more specific map type, you can use reflect.TypeOf():

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

Upvotes: 22

Related Questions