mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-12 16:52:29 +08:00
feat: add MapToStruct
This commit is contained in:
@@ -294,48 +294,6 @@ func DeepClone(src interface{}) interface{} {
|
||||
return result.Interface()
|
||||
}
|
||||
|
||||
// // CopyProperties copies each field from the source into the destination. It recursively copies struct pointers and interfaces that contain struct pointers.
|
||||
// func CopyProperties(dst, src interface{}) (err error) {
|
||||
// defer func() {
|
||||
// if e := recover(); e != nil {
|
||||
// err = errors.New(fmt.Sprintf("%v", e))
|
||||
// }
|
||||
// }()
|
||||
|
||||
// dstType, dstValue := reflect.TypeOf(dst), reflect.ValueOf(dst)
|
||||
// srcType, srcValue := reflect.TypeOf(src), reflect.ValueOf(src)
|
||||
|
||||
// if dstType.Kind() != reflect.Ptr || dstType.Elem().Kind() != reflect.Struct {
|
||||
// return errors.New("CopyProperties: param dst should be struct pointer")
|
||||
// }
|
||||
|
||||
// if srcType.Kind() == reflect.Ptr {
|
||||
// srcType, srcValue = srcType.Elem(), srcValue.Elem()
|
||||
// }
|
||||
// if srcType.Kind() != reflect.Struct {
|
||||
// return errors.New("CopyProperties: param src should be a struct or struct pointer")
|
||||
// }
|
||||
|
||||
// dstType, dstValue = dstType.Elem(), dstValue.Elem()
|
||||
|
||||
// propertyNums := dstType.NumField()
|
||||
|
||||
// for i := 0; i < propertyNums; i++ {
|
||||
// property := dstType.Field(i)
|
||||
// propertyValue := srcValue.FieldByName(property.Name)
|
||||
|
||||
// if !propertyValue.IsValid() || property.Type != propertyValue.Type() {
|
||||
// continue
|
||||
// }
|
||||
|
||||
// if dstValue.Field(i).CanSet() {
|
||||
// dstValue.Field(i).Set(propertyValue)
|
||||
// }
|
||||
// }
|
||||
|
||||
// return nil
|
||||
// }
|
||||
|
||||
// CopyProperties copies each field from the source into the destination. It recursively copies struct pointers and interfaces that contain struct pointers.
|
||||
// use json.Marshal/Unmarshal, so json tag should be set for fields of dst and src struct.
|
||||
func CopyProperties(dst, src interface{}) error {
|
||||
@@ -404,3 +362,16 @@ func GbkToUtf8(bs []byte) ([]byte, error) {
|
||||
b, err := io.ReadAll(r)
|
||||
return b, err
|
||||
}
|
||||
|
||||
// MapToStruct converts map to struct
|
||||
// Play: todo
|
||||
func MapToStruct(m map[string]interface{}, structObj interface{}) error {
|
||||
for k, v := range m {
|
||||
err := setStructField(structObj, k, v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user