Go fast-14-reflection

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

Directory

      • Reflective Reflection
        • Using reflection
          • Premise
          • Define a structure and method
          • Reflect all fields and methods
        • Accessing anonymous fields in a structure
        • Dynamically modifying the value of a property
        • Dynamic Call method

Summary

Use reflection, anonymous fields, dynamically modify properties, dynamically invoke methods

Reflective Reflection

Using reflection

Premise

Package must be referenced before using reflectionreflect

Define a structure and method

import"reflect"typestruct {    Id   int    string    Age  int}func (u User) say() {    fmt.Println("hello")}u := User{Id: 1"Peter", Age: 20}

Reflect all fields and methods

    • reflect.TypeOf(o)Used to get type prototypes
    • reflect.ValueOf(o)Used to get the value

Note that if you want to access the value of a field, the field should be public , and the method should be calledpublic

funcInfo (oInterface{}) {//Get prototype of parameter typeT: = reflect. TypeOf (o) fmt. Println ("T", T)//t Main. UserFmt. Println ("T.name ()", T.name ())//t.name () UserFmt. Println ("T.numfield ()", T.numfield ())//t.numfield (3)V: = reflect. ValueOf (o) fmt. Println ("V", V)//v <main. User value>    //detection type    ifK: = T.kind (); K! = reflect. Struct {return}//Output Properties     forI: =0; I < T.numfield (); i++ {f: = T.field (i)//The Field must be public at this timeVal: = V.field (i). Interface () fmt. Println (F.name, F.type, Val)//--> outputs        //id int 1        //name string Peter        //age int} FMT. Println ()//Output method     forI: =0; I < T.nummethod (); i++ {m: = T.method (i) fmt. Println (M.name, M.type)//-->outputs        //say func (main. User)}}info (U)

Accessing anonymous fields in a structure

typeManagerstruct{User titlestring}//typeM: = Manager{title:"Manager", User:user{id:2, Name:"Jane", Age: A}}t: = reflect. TypeOf (m) F: = T.fieldbyindex ([]int{0,1}) fmt. Println ("F", F.name, F.type)//f Name String//valueV: = reflect. ValueOf (m) Val: = V.fieldbyindex ([]int{0,1}). Interface () fmt. Println ("Val", Val)//val Jane

Using the method reflect.FieldByIndex() , the parameter of the method is slice that the "0" of the first position above represents the Manager's number No. 0 attribute (user), and 1 represents the user's 1th number attribute (Name)

Dynamically modifying the value of a property

funcSet (oInterface{}) {V: = reflect. ValueOf (o)////Determines whether the pointer is of type and writable    ifK: = V.kind (); K! = reflect. Ptr | | !v.elem (). Canset () {fmt. Println ("Invalid type")return} v = V.elem () F: = V.fieldbyname ("Name")//Determine if the specified attribute exists    if!f.isvalid () {fmt. Println ("Invalid name")return}ifF.kind () = = reflect. String {f.setstring ("a")}}u: = User{id:1, Name:"Peter", Age: -}fmt. Println ("U.name", U.name)//u.name PeterSet (&u) fmt. Println ("U.name", U.name)//u.name aSet (U)

Note that this is done by passing in pointers to dynamically modify the

Dynamic Call method

Note that the method should be called when the method ispublic

func  (U User) Hello ( Name string ) {fmt. Println ( "hello" , name,  "My name is" , u.name)}u: = User{id: 1 , Name:  "Peter" , Age: }v = reflect. ValueOf (u) MN: = V.methodbyname ( "Hello" ) args: = []reflect. Value{reflect. ValueOf ( "Andy" )}mn. Call (args) fmt. Println ( "U.name" , u.name) //hello Andy my Name is a 

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.