Analysis of struct structure in go programming

Time:2021-6-13

Struct and C language is very similar to simulate the function of class, but not completely! No constructors, etc!
Statement of struct

Copy codeThe code is as follows:
package main

import “fmt”

type Person struct {
 Age  int
 Name string
}

func main() {
 // There are two ways to initialize
 a := Person{}
 a.Age = 2
 a.Name = “widuu”
 fmt.Println(a)
 b := Person{
  Age:  24,
  Name: “widuu”,
 }
 fmt.Println(b)
}

Go pointer operation
As follows, we need to change the value, first take the memory address, and then change its reference on the memory address

Copy codeThe code is as follows:
package main

import “fmt”

type Person struct {
 Age  int
 Name string
}

func main() {
 b := &Person{
  Age:  24,
  Name: “widuu”,
 }
 fmt.Println(b)
 G(b)
 fmt.Println(b)
}

func G(per *Person) {
 per.Age = 15
 fmt.Println(per)
}

anonymous structure
(1) The use of anonymous internal structure

Copy codeThe code is as follows:
 func main() {
  a := struct {
   name string
   Age  int
  }{
   name: “widuu”,
   Age:  19,
  }
  fmt.Println(a)
}

Copy codeThe code is as follows:
package main

import “fmt”

type Person struct {
 Age    int
 Name   string
 Member struct {
  phone, City string
 }
}

func main() {
 a := Person{Age: 16, Name: “widuu”}
 a.Member.phone = “13800000”
 a.Member.City = “widuuweb”
 fmt.Println(a)
}

(2) Anonymous class value does not need data name. When assigning value, the two structures must be the same

Copy codeThe code is as follows:
package main

import “fmt”

type Person struct {
 string
 int
}

func main() {
 a := Person{“joe”, 19}
 var b Person
 b = a
 fmt.Println(b)
}

embedded structure
(1) Embedded structure simulation other programs have a concept of inheritance, just a concept

Copy codeThe code is as follows:
package main

import “fmt”

type Person struct {
 Name string
 Age  int
}
type student struct {
 Person
 work string
}

func main() {
//When instantiating, if the embedded structure does not have the name of the data structure, the default is the type name P erson:Person
 a := student{Person: Person{Name: “widuu”, Age: 19}, work: “IT”}
 fmt.Println(a)
}

(2) . structure method

Copy codeThe code is as follows:
package main

import “fmt”

type A struct {
  Name string   // This is a common upper case. If it is a lower case name, it can be private in the package
}
type B struct {
 Name string
}

func main() {
 a := A{}
 b := B{}
 a.print()
 b.print()
}
//Use different types to get the same method name
func (a *A) print() {
 fmt.Println(“A”)
}

func (b *B) print() {
 fmt.Println(“B”)
}