-2

I have method which accepts map[string]interface{} parameters (it comes from parsed YAML file):

func load(params map[string]interface{}) error {
}

This method is trying to extract one element from params and cast it to map[string]interface{}:

if tmp, has := params["badges"]; has {
    if badges, ok := tmp.([]map[string]interface{}); ok {
       // ...
    } else {
        return fmt.Errorf("expected []map[string] but was: %T", tmp)
    }
}

When I run this method with correct params (with element badges of type []map[string]string) it fails with error:

expected []map[string] but was: []interface {}

But if I go through all items manually and cast them one by one, it will be OK:

lst := tmp.([]interface{})
ifaces := make([]map[interface{}]interface{}, len(lst), len(lst))
for pos, item := range lst {
    ifaces[pos] = item.(map[interface{}]interface{})
}
badges := make([]map[string]interface{}, len(lst), len(lst))
for pos, mp := range ifaces {
    badges[pos] = make(map[string]interface{})
    for k, v := range mp {
        badges[pos][k.(string)] = v
    }
}

But the second solution looks overcomplicated for just casting one type to another. Is it possible to cast interface{} to list of maps simpler?

Kirill
  • 7,580
  • 6
  • 44
  • 95

1 Answers1

2

Is it possible to cast interface{} to list of maps simpler?

No, of course not. See also https://golang.org/doc/faq#convert_slice_of_interface

(Especially as there are absolutely no type casts in Go and you also cannot do the type conversion.)

Volker
  • 40,468
  • 7
  • 81
  • 87