Map maps to structs, where only simple data types are supported, and complex needs are expanded
Package Mainimport ("Errors" "FMT" "Reflect" "StrConv" "Time") type User struct {Name stringage int8date time. Time}func Main () {data: = Make (map[string]interface{}) data["Name"] = "Zhang San" data["age"] = 26data["Date"] = "2015-09-29 00:00 : xx "Result: = &user{}err: = fillstruct (data, result) fmt. Println (Err, FMT. Sprintf ("%+v", *result))}//fill structure with map func fillstruct (Data map[string]interface{}, obj interface{}) error {for k, V: = Range Data {err: = SetField (obj, K, v) if err! = Nil {return Err}}return nil}//replaces the value of the structure with the value of the map func setfield (obj interface{}, name s Tring, Value interface{}) error {structvalue: = reflect. ValueOf (obj). Elem ()//struct property value Structfieldvalue: = Structvalue.fieldbyname (name)//struct single property value if!structfieldvalue.isvalid () {return F Mt. Errorf ("No such field:%s in obj", name)}if!structfieldvalue.canset () {return FMT. Errorf ("Cannot set%s field value", name)}structfieldtype: = Structfieldvalue.type ()//struct type val: = Reflect. ValueOf (value)//map value of the reflection value Var err errorif StructfieldtypE! = val. Type () {val, err = Typeconversion (FMT. Sprintf ("%v", Value), Structfieldvalue.type (). Name ())//type convert if err! = Nil {return Err}}structfieldvalue.set (val) return nil}//type convert func typeconversion (value string, Ntype string) (reflect. Value, error) {if ntype = = "string" {return reflect. ValueOf (value), nil} else if ntype = = "time. Time "{T, err: = time. Parseinlocation ("2006-01-02 15:04:05", Value, time. Local) return reflect. ValueOf (t), err} else if ntype = = "Time" {T, err: = time. Parseinlocation ("2006-01-02 15:04:05", Value, time. Local) return reflect. ValueOf (t), err} else if ntype = = "int" {i, err: = StrConv. Atoi (value) return reflect. ValueOf (i), err} else if ntype = = "Int8" {i, err: = StrConv. parseint (value, ten), return reflect. ValueOf (int8 (i)), err} else if ntype = = "Int32" {i, err: = StrConv. parseint (value, ten), return reflect. ValueOf (Int64 (i)), err} else if ntype = = "Int64" {i, err: = StrConv. parseint (value, ten), return reflect. ValueOf (i), err} else if ntype = = "Float32" {i, err: = StrConv. Parsefloat (value, +) return reflect. ValueOf (float32 (i)), err} else if ntype = = "Float64" {i, err: = StrConv. Parsefloat (value, +) return reflect. ValueOf (i), err}//else if .... Add some other types of conversion return reflect. ValueOf (value), errors. New ("Unknown type:" + ntype)}
Golang map to struct