Reflective Reflection
1. Reflection can greatly improve the flexibility of the program, so that interface{} has a greater scope of play
2. Reflection using the TypeOf and VALUEOF functions to get target object information from the interface
3. Reflection will use anonymous fields as separate fields (anonymous field nature)
4. Want to use reflection to modify the state of the object, if Interface.data is settable, that is Pointer-interface
5. The method can be called "dynamic" through reflection
Example one:
Example of reflection using TypeOf and ValueOf to get the attribute field of the passed-in type in the method
Package Mainimport ("FMT" "reflect")//Define a user structure bodyType Userstruct{IdintNamestring Ageint}//binding methods for interfacesfunc (U User) Hello () {fmt. Println ("Hello World.")}//define a function that can accept any type (use rules for NULL interfaces)Func Info (oInterface{}) {T:= Reflect. TypeOf (o)//gets the received to interface to the typeFmt. Println ("Type:", T.name ())//print the corresponding type to the name (which is brought to the reflect)//The Kind () method is to get the incoming type to the return type, and the following execution determines whether the incoming type is a struct ifK: = T.kind (); K! =reflect. Struct {fmt. Println ("the incoming type is wrong, please check!") return} V:= Reflect. ValueOf (o)//gets accepted to the interface type contained into the content (that is, to attribute fields and methods)Fmt. Println ("Fields :")//How do I print it to all the fields and content? /** through the interface type. Numfield gets the number of all fields in the current type*/ forI: =0; I < T.numfield (); i++{f:= T.field (i)//field to get the corresponding indexVal: = V.field (i). Interface ()//get the contents of the current fieldFmt. Printf ("%6s:%v =%v\n", F.name, F.type, Val)} /** through the interface type. Nummethod gets the number of all methods of the current type*/FMT. Println ("Method:") forI: =0; I < T.nummethod (); i++{m:= T.method (i)//how to get the corresponding indexFmt. Printf ("%6s:%v\n", M.name, M.type)}} Func main () {u:= user{1,"OK", A} Info (U)//info (&u) if passed into the struct to address, then in the Info function in the kind method to judge, will be intercepted back}
The results of the operation are as follows:
Type:userfields: id:int = 1 name:string = OK age:int = 12method:hello:func (main. User)
Continuous update ...
Need to increase exception handling section: http://www.runoob.com/go/go-error-handling.html
Reflect reflection of Go_09:go language Foundation