Golang study notes (vi) : struct

  • 2020-05-27 05:49:41
  • OfStack

struct

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

A large number of object-oriented features, including inheritance, were abandoned, leaving only the most basic feature of composition (composition)

1. Declaration and initialization


type person struct {
    name string
    age  int
} // Initialize the func main() {
    var P person     P.name = "tom"
    P.age = 25
    fmt.Println(P.name)     P1 := person{"Tom1", 25}
    fmt.Println(P1.name)     P2 := person{age: 24, name: "Tom"}
    fmt.Println(P2.name)
}

2. Anonymous fields of struct (inheritance)


type Human struct {
    name string
    age int
    weight int
} tyep Student struct {
    Human // Anonymous field, default Student Contains the Human All of the fields
    speciality string
} mark := Student(Human{"mark", 25, 120}, "Computer Science") mark.name
mark.age

Field inheritance can be implemented. When the field name is repeated, take the outer one first. You can also decide which one to take by specifying the struct name

mark.Human = Human{"a", 55, 220}
mark.Human.age -= 1

Not only can struct use struct as an anonymous field, custom types and built-in types can be used as anonymous fields, but also functions can be performed on the corresponding fields

3.method


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

Reciver is passed by default as a value, not a reference, and can also be a pointer
Pointers as Receiver operate on the contents of the instance object, while common types as Receiver operate only on the copy of the object, not on the original instance object

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

If the receiver of an method is *T, an instance variable of type T can be passed without having to use it when called & V to call this method

func (r *Rect) Area() float64 {
    return r.width * r.height
} func (b *Box) SetColor(c Color) {
    b.color = c
}

4.method inheritance and rewrite

Inheritance is implemented by composition


type Human struct {
    name string
} type Student struct {
    Human
    School string
} func (h *Human) SayHi() {
    fmt.Println(h.name)
} // the Student and Employee Can be called
func main() {
    h := Human{name: "human"}
    fmt.Print(h.name)
    h.SayHi()     s := Student{Human{"student"}}
    s.SayHi() }

You can also do method rewriting

funct (e *Student) SayHi() {
    e.Human.SayHi()
    fmt.Println(e.School)
}


Related articles: