SoFunction
Updated on 2025-03-05

Golang study notes (VI): struct

struct

struct, a collection of fields, similar to class in other languages

Abandoned a large number of object-oriented features including inheritance, and only the most basic feature of composition is retained.

1. Declaration and initialization

Copy the codeThe code is as follows:

type person struct {
    name string
    age  int
}

//initialization

func main() {
    var P person

    = "tom"
    = 25
    ()

    P1 := person{"Tom1", 25}
    ()

    P2 := person{age: 24, name: "Tom"}
    ()
}

Anonymous field (inheritance)

Copy the codeThe code is as follows:

type Human struct {
    name string
    age int
    weight int
}

tyep Student struct {
Human //Anonymous field, the default Student contains all Human fields
    speciality string
}

mark := Student(Human{"mark", 25, 120}, "Computer Science")




It can realize field inheritance. When the field name is repeated, the outer layer will be given priority. You can also decide which one to choose by specifying the struct name.
Copy the codeThe code is as follows:

= Human{"a", 55, 220}
-= 1

struct can not only use struct as an anonymous field, custom types and built-in types can be used as an anonymous field, but also function operations on the corresponding fields


Copy the codeThe code is as follows:

type Rect struct {
    x, y float64
    width, height float64
}

//method


Receiver is passed as a value instead of a reference, or a pointer
As the Receiver, the pointer operates on the content of the instance object, while as the Receiver, the ordinary type, only uses a copy as the operation object, and does not operate on the original instance object.
Copy the codeThe code is as follows:

func (r ReciverType) funcName(params) (results) {

}


If the receiver of a method is *T, when calling, you can pass a T-type instance variable V without using &V to call this method
Copy the codeThe code is as follows:

func (r *Rect) Area() float64 {
    return *
}

func (b *Box) SetColor(c Color) {
    = c
}

Inheritance and rewrite

Inheritance is achieved through combination

Copy the codeThe code is as follows:

type Human struct {
    name string
}

type Student struct {
    Human
    School string
}

func (h *Human) SayHi() {
    ()
}

//The instances of Student and Employee can be called
func main() {
    h := Human{name: "human"}
    ()
    ()

    s := Student{Human{"student"}}
    ()

}


You can also rewrite the method
Copy the codeThe code is as follows:

funct (e *Student) SayHi() {
    ()
    ()
}