在 go 里面的面向对象没有class 的说法, go 还是使用func 和 结构体来实现面向对象编程, 并且可以实现继承和重写
例如 我定义一个 Person 对象, 它具有若干个属性, 其中的Action 是匿名字段
type Person struct {
name string // 姓名
gender string // 性别
age int // 年龄
height int // 身高
weight int // 体重
Action // 动作
}
然后我再定义一个 Action 对象,用来标记Person 可以做那些动作
type Action struct {
// 动作
}
到这里你可以理解为我定义了一个Person的对象它具有 姓名(name),
性别(gender), 年龄(age), 身高(height), 体重(weight), 动作(Action)等属性
现在该给这个Person的Action 加一些方法了,class 不就是属性 + 方法的组合吗?? 只不过go 没有class, 我们使用func 来实现加方法
func (ac Action) talk(chat string) {
fmt.Println("我跟你讲:", chat)
}
func (ac Action) eat (food string) {
fmt.Println("我请你吃: ", food)
}
func (ac Action) walk (where string) {
fmt.Println("我带你去: ", where)
}
func (ac Action) sleep() {
fmt.Println("睡觉觉")
}
func (ac Action) doSomething(thing string) {
fmt.Println("做某件事情", thing)
}
这里我给Action 这个动作加了几个方法talk, eat, walk, sleep, doSomething
继承
因为Person的属性里面包含了Action 因此你可以理解为Person 继承了Action的方法
实例化
people := Person{"张全蛋", "男", 20, 177, 60, Action{}}
# Person 继承自Action的几个方法
people.talk("PHP是世界上最好的语言")
people.eat("烤鱼")
people.walk("车陂")
people.doSomething("过家家")
重写,Person 继承了Action的几个方法,如果不需要使用可以进行重写
例如 我这里重写doSomething 这个方法
// Person 可以重写 Person 的动作
func (p Person) doSomething(thing string) {
fmt.Println("Person的doSomething方法: ", thing)
}