This is a creation in Article, where the information may have evolved or changed.
Golang reflection is very useful in certain scenarios, such as when I am in Web development, you can map a form to a struct by reflection, and you can automatically verify that the data is formatted correctly by using the Tag property defined by the struct, as in the following example:
We can use the form form
<form action="" method="POST"> <input type="text" name="Name" /> <input type="text" name="Age" /></form>
Map to the structure below.
type User struct{ Name string `valid:"String"` Age int `valid:"Int"` }
TypeOf Getting type information
valueof Getting value information
Package Mainimport ("FMT" "reflect") type a struct {Name stringage string}func (this a) Test () {fmt. Println ("Test OK.")} Func (this *a) Get () {fmt. Println ("Get OK.")} Func (this *a) Print (id int, name string) {FMT. PRINTLN ("ID is", id) fmt. Println ("name is", name)}func Test () {fmt. Println ("Func test is OK.")} Func Main () {d: = &a{name: "AAA", Age: "BBB"}v: = Reflect. ValueOf (d) Ele: = V.elem () T: = Ele. Type () fmt. Println ("\ n Read all properties of an object") for I: = 0; I < T.numfield (); i++ {fmt. Println (T.field (i). Name, Ele. Field (i). Interface ())}fmt. Println ("\ n Read all methods of an object") for I: = 0; I < T.nummethod (); i++ {fmt. Println (T.method (i). Name)}//Reflection call Method FMT. Println ("\ n test function call, it seems to be e-insured some, no error") V.methodbyname ("Get"). Call (nil) v.methodbyname ("Test"). Call (nil)//use Ele. Methodbyname ("GET"). Call (nil) throws an exception//but uses ele. Methodbyname ("Test"). is call (nil) normal? Because test does not use the pointer ele.methodbyname ("test"). Call (nil)//invokes the reflected FMT with parameters. Println ("\ n Test value call function") VId: = reflect. ValueOf (vname): = reflect. ValueOf ("Xiao Wang") v.methodbyname ("Print"). Call ([]reflect. value{VId, VName}) fmt. Println ("\ n Test parameter assignment, must be Ele") ele. Fieldbyname ("Name"). SetString ("haha") fmt. Println (d) C: = 123TC: = reflect. ValueOf (&c). Elem () TC. Setint (333) fmt. PRINTLN (TC, reflect. TypeOf (&c). Elem (). Name ()) fmt. Println (c)}