Home >Backend Development >Golang >How to Iterate Over a Map Reflected from an Interface{}?
Q: Converting Interface{} to Map and Iterating Over It
In an attempt to create a generic function that can accept various data structures, including structs, slices of structs, and maps with string keys and struct values, you are encountering an error when attempting to iterate over a map. Reflecting upon the interface reveals that it is indeed a map, but accessing its elements through range iteration results in an error.
A: Using a Type Switch or Value.MapKeys
There are two approaches to resolve this issue:
Type Switch:
For example:
switch in := in.(type) { case map[string]*Book: for key, value := range in { fmt.Printf("Key: %s, Value: %v\n", key, value) } default: // Handle other cases as needed. }
Value.MapKeys:
For example:
v := reflect.ValueOf(in) keys := v.MapKeys() for _, key := range keys { value := v.MapIndex(key) fmt.Printf("Key: %v, Value: %v\n", key.Interface(), value.Interface()) }
The above is the detailed content of How to Iterate Over a Map Reflected from an Interface{}?. For more information, please follow other related articles on the PHP Chinese website!