各类型转 sturct

最后更新于:2022-04-02 02:36:48

[TOC] ## map 转 struct
main.go ``` 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() { return errors.New("Provided value type didn't match obj field type") } structFieldValue.Set(val) return nil } func MapToStruct(m map[string]interface{},result interface{}) error { for k, v := range m { err := SetField(result, k, v) if err != nil { return err } } return nil } func main() { type MyStruct struct { Name string Age int64 } myData := make(map[string]interface{}) myData["Name"] = "Tony" myData["Age"] = int64(23) result := &MyStruct{} if err := MapToStruct(myData,result);err != nil { fmt.Println(err) } fmt.Println(result.Name) } ```

## []string 转 struct ``` func SliceString2Struct(strs []string,t *T) { v := reflect.ValueOf(t).Elem() num := v.NumField() for i:=0; i main.go ``` func setField(obj interface{}, key int, value interface{}) error { structValue := reflect.ValueOf(obj).Elem() structFieldValue := structValue.Field(key) if !structFieldValue.IsValid() { return fmt.Errorf("No such field: %v in obj", key) } if !structFieldValue.CanSet() { return fmt.Errorf("Cannot set %v field value", key) } structFieldType := structFieldValue.Type() val := reflect.ValueOf(value) if structFieldType != val.Type() { return errors.New("Provided value type didn't match obj field type") } structFieldValue.Set(val) return nil } // []string 转 struct func SilceStringToStruct(m []string,result interface{}) error { if reflect.TypeOf(result).Kind() != reflect.Ptr { panic("result 必须是指针") } for k, v := range m { err := setField(result, k, v) if err != nil { return err } } return nil } // []Interface{} 转 struct func SilceInterfaceToStruct(m []interface{},result interface{}) error { if reflect.TypeOf(result).Kind() != reflect.Ptr { panic("result 必须是指针") } for k, v := range m { err := setField(result, k, v) if err != nil { return err } } return nil } func main() { //[]map 换sturct type MyStruct struct { Name string Age string } myData :=[]string{"cph","21"} result := &MyStruct{} if err := MapToStruct(myData,result);err != nil { Println(err) } Println(result) // &{cph 21} // []interface{} 转 sturct type MyStruct struct { Name string Age int } myData :=[]interface{}{"cph",21} result := &MyStruct{} if err := SilceInterfaceToStruct(myData,result);err != nil { log.Println(err) } log.Println(result.Age==21) // &{cph 21} } ```
';