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

标签 go

虽然可以测试接口(interface){}是否是已知键/值类型的映射:

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" !!!

但是,如果我只想知道一个接口(interface){}是否是一个映射,而不用担心它的键/值类型呢?

最佳答案

为此,您可以使用 reflect 包。

package main

import "fmt"
import "reflect"

func main() {
    m := make(map[string]int)

    fmt.Printf("%v\n", isMap(m))
}

func isMap(m interface{}) bool {
    rt := reflect.TypeOf(m)
    return rt.Kind() == reflect.Map
}

关于go - 如何在不知道键/值类型的情况下测试接口(interface){}是否为映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17021356/

相关文章:

go - 如果修改信号处理程序中的ctx.rip和ctx.rsp会发生什么

http.Request RequestURI字段在go中发出请求时

go - 如何修复在 Windows 上压缩的 os.PathSeparator 解压缩文件?

go - 将不同类型重新分配给 Go 中的变量

c - 如何将Golang的cgo与链接到math.h的C库一起使用?

go - 如何使用go保存聚类模型?

android - 在 appengine 或 android 上,我在哪里可以获得应用内计费 v3 api 的 token ?

go - 从 golang 代码将文件发送到 Google Drive API 会产生错误 : Unsupported content with type: image/jpeg

go - 获取与 http.HandleFunc 匹配的当前模式

go - 如何在 golang net/smtp.sendmail 中定义发件人姓名?