api - 如何比较 map[string]interface{} 的值字符串与否

标签 api go controller beego

How to compare map[string]interface{} 's value string or not

m3 := map[string]interface{}{
"something":1,
"brawba":"Bawrbawr",
}

for key, value := range m3{
    if(reflect.TypeOf(value) == string or not){
        ... // here
    }else{
        ...
    }
}

https://play.golang.org/p/KjxMaGsMTOR

最佳答案

使用 type assertion确定值是否为 string:

for key, value := range m3 {
    if s, ok := value.(string); ok {
        fmt.Printf("%s is the string %q\n", key, s)
    } else {
        fmt.Printf("%s is not a string\n", key)
    }
}

使用 reflect 判断值的基类型字符串是否:

type mystring string

m3 := map[string]interface{}{
    "something": 1,
    "brawba":    "Bawrbawr",
    "foo":       mystring("bar"),
}

for key, value := range m3 {
    if reflect.ValueOf(value).Kind() == reflect.String {
        fmt.Printf("%s is a string with type %T and value %q\n", key, value, value)
    } else {
        fmt.Printf("%s is not a string\n", key)
    }
}

关于api - 如何比较 map[string]interface{} 的值字符串与否,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55962546/

相关文章:

api - Twitter Streaming API 使用的官方编码?是UTF-8吗?

api - 如何将 Julia 与 HTML 网页集成 - 如何从运行在 Web 浏览器中的应用程序调用 Julia 函数

json - github api 创建问题返回状态 422

go - 如何在Go中创建共享队列?

grails - 如何从grails中的 Controller 操作中搜索驱动器中的文件夹?

ruby-on-rails - 在 `match` 文件中使用 `routes.rb` 时,如何指定自定义 POST 操作?

ios - 不工作 - 在 Swift 3/4 中以编程方式在 Api 中注册用户

Gosublime:它如何在工作时向我显示函数的参数信息

go - 如何强制对自定义 Controller 中的 SharedIndexInformer 进行完全重新同步

javascript - 使用 converse.js 以编程方式发送消息?