dqx76962 2013-12-24 11:05
浏览 2535

如何在Go语言中检查变量类型是否为map

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?

  • 写回答

2条回答 默认 最新

  • dongmao9217 2013-12-24 11:16
    关注

    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
    ", map1, reflect.ValueOf(map1).Kind() == reflect.Map)
       fmt.Printf("%v is a map? %v
    ", map2, reflect.ValueOf(map2).Kind() == reflect.Map)
       fmt.Printf("%v is a map? %v
    ", 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

    评论

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致