使用反射更新结构字段



我正在为实体实现部分更新。

实体结构如下所示

type Entity struct {
    Id       string `readonly:"true"`
    Spec     EntitySpec
    Status   EntityState
}

type EntitySpec struct {
    Version  *string `readonly:"true"`
    Users    []*User
    Field1   *InnerStruct1
    Field2   []*InnerStruct2
}

等等。

所以我尝试使用反射递归地迭代Entity结构字段并更新允许用户更新的字段:

func method(existingEntity interface{}, newEntity interface{}) {
    entityType := reflect.TypeOf(existingEntity)
    logger.Debugf("type: %v", entityType)
    for i := 0; i < entityType.NumField(); i++ {
        value := entityType.Field(i)
        logger.Debugf("Name: %s", value.Name)
        tag := value.Tag
        logger.Debugf("tag: %s", tag)
        if tag.Get("readonly") == "true" {
            logger.Debugf("readonly, go to next one")
            continue
        }
        oldField := reflect.Indirect(reflect.ValueOf(existingEntity).Field(i))
        newField := reflect.Indirect(reflect.ValueOf(newEntity).FieldByName(value.Name))
        logger.Debugf("type: %v", value.Type.Kind())
        if value.Type.Kind() == reflect.Struct {
            logger.Debugf("value: %v", oldField)
            //struct, go into it
            method(oldField.Interface(), newField.Interface())
        } else {
            if oldField != newField && oldField.String() != newField.String() {
                logger.Debugf("Type of old field: %v", oldField.Type())
                logger.Debugf("Type of new field: %v", newField.Type())
                logger.Debugf("Update: %v nTo %v", oldField, newField)
                oldField.Set(newField) //HERE I get the exception
            } else {
                logger.Debugf("Field values are equal")
            }
        }
    }
}

但是当我尝试使用 oldField.Set(newField) 分配一个新值时,我得到一个异常:

reflect: reflect.Value.Set using unaddressable value

我也尝试过reflect.ValueOf(existingEntity).Field(i).Set(reflect.ValueOf(newEntity).FieldByName(value.Name))但得到了同样的异常。

你能向我解释为什么会发生这种情况以及如何解决这个问题吗?

传递指向要更新的值的指针。 下面是更新为获取现有实体指针的函数:

func method(existingEntity interface{}, newEntity interface{}) {
  entityType := reflect.TypeOf(existingEntity).Elem()
  for i := 0; i < entityType.NumField(); i++ {
    value := entityType.Field(i)
    tag := value.Tag
    if tag.Get("readonly") == "true" {
        continue
    }
    oldField := reflect.ValueOf(existingEntity).Elem().Field(i)
    newField := reflect.ValueOf(newEntity).FieldByName(value.Name)
    if value.Type.Kind() == reflect.Struct {
        method(oldField.Addr().Interface(), newField.Interface())
    } else {
        oldField.Set(newField)
    }
  }
}

像这样使用它:

var a Example
b := Example{123, 456, Example2{789}}
method(&a, b)

在操场上运行

这将处理问题中的特定情况。如果需要深层克隆,则解决方案会更加复杂。

最新更新