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

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

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)
    }
}