This is a creation in Article, where the information may have evolved or changed.
Reflection
Reflection (reflect)
The so-called reflection (reflect) is the ability to check the state of the program at run time.
Using the Three Laws of reflection:
- Reflection can convert an "interface type variable" to a "reflection type Object";
- Reflection can convert a "Reflection type Object" to an "interface type variable";
- If you want to modify the "Reflection type Object", its value must be "writable";
Using reflect is generally divided into three steps:
1, to go to reflect is a type of value (these values have implemented an empty interface), first need to convert it into a reflect object (reflect. Type or reflect. Value):
Func TypeOf (i iterface{}) type //returns the types of values held in the interface, TYPEOF (nil) returns nil.
Func ValueOf (i iterface{}) value //Returns a value of value,valueof (nil) that is initialized to the specified value of the I-Interface custodian.
2. Convert the reflect object to a corresponding value, for example:
Tag: = T.elem (). Field (0). Tag //Gets the label defined inside the struct name: = V.elem (). Field (0). String () //Gets the value stored in the first field
3, get the reflection value can return the corresponding type and value
var x float64 = 3.4V: = reflect. ValueOf (x) fmt. Println ("type:", V.type ()) fmt. Println ("Kind is float64:", v.kind () = = reflect. Float64) fmt. Println ("Value:", V.float ())
Finally, reflecting the words, then the reflected field must be modifiable. The reflected field must be read-write, meaning that if the following is written, an error occurs
var x float64 = 3.4V: = reflect. ValueOf (x) v.setfloat (7.1)
If you want to modify the corresponding value, you must write this
var x float64 = 3.4P: = reflect. ValueOf (&x) V: = P.elem () v.setfloat (7.1)
struct tag
First look at an example, how to get the struct tag:
Type Userstruct{Namestring' user_name ' ageint' age '}func ( This*User) Addage () { This. Age + =1}func Main () {User:= &user{"John", -} t:=reflect. TypeOf (user) s:=T.elem () forI: =0; I < S.numfield (); i++{fmt. Println (S.field (i). TAG)}}