Anoymouswho
Anoymouswho

Reputation: 17

Using recursion to get the deeply nested struct in go

I need to parse an interface read from a JSON object which is deeply nested. I use the following recursive function to get most of the array.

func arrayReturn(m map[string]interface{}) []interface{} {
    for _, v:= range m {
        if v.(type) == map[string]interface{} {
            return arrayReturn(v.(map[string]interface{}))
        }
        if v.(type) == string {
            return v.([]interface{})
        } 
    }
}

Which gives this error for the return line:

syntax error: unexpected return, expecting expression

What does "expecting expression" mean?

Upvotes: 0

Views: 762

Answers (1)

icza
icza

Reputation: 417612

This syntax:

if v.(type) == map[string]interface{} { /* ... */ }

is invalid. You can't compare to a type, only to a value.

What you want may be solved using a type switch, where the cases are indeed types:

func arrayReturn(m map[string]interface{}) []interface{} {
    for _, v := range m {
        switch v2 := v.(type) {
        case map[string]interface{}:
            return arrayReturn(v2)     // v2 is of type map[string]interface{}
        case []interface{}:
            return v2                  // v2 is of type []interface{}
        }
    }
    return nil
}

Also note that if you use a short variable declaration after the switch keyword, in each case the type of the variable used will be what you specify in the case, so no further type assertion is needed!

Upvotes: 5

Related Questions