Skip to content

Instantly share code, notes, and snippets.

@tokubass
Created December 6, 2018 17:14
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 tokubass/30bb4620b435c155b7540f28ccf69ebf to your computer and use it in GitHub Desktop.
Save tokubass/30bb4620b435c155b7540f28ccf69ebf to your computer and use it in GitHub Desktop.
map to struct
package main
import (
"fmt"
"github.com/mitchellh/mapstructure"
r "reflect"
)
type S struct {
Name string
Age int
Embed C
}
type C struct {
ID uint
}
func main() {
s := S{Age: 8}
input := map[string]interface{}{
"Name": "nameeee",
"Age": 10,
"Embed": C{ID: 16},
}
err := mapstructure.Decode(input, &s)
if err != nil {
fmt.Printf("%#v\n", err)
}
fmt.Printf("%#v\n", s)
s2 := S{Age: 9}
input2 := map[string]interface{}{
"Name": "nameeee",
"Age": 10,
"Embed": C{ID: 16},
}
MapToStruct(input2, &s2)
fmt.Printf("%#v\n", s2)
}
func MapToStruct(mapVal map[string]interface{}, val interface{}) (ok bool) {
structVal:= r.Indirect(r.ValueOf(val))
for name, elem := range mapVal {
structVal.FieldByName(name).Set(r.ValueOf(elem))
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment