Home > Backend Development > Golang > Check if variable is string/int/float?

Check if variable is string/int/float?

PHPz
Release: 2024-02-09 18:00:10
forward
740 people have browsed it

检查变量是否为 string/int/float?

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.

Question content

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)
Copy after login

If the value is an integer, an error will be thrown

Solution

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
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template