Created
March 7, 2018 11:00
-
-
Save manigandand/19370209a4d545b105a81de7b40690c6 to your computer and use it in GitHub Desktop.
Convert type interface to map using reflect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"reflect" | |
) | |
type Book struct { | |
ID int | |
Title string | |
Year int | |
} | |
func main() { | |
m := map[string]Book{"foo": Book{Title: "Bar"}, "quux": Book{Title: "Baz"}} | |
v := reflect.ValueOf(m) | |
if v.Kind() == reflect.Map { | |
for _, key := range v.MapKeys() { | |
strct := v.MapIndex(key) | |
fmt.Println(key.Interface(), strct.Interface()) | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment