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)}