Preface
In development, we often need to perform reflection operations on structures, variables, etc. Using reflection can directly operate variables, types and other related information, which makes our code more abstract and flexible, making the program The logic is clearer and simpler. Among them, golang provides the reflection-related package reflect
. This article will focus on the reflect
package to describe how to use reflection to set variables.
Basics
Before we dive into how to set variables using reflection, we need to understand some basics.
Type
: The type of the variable. Use the reflect.TypeOf()
method to get the type of the variable. Value
: It can be understood as the value of a variable, and the value of the variable can be obtained using the reflect.ValueOf()
method. reflect.Value
The following properties exist:
Kind()
: Get the type of value, the return value is reflect.Kind
Type. Int()
、Float()
、Bool()
、String()
、Bytes ()
, Interface()
, etc.: Get the corresponding value. Set()
: Set the value, but you need to ensure that the current value is of a settable type. For details, please refer to reflect.Value.Set()
. Reflection setting value
Reflection setting variables are mainly divided into the following steps:
of the variable reflect.Value
value; reflect.Value.Set()
method; Take the sample code as an example:
type Person struct { Name string Age int } func main() { p := Person{ Name: "John", Age: 25, } v := reflect.ValueOf(p) if v.Kind() == reflect.Struct { name := v.FieldByName("Name") age := v.FieldByName("Age") if name.IsValid() && name.CanSet() { name.SetString("Tom") } if age.IsValid() && age.CanSet() { age.SetInt(30) } } fmt.Println(p) }
Among them:
The variable is
reflect.Value Type, get the
Value of the variable
p;
The reflect.Value
value of Name and
Age;
and
age are settable The value must satisfy the validity and settability. For details, please refer to
reflect.Value.CanSet();
Modification of
Name and
Age properties.
panic exception will be thrown.
The above is the detailed content of golang reflection setting variables. For more information, please follow other related articles on the PHP Chinese website!