Golang's reflection (emphasis!!) )

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

1. Reflection: Can dynamically get information about variables at run time

Import ("reflect")

Two functions:

Reflect. TypeOf ()//Gets the type of the variable and returns the reflect. Type types
Reflect. ValueOf ()//Gets the value of the variable and returns the reflect. Value type
Reflect. Value.kind ()//Gets the category of the variable, returns a constant
Reflect. Value.interface ()//Convert to interface{} type

Reversible State

Example usage

Package Mainimport ("FMT"    "reflect") Type Studentstruct{Namestring Ageintscore Float32}func Test (bInterface{}) {T:=reflect. TypeOf (b) fmt. Println (t) V:=reflect. ValueOf (b) K:=v.kind () fmt. Println (k) IV:=v.interface () Stu, OK:=Iv.. (Student)ifOK {fmt. Printf ("%v%t\n", Stu, Stu)}} Func Testint (bInterface{}) {val:=reflect. ValueOf (b) C:=val. Int () fmt. Printf ("get Value interface{}%d\n", C)} Func Main () {varA Student =student{Name:"stu01", Age: -, Score: the,} test (a) Testint (1234)}
Reflection Usage
Package Mainimport ("FMT"    "reflect") Func main () {varX float64=3.4FMT. Println ("Type:", reflect. TypeOf (x)) V:=reflect. ValueOf (x) fmt. Println ("Value:", V) fmt. Println ("Type:", V.type ()) fmt. Println ("Kind:", V.kind ()) fmt. Println ("Value:", V.float ()) fmt. Println (V.interface ()) fmt. Printf ("value is%5.2e\n", V.interface ()) Y:=V.interface (). (float64) fmt. Println (y)}
Reflex Exercises

Get the value of a variable

Reflect. ValueOf (x). Float () reflect. ValueOf (x). Int () reflect. ValueOf (x). String () reflect. ValueOf (x). Bool ()

Reflection Elem () method of modifying pointers

Package Main//dynamically modifying the value of a variable by reflectionImport ("FMT"    "reflect") Type Studentstruct{Namestring Ageintscore Float32}func Test (bInterface{}) {T:=reflect. TypeOf (b) fmt. Println (t) V:=reflect. ValueOf (b) K:=v.kind () fmt. Println (k) IV:=v.interface () Stu, OK:=Iv.. (Student)ifOK {fmt. Printf ("%v%t\n", Stu, Stu)}} Func Testint (bInterface{}) {val:=reflect. ValueOf (b) Val. Elem (). Setint ( -)//val. Elem (). Setint () is equivalent to pointer manipulationC:=val. Elem (). Int () fmt. Printf ("Get value interface{}%d\n", c) fmt. Printf ("string val:%d\n", Val. Elem (). Int ())}func main () {varA Student =student{Name:"stu01", Age: -, Score: the,} test (a)varBint=1b= $Testint (&b) fmt. Println (b)}
val. Elem (). Setint ()

Using reflection to manipulate structure body

Reflect. Value.numfield () Gets the number of fields in the struct reflect. Value.method (n). Call to strip the method in the structure body

Reflection gets the number of struct methods, number of fields

Package Main//dynamically modifying the value of a variable by reflectionImport ("FMT"    "reflect") Type Studentstruct{Namestring Ageintscore float32 Sexstring}func (S Student) Set (namestring, ageint, score float32, sexstring) {S.name=name S.age=Age S.score=score S.sex=Sex}func teststruct (aInterface{}) {val:=reflect. ValueOf (a) KD:=val. Kind ()ifkd! =reflect. Struct {fmt. Println ("expect struct")        return} num:=val. Numfield () fmt. Printf ("struct has%d fields\n", num) Numofmethod:=val. Nummethod () fmt. Printf ("struct has%d methods\n", Numofmethod)} Func Main () {vara Student a=student{Name:"stu01", Age: -, Score:92.8,    } Teststruct (a) fmt. Println (a)}
code in this

Reflex Exercises

Package Main//dynamically modifying the value of a variable by reflectionImport ("FMT"    "reflect") Type Notknowntypestruct{S1stringS2stringS3string}//defines a string methodFunc (n notknowntype) String ()string {    returnN.S1 +"-"+ N.s2 +"-"+N.S3}varSecretInterface{} = notknowntype{"Ada","Go","Oberon"}func Main () {value:= Reflect. ValueOf (Secret)//<main. Notknowntype value>Typ: = reflect. TypeOf (Secret)//Main. NotknowntypeFMT. Println (Typ) KND:= value. Kind ()//structFMT. Println (KND) forI: =0; I < value. Numfield (); i++{fmt. Printf ("Field%d:%v\n", I, value. Field (i))} results:= value. Method (0). Call (nil) fmt. PRINTLN (Results)//[Ada-go-oberon]}
Reflex Exercises

Modifying a struct by reflection

Package Mainimport ("FMT"    "reflect") Type Tstruct{AintBstring}func Main () {t:= t{ at,"Skidoo"} s:= 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 ())} S.field (0). Setint ( the) S.field (1). SetString ("Sunset Strip") fmt. Println ("T is now", T)}
reflection Modify Structure body

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.