doudao1950 2013-06-10 10:06
浏览 18
已采纳

如何在不知道键/值类型的情况下测试接口{}是否为映射?

Although it is possible to test whether an interface{} is a map of known key/value type:

func TypeTest(thing interface{}) {
    switch thing.(type) {
    case map[string]string:
        fmt.Println("map string string")
    case map[string]interface{}:
        fmt.Println("map string")
    case map[interface{}]interface{}:
        fmt.Println("map")
    case interface{}:
        fmt.Println("interface")
    default:
        fmt.Println("unknown")
    }
}
TypeTest(map[string]string{"a": "1"}) // "map string string"
TypeTest(map[string]int{"a": 1}) // "interface" !!!

But what if I just want to know whether an interface{} is a map or not, without worrying about its key/value type?

  • 写回答

1条回答 默认 最新

  • douche5961 2013-06-10 10:24
    关注

    You can use the reflect package for this.

    package main
    
    import "fmt"
    import "reflect"
    
    func main() {
        m := make(map[string]int)
    
        fmt.Printf("%v
    ", isMap(m))
    }
    
    func isMap(m interface{}) bool {
        rt := reflect.TypeOf(m)
        return rt.Kind() == reflect.Map
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 ARIMA模型时间序列预测用pathon解决
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)