简体   繁体   中英

How to iterate an array in an interface{}?

i have a map

myMap := make(map[string]interface{})

one of this map elements is array of []map[string]string

myMap["element"] = []map[string]string

how can i iterate this array?

You can't iterate over a value of type interface{} , which is the type you'll get returned from a lookup on any key in your map (since it has type map[string]interface{} ).

You should use a type assertion to obtain a value of that type, over which you can then range.

myElt := myMap["element"]
v, ok := myElt.([]map[string]string)
if !ok {
    // TODO: Handle the error
}

for i, item := range v {
    // TODO: do something with each map[string]string item in the slice
}

Here's a working playground example using a contrived setup for those map types.


If you know the value is of the specified slice type, you can omit the ok check in the type assertion. This might be the case if you are using someone else's generic map implementation (which has keys of type interface{} ) and know you only ever populate it with values of type []map[string]string . However, exercise caution: if you obtain a value not of this type from the map, and you omit the check, your program will panic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM