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{
...
}
}
最佳答案
使用 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/