Skip to content

Instantly share code, notes, and snippets.

@bonfy
Last active September 3, 2018 13:02
Show Gist options
  • Save bonfy/15f13f39ddb07f65bb0cdbf066bad615 to your computer and use it in GitHub Desktop.
Save bonfy/15f13f39ddb07f65bb0cdbf066bad615 to your computer and use it in GitHub Desktop.
map2struct.go
package main
import (
"errors"
"fmt"
"reflect"
)
func SetField(obj interface{}, name string, value interface{}) error {
structValue := reflect.ValueOf(obj).Elem()
structFieldValue := structValue.FieldByName(name)
if !structFieldValue.IsValid() {
return fmt.Errorf("No such field: %s in obj", name)
}
if !structFieldValue.CanSet() {
return fmt.Errorf("Cannot set %s field value", name)
}
structFieldType := structFieldValue.Type()
val := reflect.ValueOf(value)
if structFieldType != val.Type() {
invalidTypeError := errors.New("Provided value type didn't match obj field type")
return invalidTypeError
}
structFieldValue.Set(val)
return nil
}
type MyStruct struct {
Name string
Age int64
}
func (s *MyStruct) FillStruct(m map[string]interface{}) error {
for k, v := range m {
err := SetField(s, k, v)
if err != nil {
return err
}
}
return nil
}
func main() {
myData := make(map[string]interface{})
myData["Name"] = "Tony"
myData["Age"] = int64(23)
result := &MyStruct{}
err := result.FillStruct(myData)
if err != nil {
fmt.Println(err)
}
fmt.Println(result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment