Examples of several reflections: 1) Simple Type reflection, 2) complex type reflection, 3) modifiable properties for reflected data
1. Simple Type Reflection
1.1) Code
Package Mainimport ("FMT" "reflect") Func main () {varx 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 ())}
1.2) running Results
is true 3.4
2. Complex Type Reflection
2.1) Code
1 Package Main2 3 Import (4 "FMT"5 "reflect"6 )7 8Type Tstruct {9AintTenBstring One } A - Func Main () { -T: = t{203,"mh203"} theS: = reflect. ValueOf (&t). Elem () -Typeoft: =S.type () - forI: =0; I < S.numfield (); i++ { -F: =S.field (i) +Fmt. Printf ("%d:%s%s =%v\n", I, - Typeoft.field (i). Name, F.type (), F.interface ()) + } A}
2.2) Running results
0 int 203 1 string = mh203
3. Configurable properties of variables obtained through reflection
3.1) Code example
1 Package Main2 3 Import (4 "FMT"5 "reflect"6 )7 8 func TestA () {9 varx float64 =3.4TenV: =reflect. ValueOf (x) One if(true==V.canset ()) { AFmt. Println ("V is setable") - //V.set (4.1) -}Else { theFmt. Println ("v is not setable") - } - } - + func Testb () { - varx float64 =3.4 +P: = reflect. ValueOf (&x) AFmt. Println ("type of P:", P.type ()) atFmt. Println ("Settablitty of P:", P.canset ()) - -V: =P.elem () -Fmt. Println ("Settablitty of V:", V.canset ()) - -V.setfloat (7.1) in FMT. Println (V.interface ()) - FMT. PRINTLN (x) to } + - Func Main () { the TestA () * Testb () $}
3.2) Running results
Setis*falsetrue7.17.1
Go language Exercise: Reflection