Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 728
Elliot Avatar asked Jun 05 '26 18:06

Elliot


1 Answers

Use a type assertion to determine if the value is a 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)
    }
}

Use reflect to determine if the value's base type string:

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

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!