Go language reflect understanding

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

Many articles in the explanation of Golang reflection mechanism are more complex, here simple summary, to do a superficial introductory tutorial:

1. typeof method and valueof method

typeof is used to return the type of the variable, valueof the method used to return the variable.

When we initialize a struct, there are two ways, var a struct and a: =new (struct), where the type of the former is a struct, and the latter type is a pointer.

package mainimport ("fmt""reflect")type MyStruct struct {name string}func (this *MyStruct) GetName() string {return this.name}func main() {a := new(MyStruct)a.name = "yejianfeng"typ := reflect.TypeOf(a)fmt.Println(typ)fmt.Println("-------------------")var b MyStructb.name = "abc"fmt.Println(reflect.TypeOf(b))}

The output is as follows:

*main. MyStruct


Main. MyStruct

2,reflect. ValueOf (a). Fieldbyname method

If a is a structural body, reflect. ValueOf (a). Fieldbyname ("name") is equivalent to A.name.

If it is a pointer, valueof returns the type of the pointer, it does not have field, so it cannot be used Fieldbyname

3. Canset method

Canset returns True when value is addressable, otherwise false.

When the previous canset is a pointer (p) It is not addressable, but when it is p. Elem () (actually *p), which is an addressable

package mainimport ("fmt""reflect")type MyStruct struct {name string}func (this *MyStruct) GetName() string {return this.name}func main() {var a MyStructa.name = "xiangli"fmt.Println(reflect.ValueOf(a).FieldByName("name").CanSet()) //falsefmt.Println(reflect.ValueOf(&(a.name)).Elem().CanSet())      //truefmt.Println("--------------")var c string = "yejianfeng"p := reflect.ValueOf(&c)fmt.Println(p.CanSet())        //falsefmt.Println(p.Elem().CanSet()) //truep.Elem().SetString("newName")fmt.Println(c)}

Related Article

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.