使用反射设置嵌套结构体字段
问题:
我们如何使用反射以持久的方式修改嵌套结构体字段的值?
代码:
<code class="go">type ProductionInfo struct { StructA []Entry } type Entry struct { Field1 string Field2 int } func SetField(source interface{}, fieldName string, fieldValue string) { v := reflect.ValueOf(source) tt := reflect.TypeOf(source) for k := 0; k < tt.NumField(); k++ { fieldValue := reflect.ValueOf(v.Field(k)) fmt.Println(fieldValue.CanSet()) if fieldValue.CanSet() { fieldValue.SetString(fieldValue.String()) } } } func main() { source := ProductionInfo{} source.StructA = append(source.StructA, Entry{Field1: "A", Field2: 2}) SetField(source, "Field1", "NEW_VALUE") }</code>
问题:
解决方案:
修改对 SetField 的调用以定位嵌入的 Entry struct:
<code class="go">SetField(source.StructA[0], "Field1", "NEW_VALUE")</code>
更改函数以接受和修改指向 Entry 的指针:
<code class="go">func SetField(source *Entry, fieldName string, fieldValue string) { v := reflect.ValueOf(source).Elem() fmt.Println(v.FieldByName(fieldName).CanSet()) if v.FieldByName(fieldName).CanSet() { v.FieldByName(fieldName).SetString(fieldValue) } }</code>
最终代码:
<code class="go">package main import ( "fmt" "reflect" ) type ProductionInfo struct { StructA []Entry } type Entry struct { Field1 string Field2 int } func SetField(source *Entry, fieldName string, fieldValue string) { v := reflect.ValueOf(source).Elem() if v.FieldByName(fieldName).CanSet() { v.FieldByName(fieldName).SetString(fieldValue) } } func main() { source := ProductionInfo{} source.StructA = append(source.StructA, Entry{Field1: "A", Field2: 2}) fmt.Println("Before: ", source.StructA[0]) SetField(&source.StructA[0], "Field1", "NEW_VALUE") fmt.Println("After: ", source.StructA[0]) }</code>
输出:
Before: {A 2} true After: {NEW_VALUE 2}
以上是如何使用反射修改嵌套结构体字段来实现持久化?的详细内容。更多信息请关注PHP中文网其他相关文章!