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
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)
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.
= 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
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.
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
func (r *Rect) Area() float64 {
return *
}
func (b *Box) SetColor(c Color) {
= c
}
Inheritance and rewrite
Inheritance is achieved through combination
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
funct (e *Student) SayHi() {
()
()
}