Go语言中的结构体《三》

struct的方法

Golang中的方法是作用在特定类型的变量上,因此自定义类型,都可以有方法,而不仅仅是struct
定义:func (recevier type) methodName(参数列表)(返回值列表){}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
type student struct {
name string
age int
score int
}

func (p *student) init(name string, age, score int) {
p.name = name
p.age = age
p.score = score
}

func (p student) getName() string {
return p.name
}

func (p student) print() {
fmt.Println("p is :", p)
}

func main() {
var stu student
stu.init("张三", 18, 61)
stu.print()
name := stu.getName()
fmt.Printf("stu name:%s\n", name)
}

struct的继承

如果一个struct嵌套了另一个匿名结构体,那么这个结构可以直接访问匿名结构体的方法,从而实现了继承。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
type car struct {
brand string
model string
}

type train struct {
car
wheel int
}

func (p car) run() {
fmt.Printf("%s run....\n", p.brand)
}
func main() {
var tr train
tr.brand = "火车"
tr.model = "长"
tr.wheel = 50
tr.run()
}
------
火车 run....

如果一个struct嵌套了另一个有名结构体,那么这个模式就叫组合。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
type car struct {
brand string
model string
}

type audi struct {
c car
wheel int
}

func (p car) run() {
fmt.Printf("%s run....\n", p.brand)
}

func main() {
var ad audi
ad.c.brand = "奥迪"
ad.c.model = "suv"
ad.wheel = 4
ad.c.run()
}
------
奥迪 run....