Browse Source

experimenting with recursive update

reid 2 năm trước cách đây
mục cha
commit
65ce4c9a22
1 tập tin đã thay đổi với 15 bổ sung13 xóa
  1. 15 13
      broadcast/broadcast.go

+ 15 - 13
broadcast/broadcast.go

@@ -265,27 +265,29 @@ func recursiveUpdate(dst, src reflect.Value) error {
         return nil
     }
 	// If dst is a struct and src is a map, handle them field by field
-	if dst.Kind() == reflect.Struct && src.Kind() == reflect.Map {
+	if dst.Kind() == reflect.Map && src.Kind() == reflect.Map {
+		if dst.IsNil() {
+			dst.Set(reflect.MakeMap(dst.Type()))
+		}
 		for _, key := range src.MapKeys() {
-			dstField := dst.FieldByName(key.String())
-			if !dstField.IsValid() {
-				return fmt.Errorf("field %s does not exist in the struct", key.String())
-			}
-			fmt.Printf("Updating key: %s with value of type: %s\n", key.String(), src.MapIndex(key).Type())
-			// Initialize the map if it's nil and we're trying to set a map
-			if dstField.Kind() == reflect.Map && dstField.IsNil() && src.MapIndex(key).Kind() == reflect.Map {
-				dstField.Set(reflect.MakeMap(dstField.Type()))
-			}
-			if !dstField.CanSet() {
-				return fmt.Errorf("field %s is not settable in the struct", key.String())
+			dstVal := dst.MapIndex(key)
+			// If the value in the map is a struct, create a new instance for modification
+			if dstVal.Kind() == reflect.Struct {
+				tmpVal := reflect.New(dstVal.Type()).Elem()
+				tmpVal.Set(dstVal)
+				dstVal = tmpVal
 			}
 			srcVal := src.MapIndex(key)
 			if srcVal.Kind() == reflect.Interface {
 				srcVal = srcVal.Elem()
 			}
-			if err := recursiveUpdate(dstField, srcVal); err != nil {
+			if err := recursiveUpdate(dstVal, srcVal); err != nil {
 				return err
 			}
+			// If the value in the map was a struct, update the map with the modified struct
+			if dstVal.Kind() == reflect.Struct {
+				dst.SetMapIndex(key, dstVal)
+			}
 		}
 		return nil
 	}