php editor Xiaoxin introduces you how to check whether a variable is a string, integer or floating point number. In PHP, we can use some built-in functions to achieve this purpose. First, use the is_string() function to check whether a variable is of string type. If true is returned, it means that the variable is of type string. Next, use the is_int() function to check whether a variable is of integer type. Likewise, if true is returned, it means that the variable is of integer type. Finally, use the is_float() function to check whether a variable is of floating point type. Likewise, if true is returned, it means that the variable is of floating point type. By using these functions, we can easily check the type of a variable and perform appropriate operations as needed.
Get this type map[string]interface{}
because I want to allow for both strings
and integers
map
But how do I convert a map to map[string]string
and return an error if any value is "not supported"?
value, ok := v.(string)
If the value is an integer, an error will be thrown
Go supports type switches:
For your use case it would look like:
m := map[string]string{} for k,v := range values { switch value := v.(type) { switch value := v.(type) { case int: m[k] = fmt.Sprintf("%v", value) case float64: m[k] = fmt.Sprintf("%v", value) case string: m[k] = fmt.Sprintf("%v", value) default: return nil,fmt.Errorf("unknown type %T", v) } } return m,nil
If you want, you can merge these cases into one case, for example //m.sbmmt.com/link/658953f1f681915f543a40eef9acb562
The above is the detailed content of Check if variable is string/int/float?. For more information, please follow other related articles on the PHP Chinese website!