Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Clubbing values of type switch

Following code is working fine

var requestMap map[string]interface{}
for _, value := range requestMap {
    switch v := value.(type) {
    case []interface{}:
        if len(v) == 0 {
            // if is empty then no need to throw NA
            return http.StatusOK, nil
        }
    case string:
        if len(v) == 0 {
            // if is empty then no need to throw NA
            return http.StatusOK, nil
        }
    }
}

But following code is giving invalid argument for len function, I have read this question

var requestMap map[string]interface{}
for _, value := range requestMap {
    switch v := value.(type) {
    case []interface{}, string:
        if len(v) == 0 {
            // if is empty then no need to throw NA
            return http.StatusOK, nil
        }
    }
}

Isn’t this case statement enough to identify []interface{} or string as value type ?
Why is it still considering interface{} as parameter of len()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you list multiple types in a case of a type switch, the static type of the switch variable will be of the type of the original variable. Spec: Switch statements:

In clauses with a case listing exactly one type, the variable has that type; otherwise, the variable has the type of the expression in the TypeSwitchGuard.

So if the switch expression is v := value.(type), the of v in the matching case (listing multiple types) will be the type of value, in your case it will be interface{}. And the builtin len() function is not allowed to use on values of type interface{}.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading