如何检查变量类型是Go语言中的map

emi*_*tle 6 go

map1 := map[string]string{"name":"John","desc":"Golang"}
map2 := map[string]int{"apple":23,"tomato":13}
Run Code Online (Sandbox Code Playgroud)

那么,如何检查变量类型是Go语言中的映射?

Eve*_*man 9

您可以使用reflect.ValueOf()函数来获取这些映射的值,然后从Value获取Kind,它具有Map条目(reflect.Map).

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

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

这是一个与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)
}
Run Code Online (Sandbox Code Playgroud)

打印:

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
Run Code Online (Sandbox Code Playgroud)

如果您想知道更具体的地图类型,可以使用reflect.TypeOf():

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