Created
December 6, 2018 17:14
-
-
Save tokubass/30bb4620b435c155b7540f28ccf69ebf to your computer and use it in GitHub Desktop.
map to struct
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" | |
"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