function

Go language pointer as function argument

Package main import "FMT" func main() {/* define local variables */ var a int= 100 var b int= 200 ftt.printf (" Printf(" %d\n", b) // "%d\n", b) //" %d\n", b) // "%d\n", b) 200 /* Call the function to swap values * &a to the address of a variable * &b to the address of b variable */ swap(&a, &b); Printf(" a: %d\n", a) // A: 200 ftt. Printf(" B: %d\n", b) // B: 200 ftt. Printf(" B: %d\n", b) 100 } func swap(x *int, {var temp int temp = *x /* x = *y /* y = temp /* y = temp /* y = temp /* y = temp /* y = temp / /}Copy the code

The structure of the body

The basic concept

There is no “class” in Golang, and structures in Golang are somewhat similar to classes in other languages

Golang base data types can be expressed in some of the basic properties of things, but when we want to express a thing all or part of the property, this time with a single basic data types cannot meet the demand, Golang provides a custom data types, multiple basic data types can be encapsulated, this data type is called structure, Struct. So we can define our own type from structs

Type Keyword User-defined type and type alias

Golang defines a structure with the type keyword

Custom type

There are some basic data types in Go, such as string, integer, floating point, Boolean, etc. In Go, you can use the type keyword to define custom types.

type myInt int
Copy the code

Type the alias

type TypeAlias = Type
Copy the code

The difference between custom types and type aliases

type myInt int type myFloat = float64 func main() { var a myInt = 10 fmt.Printf("%v %T\n", a, A) //10 main.myInt var b myFloat = 12.3ftt. Printf("%v %T", b, b) //12.3 float64}Copy the code

The result shows that the type of a is main.newInt, which represents the newInt type defined under the main package. B is of type int.

The structure definition is initialized

Definition of structure

Use the type and struct keywords to define structures in the following code format

Struct {struct {struct {struct {struct {struct {struct {struct {struct... }Copy the code
type person struct { 
  name string
  city string 
  age int8 
}
Copy the code

Struct instantiation

Memory is actually allocated only when the structure is instantiated. That is, the structure’s fields must be instantiated before they can be used

type Person struct {
	Name string
	Age  int
	Sex  string
}
Copy the code

The first kind of

Var p1 Person // instantiate the Person structure p1.name = "p3. sex =" male "p1.age = 20 ftt. Printf(" value :%v type :%T\n", p1, (p1) / / value: 20 male} {zhang SAN type: main. The Person FMT) Printf (" value: # % v type: % T ", p1, p1) / / value:. The main Person {name: "zhang", the age: 20, Person var p2 = new(Person) p2.name = "" p2.age = 20 p2.sex =" "(*p2).Name =" "FMT.Printf(" value :%#v Type: % T \ n ", p2, p2) / / value: & main. The Person {Name: "bill", the Age: 20, Person var p3 = &person {} p3.Name = "Person" p3.Age = 23 p3.Sex = "man" FMT.Printf(" value :%#v type :%T\n", p3, Person var p4 = Person{Name:" ha ", Age: 20, Sex:" male "} type :*main.Person var p4 = Person{Name:" ha ", Age: 20, Sex:" male "} "Male",} FMT. Printf (" value: # % v type: % T \ n ", p4, p4) / / value: main. Person {Name: "ha ha", the Age: 20, Person var p5 = &person {Name: "", Age: 20, Sex: "Male",} FMT. Printf (" value: # % v type: % T \ n ", p5, p5) / / value: & main. Person {Name: "just soso," Age: 20, } type :*main.Person var p6 = &person {Name: "Just soso,"} FMT. Printf (" value: # % v type: % T \ n ", p6, p6) / / value: & main. Person {Name: "just soso," Age: 0, Sex: ""} type: * the main Person var p7 = & Person {" zhang", 20, "male",} FMT) Printf (" value: # % v type: % T \ n ", p7, P7) / / value: & main Person {Name: "zhang", the Age: 20, Sex: "male"} type: * the main PersonCopy the code

Value types

Type Person struct {Name string Age int Sex string} func main() {var p1 = Person{Name: "ha ha ", Age: 20, Sex: "Male",} p2: = p1 p2. The Name = "bill" FMT. Printf (" % # v \ n ", p1). / / the main Person {Name: "ha ha", the Age: 20, Sex: "male"} FMT) Printf (" % # v ", P2) //main.Person{Name:" li si ", Age:20, Sex:" male "}Copy the code

Structure method

The receiver of the value type

When a method is applied to a value type receiver, the Go language makes a copy of the receiver’s value at runtime. The recipient’s member values can be obtained in the method of the value type receiver, but the modification operation is only for the copy and the recipient variable itself cannot be modified.

Type Person struct {Name string Age int Sex string height int} func (p Person) PrintInfo() {fmt.printf (" %v Age: %v\n", p.name, p.age)} func main() {var p1 = Person{Name: "", Age: 20, Sex: } p1.PrintInfo() var p2 = Person{Name: "", Age: 30, Sex: "Male ",} p2.printinfo () // Name: Li Si age :30 p1.printinfo () // name: Zhang SAN age :20Copy the code

Pointer type receiver

The receiver of a pointer type consists of a pointer to a structure. Due to the nature of Pointers, any member variable of the receiver pointer that is modified when a method is called is valid after the method ends. This approach is very similar to this or self in other object-oriented languages.

type Person struct { Name string Age int Sex string height int } // PrintInfo aa func (p Person) PrintInfo() { FMT. Printf (" name: %v age :%v\n", p.name, p.age)} // SetInfo aa func (p *Person) Age int) {p.name = name p.age = age} func main() {var p1 = Person{name: "", age: 20, Sex: P1.setinfo () p1.setinfo () p1.setinfo () p1.setinfo () p1.setinfo ()Copy the code

Recipients of instantiated pointer types that do not affect each other

Type Person struct {Name string Age int Sex string height int} func (p Person) PrintInfo() {fmt.printf (" %v age :%v\n", p.name, p.age)} func (p *Person) SetInfo(name string, Age int) {p.name = name p.age = age} func main() {var p1 = Person{name: "", age: 20, Sex: } p1.printinfo () var p2 = Person{Name: "", Age: 22, Sex: PrintInfo() // name: PrintInfo() // name: PrintInfo() // name: PrintInfo()Copy the code

Add methods to any type

In the Go language, the receiver can be of any type, not just a structure, but any type can have methods.

We use the type keyword to define new custom types based on the built-in int type, and then add methods to our custom types

Type MyInt int func (m MyInt) PrintInfo() {fmt.println (" I am a custom method inside a custom type ")} func main() {var a MyInt = 20 a.PrintInfo() }Copy the code

The anonymous field of a structure

A structure allows its member fields to be declared without a field name but only with a type. Such nameless fields are called anonymous fields

By default, an anonymous field uses the type name as the field name. The structure requires that the field name be unique. Therefore, only one anonymous field of the same type can be created in a structure

Type Person struct {string int} func main() {FMT.Println(p)}Copy the code

The field type of the structure

The structure’s field types can be: basic data type, slice, Map, or structure

If the structure’s field type is pointer, slice, and map nil, then no space has been allocated

If you want to use such a field, you need to make it.

type Person struct { Name string Age int Hobby []string map1 map[string]string } func main() { var p Person p.Name = P.age = 20 p.hoby = make([]string, 3, 6) p.hoby [0] = "write code" p.hoby [1] = "play basketball" p.hoby [2] = "sleep" p.p.ap1 = make(map[string]string) p.p.ap1 ["address"] = "Beijing" P. ap1 (" phone ") = "1324325325" FMT) Printf (" % # v \ n ", p) / / the main Person {Name: "zhang", the Age: 20, Hobby: [] string {" code ", "basketball", "Sleep"}, FMT. Printf (" % v ", p.H obby) / / map1: map [string] string {" address ":" Beijing ", "phone" : "1324325325"}}} [write code to play basketball sleep]Copy the code

Structure nesting

basic

Type User struct {Username string Password string Address Address} type Address struct {Name string Phone string City string } func main() { var u User u.Username = "itying" u.Password = "1234567" u.Address.Name = City = "Beijing" FMT.Printf("%#v", u) //main.User{Username:"itying", Password:"1234567", Address:main.Address{Name:" zhang SAN ", Phone:"15201671234", City:" Beijing "}}Copy the code

Nested anonymous structures

type User struct { Username string Password string Address } type Address struct { Name string Phone string City string } func main() {var User u.user Name = "itying" u.password = "1234567" u.dress. Name = "" u.dress.phone =" "15201671234" u.dress. City = "Beijing" U.city = "Shanghai" Printf("%#v\n", u) //main.User{Username:"itying", Password:"1234567", Address:main.Address{Name:" zhang3 ", Phone:"15201671234", City:" "}} ftt. Println(u.adddress.phone) //15201671234 FTt. Println(u.hone) //15201671234}Copy the code

Nested anonymous structures

When accessing a structure member, the field will be searched in the structure first, and if it cannot be found, it will be searched in the anonymous structure.

type User struct { Username string Password string AddTime string Address } type Address struct { Name string Phone string City string AddTime string } func main() { var u User u.Username = "itying" u.Password = "1234567" u.Address.Name City = "Beijing" u.city = "Shanghai" // When accessing a struct member, the field will be searched in the struct first. If not, the field will be searched in the anonymous struct. u.AddTime = "2020-05-1" u.Address.AddTime = "2020-06-1" fmt.Printf("%#v\n", u) //main.User{Username:"itying", Password:"1234567", AddTime:"2020-05-1", Address:main.Address{Name:" zhang SAN ", Phone:"15201671234", City:" Shanghai ", AddTime:"2020-06-1"}} }Copy the code

Field name conflicts about nested structures

Username string Password string Address Email } type Address struct { Name string Phone string City string AddTime string } type Email struct { Account string AddTime string } func main() { var u User u.Username = "itying" u.Password = "1234567" u.dress. Name = "zhang SAN" U.dress. Phone = "15201671234" U.dress. City = "Beijing" U.city = "Shanghai" // When accessing a struct member, the field will be searched in the struct first. If it cannot be found, the field will be searched in the anonymous struct. u.Address.AddTime = "2020-05-1" u.Email.AddTime = "2020-06-1" fmt.Printf("%#v\n", u) }Copy the code

inheritance

basic

Type Animal struct {Name string} func (a Animal) run() {FMT.Printf("%v in sport \n", Func (d Dog) wang() {FMT.Printf("%v \n", D.name)} func main() {var d = Dog{Age: 20, Animal: Animal{Name: "archie ",},}Copy the code

Pointer to the

Type Animal struct {Name string} func (a Animal) run() {FMT.Printf("%v in sport \n", Func (d Dog) wang() {FMT.Printf("%v in wongwongn ", D.name)} func main() {var d = Dog{Age: 20, Animal: &animal {Name: "aich ",},} d.run() // aich is in sport d.wang() // Aich is in want}Copy the code

Structure and JSON

basic

Type Student struct {ID int Gender string Name string Sno string} func main() {var s1 = Student{ID: Gender: "Male ", Name:" Li Si ", Sno: "S0001} FMT. Printf (" % # v \ n", s1). / / the main Student {ID: 12, Gender: "male", the Name: "bill," Sno: "s0001} jsonByte, _ := json.Marshal(s1) fmt.Printf("%v", jsonByte) jsonStr := string(jsonByte) fmt.Printf("%v", JsonStr) / / {" ID ": 12," Gender ":" male ", "Name" : "bill", "Sno" : "s0001"}}Copy the code

Type Student struct {ID int Gender string Name string Sno string} func main() {//json string var STR = ` {" ID ": 12," Gender ":" male ", "Name" : "bill", "Sno" : "s0001} ` var s1 Student err: = json. The Unmarshal (byte [] (STR), & s1) if err! = nil { fmt.Println(err) } fmt.Printf("%#v\n", s1) fmt.Println(s1.Name) }Copy the code

Structural label

Type Student struct {Id int 'json:" Id "' Gender string 'json:" Gender "' Name string 'json:" Name "' // Private property cannot be accessed by json package Sno String 'json:"sno"'} func main() {var s1 = Student{Id: 12, Gender: "male ", Name: "sno", sno: "S0001} FMT. Printf (" % # v \ n", s1). / / the main Student {Id: 12, Gender: "male", the Name: "bill," Sno: "s0001} jsonByte, _ := json.Marshal(s1) jsonStr := string(jsonByte) fmt.Printf("%v", JsonStr) / / {" id ": 12," gender ":" male ", "name" : "bill", "sno" : "s0001"}}Copy the code
Type Student struct {Id int Gender string Name string} Class Class type Class struct {Title string Students []Student} Func main() {c := Class{Title: "001 ", Students: make([]Student, 0),} for I := 1; i <= 10; I ++ {s := Student{Id: I, Gender: "male ", Name: fmt.Sprintf("stu_%v", i), } c.Students = append(c.Students, s) } // fmt.Println(c) strByte, err := json.Marshal(c) if err ! = nil { fmt.Println(err) } else { strJson := string(strByte) fmt.Println(strJson) } }Copy the code
Type Student struct {ID int Gender string Name string} //Class Class type Class struct {Title string Students []Student } func main() { str := ` {" Title ":" 001 ", "Students" : [{" Id ": 1," Gender ":" male ", "Name" : "stu_1"}, {" Id ": 2," Gender ":" male ", "Name" : "stu_2"}, {" Id ": 3," Gender ": "Male", "Name" : "stu_3"}, {" Id ": 4," Gender ":" male ", "Name" : "stu_4"}, {" Id ": 5," Gender ":" male ", "Name" : "stu_5"}, {" Id ": 6," Gender ":" male ", "the Name ":" stu_6 "}, {" Id ": 7," Gender ":" male ", "Name" : "stu_7"}, {" Id ": 8," Gender ":" male ", "Name" : "stu_8"}, {" Id ": 9," Gender ":" male ", "Name" : "stu_9" }, {" Id ": 10," Gender ":" male ", "Name" : "stu_10}]} ` var c = & Class {} err: = json. The Unmarshal (byte [] (STR), c) if err! = nil { fmt.Println(err) } else { fmt.Printf("%#v\n", c) fmt.Printf("%v", c.Title) } }Copy the code

interface

Interface in Golang

Golang interface is an abstract data type. Golang interface defines the behavior of an object. Specifications defined in interfaces are implemented by concrete objects

Type Interface name interface{Method name 1(parameter list 1) Return value list 1 Method name 2(Parameter list 2) Return value list 2... }Copy the code

Define a Usber interface that the Phone and Camera constructs implement

Type Usber interface {start() stop()} type Phone struct {Name string} func (p Phone) start() { Func (p Phone) stop() {fmt.println (p.name, "start ")} func (p Phone) stop() {fmt.println (p.name," start ")} } type Camera struct {} func (p Camera) start() {fmt.println (" Camera ")} func (p Camera) stop() { FMT.Println(" Camera shutdown ")} func (p Camera) run() {FMT.Println("run")} func main() {p := Phone{Name: "Huawei Mobile ", } var c1 Usber p1 = p p1.stop() c := Camera{} var c1 Usber = c // c1.start() //run }Copy the code

The Work method in the Computer structure must be passed into a Usb interface

Type Usber interface {start() stop()} type Computer struct {} func (c Computer) work(usb Usber) { usb.start() usb.stop() } type Phone struct { Name string } func (p Phone) start() { Func (p Phone) stop() {fmt.println (p.name, "start ")} func (p Phone) stop() {fmt.println (p.name," start ")} } type Camera struct {} func (p Camera) start() {fmt.println (" Camera ")} func (p Camera) stop() { Println(" Camera shutdown ")} func (p Camera) run() {fmt.println ("run")} func main() {var computer = computer {} var phone = Phone{Name: "mI ",} var camera = camera {} computer. Work (Phone) // camera.Copy the code

Empty interface

An interface in Golang may not define any methods, and an interface that does not define any methods is an empty interface. An empty interface means that there are no constraints, so any type variable can implement an empty interface.

Empty interfaces are used a lot in real projects and can represent any data type.

Func main() {var A A var STR = "hello golang" A = STR // let the string implement A interface FMT.Printf(" value :%v type :%T\n", a, Var num = 20 a = num FMT.Printf(" value :%v :%T\n", a, Printf(" value :%v type :%T", a, a)}Copy the code

An empty interface is taken as an argument to the function

An empty interface implementation can accept function arguments of any type.

Func show(a interface{}) {fmt.Printf(" value :%v type :%T\n", a, A)} func main() {show(20) {20 type :int show(" golang") // value :string slice := []int{1, 2, 34, 4} show(slice) // Value :[1 2 34 4] Type :[]int}Copy the code

The value of map implements the null interface

Var m1 = make(map[string]interface{}) m1["age"] = 20 m1["married"] = true FMT.Println(m1) //map[age:20 married:true username: zhang 3]Copy the code

Slicing implements an empty interface

Var s1 = []interface{}{1, 2, "hello ", true} FMT.Println(s1)Copy the code

Types of assertions

An interface value consists of a specific type and a specific type of value. These are called dynamic types and dynamic values of interfaces.

If we want to determine the type of a value in an empty interface, we can use type assertions with the syntax x.(T).

  1. X: indicates a variable of type interface{} •
  2. T: indicates the type of assertion x may be

This syntax returns two arguments. The first argument is the variable after x is converted to type T. The second value is a Boolean value that indicates that the assertion succeeded if it is true and failed if it is false.

Var a interface{} a = "golang" v, ok := a.(string) if ok {FMT.Println("a is a string, and the value is: ", v)} else {fmt.println (" assertion failed ")} //a is a string with the value: hello golangCopy the code
func MyPrint1(x interface{}) { if _, ok := x.(string); Println("string ")} else if _, ok := x.(int); Println("int type ")} else if _, ok := x.(bool); Ok {FMT.Println("bool type ")}} func MyPrint2(x interface{}) {switch x. Fmt. Println("int type ") Case String: FMt. Println("string type ") Case bool: FMt. Println("bool type ") default: FMT.Println(" incoming error..." }} MyPrint1(" hello golang") //string MyPrint1(true) //bool MyPrint2(" hello golang") //string MyPrint2(true) //boolCopy the code

Structure value receiver and pointer receiver implement interface differences

Value receiver:

If a method in a structure is a value receiver, then both the instantiated structure value type and the structure pointer type can be assigned to the interface variable

Type Usber interface {start() stop()} // Computer type Computer struct {} func (c Computer) work(USB Usber)  _, ok := usb.(Phone); Ok {// type predicate usb.start()} else {usb.stop()}} // Phone type Phone struct {Name string} func (p Phone) start() { Func (p Phone) stop() {fmt.println (p.name, "start ")} func (p Phone) stop() {fmt.println (p.name," start ")} // Camera type Camera struct {} func (p Camera) start() {fmt.println (" Camera start ")} func (p Camera stop() { Println(" camera shutdown ")} func main() {var computer = computer {} var phone = phone {Name: Work (camera) {work(camera) {work(camera) {work(camera)}Copy the code

Pointer receiver

If a method in a structure is a pointer receiver, the instantiated structure pointer type can be assigned to the interface variable, but the structure value type cannot be assigned to the interface variable

Type Usber interface {start() stop()} type Phone struct {Name string} func (p *Phone) start() Func (p *Phone) stop() {fmt.println (p.name, "start ")} func (p *Phone) stop() {fmt.println (p.name," start ")} } func main() {var phone1 = Phone{Name: "Millet", } var p1 Usber = phone1 // Phone does not implement Usber (start method has pointer receiver p1.start() */ var phone1 = &phone {Name: "Phone ",} var p1 Usber = phone1 p1.start()}Copy the code

Define an Animal interface. Multiple constructs implement this method

Define an interface of Animal, the Animal is defined in two methods, respectively is elegantly-named SetName and GetName. Let the Dog and Cat structures implement this method, respectively

package main import "fmt" type Animaler interface { SetName(string) GetName() string } type Dog struct { Name string } func (d *Dog) SetName(name string) { d.Name = name } func (d Dog) GetName() string { return d.Name } type Cat struct { Name string } func (c *Cat) SetName(name string) { c.Name = name } func (c Cat) GetName() string { return c.Name } func D := &dog {Name: "Black", } var d1 Animaler = DMT.Println(d1.getName ()) d1.setname (" Archie ") fdt.println (d1.getName ()) Println(c1.getName ())} var c1 Animaler = c fmt.println (c1.getName ())}Copy the code

A structure implements multiple interfaces

type Animaler1 interface { SetName(string) } type Animaler2 interface { GetName() string } type Dog struct { Name string  } func (d *Dog) SetName(name string) { d.Name = name } func (d Dog) GetName() string { return d.Name } func main() { D := &dog {Name: "Black", } var d2 Animaler1 = d // Animaler2 = d // d1.setName (" puppy ") FMT.Println(d2.getName ())}Copy the code

Nested interface

type Ainterface interface { SetName(string) } type Binterface interface { GetName() string } type Animaler interface { Struct {Name string} func (d *Dog) SetName(Name string) {d.name = Name} Func (d Dog) GetName() string {return d.name} func main() {d := &dog {Name: D1.setname (d1.getname ()) // d1.getname ()) //Copy the code

reflection

The trigger for reflection

  1. An empty interface can store variables of any type, so how do we know what type of data this empty interface holds? What are the values?

Type assertions can be used

This can be implemented using reflection, which dynamically retrieves the type and value information of a variable while the program is running.

  1. Reflection is used when serializing a structure as a JSON string and customizing the structure Tag

  2. Later we will talk about ORM framework, which uses reflection technology

reflect.TypeOf()

Reflect.typeof () Gets an arbitrary value for a type object

The reflect.typeof () function can take any interface{} argument and get a class object with any value. The program can access the Type information of any value through the Type object.

type myInt int type Person struct { Name string Age int } func reflectFn(x interface{}) { v := reflect.TypeOf(x) // Printf(" type :%v type name :%v type type :%v \n", v, v.name (), V.coin ())} func main() {a := 10 //int b := 23.4 //float64 C := true //bool d := "Hi golang" // String reflectFn(a) ReflectFn (b) reflectFn(C) reflectFn(D) var e myInt = 34 var f = Person{Name: "Three ", Age: MyInt reflectFn(f) //main.Person var h = 25 reflectFn(&h) //*int Type name: Type Type: PTR var I = [3]int{1, 2, 3} reflectFn(I) //[3]int Type name: Type type :array var j = []int{11, 22, 33} reflectFn(j) //[]int Type name: Type type :slice}Copy the code

reflect.ValueOf()

Reflection gets the variable’s original value of 1

func reflectValue(x interface{}) { // var num = 10 + x //(mismatched types int and interface {} // b, (int) // var num = 10 + b // fmt.println (num) // v := reflect.valueof (x) // fmt.println (v) //13 // var n = v + 1 // FMT.Println(n) //mismatched types reflect.Value and int //mismatched types (n) v := reflect.valueof (x) var m = v.Int() + 12 fmt.Println(m) //25 } func main() { var a = 13 reflectValue(a) }Copy the code

Getting raw values by reflection Demonstration 2

Func reflectValue(x interface{}) {v := reflect.valueof (x) // v.kinde () // Get kind := v.kinde () switch kind {case Reflect.int64: FMT.Printf("int %v \n", v.I. Nt (), v.I. Nt ()+10) case Reflect.int64: FMT.Printf("int %v \n", v.I. Nt ()+10) Printf("Float32 = %v\n", v.float ()) case reflect.float64: Printf("Float64 float %v\n", v.float ()) case reflect.String: float.Printf(" String float %v\n", v.float ()) default: Printf(" "\n")}} func main() {var a int64 = 100 var b float32 = 12.3 var c string = ReflectValue (a) // The original value of int type is 100. The calculated value is 110 reflectValue(b) // Original value of Float32 12.300000190734863 reflectValue(c) // A primitive value of type string hello golang}Copy the code

3

func reflectSetValue(x interface{}) { // *x = 120 //invalid indirect of x (type interface {}) // v, _ := x.(*int) // *v = 120 // invalid memory address or nil pointer dereferenc v := reflect.ValueOf(x) // fmt.Println(v.Kind()) //ptr // fmt.Println(v.Elem().Kind()) //int64 if v.Elem().Kind() == reflect.Int64 { V.lem ().setint (123)} else if v.lem ().kind () == reflect.string {v.lem ().setString (" Hello go language ")}} func main() {var a Int64 = 100 reflectSetValue(& A) fmt.println (a) var b string = "Golang" reflectSetValue(&b) //123 FMt.println (b) // Hello The go language}Copy the code

Structural reflection

Gets structure properties, gets the execute structure method

type Student struct { Name string `json:"name1" form:"username"` Age int `json:"age"` Score int `json:"score"` } func (s Student) GetInfo() string {var STR = FMT.Sprintf(" name :%v age :%v grade :%v", s.name, s.age, s.Score) return str } func (s *Student) SetInfo(name string, age int, Score int) {s.name = name s.age = age s.core = score} func (s Student) Print() {fmt.println (" Func PrintStructField(s interface{}) {t := reflect.typeof (s) v := reflect.valueof (s) if t.Kind() ! = reflect.Struct && t.Elem().Kind() ! Struct {field0 := t.field (0) field0 := t.field (0) field0 := t.field (0) fmt.Printf("%#v \n", field0) //reflect.StructField{Name:"Name", PkgPath:"", Type:(*reflect.rtype)(0x4adf20), Tag:"json:\"name\", Offset:0x0, Index:[]int{0}, Anonymous:false} fmt.Println(" fieldname :", field0.Name) fmt.Println(" fieldname :", field0.Name) fmt.Println(" fieldname :", field0. ", field0.type) fmt.Println(" field0.tag.get ("json")) fmt.Println(" field0: Tag ") ", field0. Tag. The Get (" form ")) / / 2, through the inside of the type variable FieldByName fields of structure can be gained FMT. Println (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ") field1, Ok := t.fieldbyName ("Age") if ok {FMT.Println(" field1.name ") FMT.Println(" field1.name ") FMT. ", field1.type) FMT.Println(" field Tag: Var fieldCount = t.numfield () ftm.println (" fieldCount ", fieldCount = t.numfield ()) fieldCount, Println(v.fieldbyname ("Name")) (v.fieldbyname ("Age")) fmt.Println("----------------------") for i := 0; i < fieldCount; I++ {FMT. Printf (" the attribute Name, % v attribute values: % v attribute types: % v attribute Tag: % v \ n ", t.F ield (I). The Name, v. ield (I), t.F ield (I). The Type, Func PrintStructFn(s interface{}) {t := reflect.typeof (s) v := reflect.ValueOf(s) if t.Kind() ! = reflect.Struct && t.Elem().Kind() ! Struct {Struct.Println(" Method is not a Struct ") return} // // It has nothing to do with the order of the struct methods, Println(method0.name) //GetInfo fmt.println (method0.type) //func(main.student) string FMT. Println (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - ") / / 2, through the type variables there are many methods to get this structure method1, ok := t.MethodByName("Print") if ok { fmt.Println(method1.Name) //Print fmt.Println(method1.Type) //func(main.Student) } FMT. Println (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - ") / / 3, through the "parameters" execution method (note that you need to use the values of variables, Call(nil) or v.thodbyname ("Print").call (nil) // v.thod (1).call (nil) V.thodbyname ("Print").call (nil) info1 := v.thodbyName ("GetInfo").call (nil) fmt.println (info1) //4 (Note the use of Value Variables, Var params []reflect.Value params = append(params, ValueOf(" 四")) params = append(params, reflect.valueof (23)) params = append(params, Reflect.valueof (99) v.mode byName ("SetInfo").call (params) // The execution method passes info2 := v.mode byName ("GetInfo").call (nil) Println(" stu1 :", t.nummethod ())} func main() {stu1 := Student{Name: "stu2 ", Age: = Student{Name:" info2 ", Age: = Student{Name: "info2 ", Age: = Student{Name:" info2 ", Age: = Student{Name: "info2 ", Age: 15, Score: 98, } // PrintStructField(stu1) PrintStructFn(&stu1) fmt.Printf("%#v\n", stu1) }Copy the code

Modify the structure method

type Student struct { Name string `json:"name"` Age int `json:"age"` Score int `json:"score"` } func (s Student) GetInfo() string {var STR = fmt.sprintf (" name :%v age :%v grade :%v", s.name, s.age, S. core) return STR} // // reflectChangeStruct(s interface{}) {t := reflectChangeStruct(s interface{}) {t := reflect.TypeOf(s) v := reflect.ValueOf(s) if t.Kind() ! = reflect.ptr {fmt.println (" not the structure pointer type ") return} else if t.lem ().kind ()! Struct {fmt.println (" no Struct pointer type ") return} name := v.lem ().fieldByName (" name ") FieldByName(" age ") age.setint (22)} func main() {stu1 := Student{name := Student{name: "Xiao Ming ", Age: 15, Score: } // PrintStructField(stu1) reflectChangeStruct(&stu1) FMT.Printf("%#v\n", stu1) //main.Student{Name:" lI ", Age:22, Score:98} }Copy the code