Using Reflection to Modify Struct Fields: CanSet() and Structs
When using reflection to modify struct fields, it's important to understand the principles behind field accessibility and modification.
CanSet() for Structs
In your example, you encountered CanSet() returning false for struct fields. This is because by default, Go does not allow modifying non-exported (private) fields of a struct using reflection. This is a security measure to prevent accidental or malicious modification of internal struct state.
Addressing the Issues
To set the values of struct fields using reflection, consider the following steps:
Modified Code
Here's the modified code that addresses the issues:
<code class="go">func SetField(source interface{}, 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) } } 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>
This code will now successfully modify the Field1 value of the Entry struct.
The above is the detailed content of How to Use Reflection to Modify Struct Fields with CanSet() and Structs?. For more information, please follow other related articles on the PHP Chinese website!