Go language reflection allows manipulating variable values at runtime, including modifying Boolean values, integers, floating point numbers, and strings. By getting the Value of a variable, you can call the SetBool, SetInt, SetFloat and SetString methods to modify it. For example, you can parse a JSON string into a structure and then use reflection to modify the values of the structure fields. It should be noted that the reflection operation is slow and unmodifiable fields cannot be modified. When modifying the structure field value, the related fields may not be automatically updated.
Use Go reflection to dynamically modify variable values
Reflection is a powerful tool that allows Go programs to manipulate variables at runtime value. It is useful for implementing various advanced features such as dynamic typing and code generation.
Basics
The reflection API contains type reflect.Value
, which represents a value. You can use reflect.ValueOf(x)
to get the Value of a specific variable.
Value has the following methods, which can be used to modify the value:
SetBool(v)
, SetInt(v)
, SetFloat(v)
: Set Boolean values, integers and floating point numbersSetString(v)
: Set stringSet(v)
: Set any value, manual type conversion is required Practical case
The following is an example of using reflection to parse a JSON string into a structure :
import ( "encoding/json" "reflect" ) type User struct { Name string Age int } func main() { jsonStr := `{ "Name": "John", "Age": 30 }` u := &User{} // 解析 JSON 字符串到 Value v := reflect.ValueOf(u).Elem() err := json.Unmarshal([]byte(jsonStr), u) if err != nil { panic(err) } // 使用反射修改字段值 v.FieldByName("Name").SetString("Alice") // 输出修改后的值 fmt.Printf("User: %+v\n", u) }
Note
When using reflection, you need to pay attention to the following points:
The above is the detailed content of How to use reflection to dynamically modify variable values in golang. For more information, please follow other related articles on the PHP Chinese website!