Structure of GO Foundation


1. What is a structure
In GO language, arrays can store data of the same type, but in structure we can define different data types for different items. A structure is a data set composed of a series of data of the same type or different types.

2. What is instantiation?

  • The definition of Go structure is only a description of memory layout. Only when the structure is instantiated, can the memory be really allocated. Therefore, you must define the structure and instantiate it before you can use the structure instantiation, which is to create a memory area consistent with the format according to the format defined by the structure.
  • The memory between structure instances is completely independent.
package main

import "fmt"

func main() {
    //Instantiation method 1
    var stu1 Student
    fmt.Printf("stu1=%T,%v,%q \n", stu1, stu1, stu1)
    stu1.name = "zs"
    stu1.age = 12
    stu1.sex = 1
    fmt.Printf("stu1=%T,%v,%q \n", stu1, stu1, stu1)
    //Instantiation method 2
    stu2 := Student{}
    stu2.name = "David"
    stu2.age = 33
    stu2.sex = 1
    fmt.Printf("stu2=%T,%v,%q \n", stu2, stu2, stu2)
    //Instantiation mode 3
    stu3 := Student{
        name: "Josh",
        age:  28,
        sex:  1,
    }
    fmt.Printf("stu3=%T,%v,%q \n", stu3, stu3, stu3)
    //Instantiation four
    stu4 := Student{"Ruby", 30, 0}
    fmt.Printf("stu3=%T,%v,%q \n", stu4, stu4, stu4)
    //Instantiation five
    //Use built-in functions new()Instantiate a structure,A pointer type structure is formed after the structure is instantiated
    //·new Built in functions allocate memory. The first parameter is the type,Not the value.,The value returned is a pointer to the newly assigned zero value of the type. This function is used to create a pointer of a type.
    stu5 := new(Student)
    (*stu5).name = "Running"
    (*stu5).age = 31
    stu5.sex = 0                                     //The way of grammar sugar
    fmt.Printf("stu3=%T,%v,%q \n", stu5, stu5, stu5) //stu3=*main.Student,&{Running 31 0},&{"Running" '\x1f' '\x00'}

}

//Definition of structure
type Student struct {
    name string
    age  int
    sex  int8
}

The concept of grammatical sugar

  • Grammar sugar, also translated as icing grammar, is a term invented by Peter J. landin, a British computer scientist. It refers to a kind of grammar added to a computer language, which has no effect on the function of the language, but is more convenient for programmers to use.
  • Generally speaking, the use of syntax sugar can increase the readability of the program, thus reducing the chance of program code errors
  • Both the structure and the array contain syntactic sugar.
package main

import "fmt"

func main() {
    arr := [4]int{1, 2, 3, 4}
    arr2 := &arr
    fmt.Println((*arr2)[3])
    //Syntax sugar in array
    fmt.Println(arr2[3])
    
    //Section
    arr3 := []int{10, 20, 30, 40}
    arr4 := &arr3
    fmt.Println((*arr4)[3])
    //No grammar sugar in the slice
    //fmt.Println(arr4[3])
}

 

3. Structure is value type transfer

2. Deep copy and shallow copy

struct is a deep copy by default

package main

import "fmt"

func main() {
    stu1 := Student{"zs", 18, 0}
    fmt.Printf("stu1:=%T,%p,%v \n", stu1, &stu1, stu1)
    //stu1:=main.Student,0xc0000044a0,{zs 18 0}
    stu2 := stu1
    stu2.name = "ls"
    fmt.Printf("stu2:=%T,%p,%v \n", stu2, &stu2, stu2)
    //stu2:=main.Student,0xc000004520,{ls 18 0}
    
    fmt.Printf("stu1:=%T,%p,%v \n", stu1, &stu1, stu1)
    //stu1:=main.Student,0xc0000044a0,{zs 18 0}
    //modify stu2 Yes stu1 No impact

}

 

Enable shallow copy

1. Direct assignment pointer address

package main

import "fmt"

func main() {
    stu1 := Student{"zs", 18, 0}
    fmt.Printf("stu1:=%T,%p,%v \n", stu1, &stu1, stu1)
    //stu1:=main.Student,0xc00005a440,{zs 18 0}
    stu2 := &stu1
    stu2.name = "ls"
    fmt.Printf("stu2:=%T,%p,%v \n", stu2, stu2, stu2)
    //stu2:=*main.Student,0xc00005a440,&{ls 18 0}

    fmt.Printf("stu1:=%T,%p,%v \n", stu1, &stu1, stu1)
    //stu1:=main.Student,0xc00005a440,{ls 18 0}
    //modify stu2 Yes stu1 Influential
}

