Home >Backend Development >Golang >How to Overcome SetCan() Always Returning False When Setting Struct Field Values Using Reflection?
Exploring Reflection with SetString for Structs
Reflection provides powerful tools for manipulating Go structures dynamically. In this example, we encounter a common issue when attempting to set the value of a struct field using reflection: CanSet() always returns false. This hindrance prevents field modifications, leaving us in a quandary.
Identifying the Pitfalls
The provided code snippet highlights two fundamental errors:
Resolving the Issues
After addressing these pitfalls, we can refine our code:
<code class="go">func SetField(source interface{}, fieldName string, fieldValue string) { v := reflect.ValueOf(source).Elem() // Obtain the value of the pointed object fmt.Println(v.FieldByName(fieldName).CanSet()) if v.FieldByName(fieldName).CanSet() { v.FieldByName(fieldName).SetString(fieldValue) } }</code>
In the modified SetField() function, we:
Code in Action
With these modifications, the code now successfully updates the Field1 value:
<code class="go">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>
Output:
Before: {A 2} true After: {NEW_VALUE 2}
The result showcases the successful modification of Field1 within the Entry struct.
The above is the detailed content of How to Overcome SetCan() Always Returning False When Setting Struct Field Values Using Reflection?. For more information, please follow other related articles on the PHP Chinese website!