Skip to content

Instantly share code, notes, and snippets.

@manigandand
Created March 7, 2018 11:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manigandand/19370209a4d545b105a81de7b40690c6 to your computer and use it in GitHub Desktop.
Save manigandand/19370209a4d545b105a81de7b40690c6 to your computer and use it in GitHub Desktop.
Convert type interface to map using reflect
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