2. Implement shallow copy of structure: instantiate the object through the new() function

package main

import "fmt"

func main() {
    //3,Implementation of shallow copy of structure: through new()Function to instantiate an object
    d4 := new(Dog)
    d4.name = "Much"
    d4.color = "brown"
    d4.age = 1
    d4.kind = "Pug"
    d5 := d4
    fmt.Printf("d4: %T , %v , %p \n", d4, d4, d4)
    //d4: *main.Dog , &{Brown 1 Pug} , 0xc000040080
    fmt.Printf("d5: %T , %v , %p \n", d5, d5, d5)

    fmt.Println("--------------------------------------")

    d5.color = "Golden"
    d5.kind = "Golden hair"
    fmt.Println("d5 After amendment:", d5)
    //d5 After amendment: &{Duoduo gold 1 golden hair}
    fmt.Println("d4: ", d4)
    //d4:  &{Duoduo gold 1 golden hair}
}

type Dog struct {
    name  string
    color string
    age   int8
    kind  string
}

struct as function parameter

Structure object or pointer as parameter and return value of function

  • The difference between structure object as function parameter and structure pointer as function parameter
  • The difference between structure object as function return value and structure pointer as function return value

 

 

IV. anonymous structure and anonymous field

Anonymous structure

  • • a structure without a name. You don't need to define the type keyword to use it directly.
  • • when you create anonymous structures, you also create objects.
  • • anonymous structure consists of structure definition and key value pair initialization
    //Anonymous structure
    addr := struct {
        province, city string
    }{"Shaanxi Province", "Xi'an City"}
    fmt.Println(addr)

Anonymous field of structure
A field in a structure has no name and only contains a type without a field name. These fields are called anonymous fields.

  • • if the field does not have a name, the type is used as the field name by default.
  • • note: only one type can be written.
  • Using anonymous structure field in structure nesting can simulate inheritance relationship.
package main

import "fmt"

type User struct {
    string
    byte
    int8
    float64
}

func main() {
    //    Instanced structure
    user:= User{"Steven" , 'm' , 35 , 177.5}
    fmt.Println(user)
    //If you want to output name, age, height and gender in sequence
    fmt.Printf("Full name:%s \n" , user.string)
    fmt.Printf("Height:%.2f \n" , user.float64)
    fmt.Printf("Gender:%c \n" , user.byte)
    fmt.Printf("Age:%d \n" , user.int8)
}

5. Polymerization of structure

• take one structure as the attribute (field) of another structure, which is the nesting of structures.
• nesting of structures can simulate two kinds of relationships in object-oriented

  • Aggregation relationship: one class as the property of another
  • Inheritance relationship: one class is a subclass of another. Children and parents.
package main

import "fmt"

type Address struct {
    province, city string
}

type Person struct {
    name    string
    age     int
    address *Address
}

func main() {
    //Aggregate relationship between simulation structure objects
    p := Person{}
    p.name = "Steven"
    p.age = 35

    //Assignment method 1:
    addr := Address{}
    addr.province = "Beijing City"
    addr.city = "Haidian District"
    p.address = &addr

    fmt.Println(p)
    fmt.Println("Full name:", p.name)
    fmt.Println("Age:", p.age)
    fmt.Println("Province:", p.address.province)
    fmt.Println("City:", p.address.city)
    fmt.Println("-----------------------")

    //modify Person Whether the data of the object will affect Address Object data?
    p.address.city = "Changping District"
    fmt.Println("Full name:", p.name)
    fmt.Println("Age:", p.age)
    fmt.Println("Province:", p.address.province)
    fmt.Println("City:", p.address.city)
    fmt.Println("addr City:", addr.city) //?Will it be affected?
    fmt.Println("-----------------------")

    //modify Address Whether the data of the object will affect Person Object data?
    addr.city = "Daxing District"
    fmt.Println("Full name:", p.name)
    fmt.Println("Age:", p.age)
    fmt.Println("Province:", p.address.province)
    fmt.Println("City:", p.address.city)
    fmt.Println("addr City:", addr.city) //?Will it be affected?
    fmt.Println("-----------------------")

    //Assignment method 2
    p.address = &Address{
        province: "Shaanxi Province",
        city:     "Xi'an City",
    }
    fmt.Println(p)
    fmt.Println("Full name:", p.name)
    fmt.Println("Age:", p.age)
    fmt.Println("Province:", p.address.province)
    fmt.Println("City:", p.address.city)
    fmt.Println("-----------------------")
}

Vi. structure nesting simulation inheritance relationship

