Package Main Import ( "Errors" "FMT" "Reflect" "StrConv" "Time" ) Type User struct { Name string Age int8 Date time. Time } Func Main () { Data: = Make (map[string]interface{}) data["Name" = "John" Data["Age" = 26 data["Date"] = "2015-09-29 00:00:00" 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 } Replace the value of a struct with the value of a map Func SetField (obj interface{}, name string, value interface{}) error { Structvalue: = reflect. valueof (obj). Elem ()//struct Body property value Structfieldvalue: = Structvalue.fieldbyname (name)//struct Body single property value 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: = Type of Structfieldvalue.type ()//struct body Val: = reflect. Reflection value of valueof (value)//map value var err error If Structfieldtype!= val. Type () { Val, err = Typeconversion (FMT. Sprintf ("%v", Value), Structfieldvalue.type (). Name ())//Type conversions If Err!= nil { return err } } Structfieldvalue.set (Val) return Nil } Type conversions 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, 10, 64) return reflect. valueof (int8 (i)), err else if ntype = = "Int32" { I, err: = StrConv. parseint (value, 10, 64) return reflect. valueof (Int64 (i)), err else if ntype = = "Int64" { I, err: = StrConv. parseint (value, 10, 64) return reflect. valueof (i), err else if ntype = = "Float32" { I, err: = StrConv. Parsefloat (value, 64) return reflect. valueof (float32 (i)), err else if ntype = = "Float64" { I, err: = StrConv. Parsefloat (value, 64) return reflect. valueof (i), err } else if ..... Add some other types of conversions return reflect. valueof (value), errors. New ("Unknown type:" + ntype) } |