Go language learning notes -- structure and object-oriented programming

Posted by oaf357 on Fri, 31 Dec 2021 19:50:54 +0100

A structure is a data set composed of a series of data of the same type or different types.

  • The type in the structure can be arbitrary
  • The storage space of the structure is continuous
  • Structure is used to express all or part of the attributes of a thing
  • You can use structs to implement object orientation

definition

type Type name struct {
	Field name 1 data type of field 1
	Field name 2 data type of field 2
	...
}

Defines the structure of a Person

type Person struct {
   name string
   sex  int8
   age  int8
}

The same data type can also write the same row

type person struct {
    name string
    sex,age  int8
}

Structure instantiation

Only when the structure is instantiated can the memory be allocated, that is, the fields of the structure can be used after instantiation.

var Structure instance structure type

Instantiate first and then assign value

var p1 Person
p1.name = "Zhang San"
p1.sex = 0
p1.age = 20

Instantiate and assign values at the same time

p2 := Person{
    name: "Li Si",
    sex:  1,
    age:  18,
}

Anonymous structure

var user struct{Name string; Age int}
user.Name = "test"
user.Age = 18

Object oriented constructor

  • The structure of Go language has no constructor and needs to be implemented by itself.
  • Because struct is a value type, if the structure is complex, the performance cost of value copy will be large, so the constructor returns the structure pointer type.

Define structure

type Person struct {
	name     string
	sex, age int8
}

Constructor

/**
 * @Description: Person Constructor for
 * @param name full name
 * @param sex Gender
 * @param age Age
 * @return *Person Structure pointer
 */
func newPerson(name string, sex, age int8) *Person {
	return &Person{
		name: name,
		sex:  sex,
		age:  age,
	}
}

Object oriented method

func (Receiver variable receiver type) Method name(parameter list) (Return parameters) {
	Function body
}
  • Receiver variable: when naming the parameter variable name in the receiver, it is officially recommended to use the first lowercase letter of the receiver type name instead of naming such as self and this. For example, the receiver variable of Person type should be named p, the receiver variable of Connector type should be named c, etc.
  • Receiver type: receiver type is similar to parameter, and can be pointer type and non pointer type.
  • Method name, parameter list and return parameter: the specific format is the same as the function definition.
Recipient of value type
// Define structure
type Person struct {
	name     string
	sex, age int8
}

// Binding method
func (p Person) Say() {
	fmt.Println(p.name + "Hello")
}

// call
p1 := Person{
    name: "Li Si",
    sex:  1,
    age:  18,
}
p1.Say()
Receiver of pointer type
func (p *Person) Say2() {
	fmt.Println(p.name + "Hello")
}

p1 := Person{
    name: "Li Si",
    sex:  1,
    age:  18,
}
(&p1).Say2()
  1. The value in the receiver needs to be modified
  2. The receiver is a large object with high copy cost
  3. To ensure consistency, if a method uses a pointer receiver, other methods should also use a pointer receiver.

reference material: https://blog.csdn.net/leo_jk/article/details/118438213

Object oriented inheritance

Inheritance through nested structures

// Person definition structure
type Person struct {
	name     string
	sex, age int8
	//Nested anonymous structure
	Student
	//Nested structure
	//Student Student
}

// Student defines the nested structure
type Student struct {
	School string `json:"schoolName"`
	//Specify the tag to realize the key when json serializes the field
	Id string `json:"student"`
}

// Say uses the receiver of the pointer type to create a method for the Person structure
func (p *Person) Say() {
	fmt.Println(p.name + "Hello")
}

// printSchool creates a method using the receiver Student struct of pointer type
func (s Student) printSchool() {
	fmt.Println("Welcome to" + s.School)
}

func main() {
	// Instantiate a structure
	p1 := Person{
		name: "Li Si",
		sex:  1,
		age:  18,
		Student: Student{
			Id:     "123456",
			School: "Xi'an Jiaotong University",
		},
	}

	data, err := json.Marshal(p1)
	if err != nil {
		fmt.Println("json marshal failed!")
		return
	}
	fmt.Printf("json str:%s\n", data)

	// Call your own method
	p1.Say()
	// Call a method that inherits the Student structure
	p1.printSchool()
}

Object oriented polymorphism

type Square struct {
	sideLen float32
}

type Triangle struct {
	Bottom float32
	Height float32
}

func (s *Square) Area() {
	fmt.Println("Square area calculation")
}

func (t *Triangle) Area() {
	fmt.Println("Triangle area calculation")
}

func main() {
	t := Triangle{
		Bottom: 15,
		Height: 20,
	}
	s := Square{
		sideLen: 10
	}

	//Calculated area
	t.Area()
	s.Area()
}

Topics: Go