Inheritance is one of the three characteristics of traditional object-oriented programming. Used to describe the relationship between two classes. One class (child class, derived class) inherits from another class (parent class, superclass).
• a subclass can have its own properties and methods, or it can override the existing methods of the parent class.
• subclass can directly access all properties and methods of the parent class.
• promotion field:
Fields belonging to anonymous structures in structures are called promoted fields, because they can be accessed as if they belong to structures with anonymous structure fields.
In other words, the fields in the parent class are promoted fields.
• the meaning of inheritance: avoid duplicate code and extend the function of class
The form of anonymous field is to simulate the inheritance relationship. When simulating aggregation relations, we must use the named structure as the field

package main

import (
    "fmt"
)

type Person struct {
    name string
    age  int
    sex  string
}

type Student struct {
    Person
    schoolName string
}

func main() {
    //1,Instantiate and initialize Person
    p1 := Person{"Steven", 35, "male"}
    fmt.Println(p1)
    fmt.Println("-------------------")

    //2,Instantiate and initialize Student
    //    Writing 1:
    s1 := Student{p1, "Beihang Software Institute"}
    printInfo(s1)

    //Writing 2:
    s2 := Student{Person{"Josh", 30, "male"}, "Beiwaigaofancollege"}
    printInfo(s2)

    //Writing 3:
    s3 := Student{Person: Person{
        name: "Penn",
        age:  19,
        sex:  "male",
    },
        schoolName: "Yuanpei College of Peking University",
    }
    printInfo(s3)

    //    Writing 4:
    s4 := Student{}
    s4.name = "Daniel"
    s4.sex = "male"
    s4.age = 12
    s4.schoolName = "Beijing shilongyue"
    printInfo(s4)

}

func printInfo(s1 Student) {
    fmt.Println(s1)
    fmt.Printf("%+v \n", s1)
    fmt.Printf("Full name:%s, Age:%d , Gender:%s ,School:%s \n", s1.name, s1.age, s1.sex, s1.schoolName)
    fmt.Println("-------------------")
}

 

VII. Method in structure

 

• Go language has function and method at the same time, the essence of method is function, but method and function have different points.
1. Different meanings
• function is a piece of code with independent functions, which can be called repeatedly, so as to realize code reuse. method is the behavior function of a class, which can only be called by its objects.
2. Method has acceptor, but function has no acceptor
• methods of the Go language - a function that acts on a specific type of variable. This particular type of variable is called a Receiver.
• the concept of receiver is similar to this or self keyword in traditional object-oriented language.
• recipients of the Go language emphasize that a method has a working object, while a function has no working object.
• a method is a function that contains the receiver.
• in the Go language, the type of the receiver can be any type, not only the structure, but also any type other than the struct type.
3. Function cannot be renamed, but method can be renamed
• method names can be the same as long as the recipients are different.

package main

import "fmt"
import "base"
type Employee struct {
    name , currency string
    salary float64
}
func main() {
    emp1 := Employee{"Daniel" , "$" , 2000}
    emp1.printSalary()//Employee name: Daniel ,Salary: $2000.00 
    emp1.updateSalary(1000)
    emp1.printSalary()//Employee name: Daniel ,Salary: $1000.00 
}

//printSalary Method
func (e Employee) printSalary() {
    fmt.Printf("Employee name:%s ,Salary:%s%.2f \n", e.name , e.currency , e.salary)
}
func (e *Employee) updateSalary(num float64)  {
    e.salary=num
}

Inheritance and rewriting of methods

package main

import "fmt"
import "base"

type Human struct {
    name, phone string
    age         int
}

type Student struct {
    Human
    school string
}

type Employee struct {
    Human
    company string
}

func main() {
    s1 := Student{Human{"Daniel", "15012345678", 13}, "Eleven Dragon"}
    e1 := Employee{Human{"Steven", "17812345678", 35}, "1000phone"}
    s1.printName()
    e1.printName()
    s1.SayHi()
    e1.SayHi()
}
//======================Method inheritance=============================
func (h *Human) printName() {
    fmt.Println("Hello everyone! I am%s ", h.name)
}

//=====================Method override=============================
func (h *Human) SayHi() {
    fmt.Printf("Hello everyone! I am%s , I%d Age, contact:%s \n", h.name, h.age, h.phone)
}

func (s *Student) SayHi() {
    fmt.Printf("Hello everyone! I am%s , I%d I am%s School, contact:%s \n", s.name, s.age, s.school, s.phone)
}

func (e *Employee) SayHi() {
    fmt.Printf("Hello everyone! I am%s , I%d I am%s Work, contact:%s \n", e.name, e.age, e.company, e.phone)
}

Tags: Go Ruby Attribute Programming

Posted on Wed, 06 Nov 2019 16:40:46 -0800 by TheVoice