Go language Exercise: Reflection

Source: Internet
Author: User

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

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.