基于结构体实现Go的面向对象编程
// person结构体-person类
type person struct {
name string
age int8
}
// person成员方法
func (p person) sayHi() {
fmt.Printf("%s say Hi!
", p.name)
}
// person成员方法
func (p *person) happyBirthday() {
p.age++
}
// worker结构体-worker类
type worker struct {
person // 匿名嵌套(继承)
company string
}
// worker成员方法
func (w worker) working() {
w.sayHi() // 调用继承的方法
fmt.Println("work at " + w.company)
}
// 使用案例:
w := worker{person: person{name: "go", age: 18}, company: "google"}
w.working()
// 打印结果:
//go say Hi!
//work at google
方法重写:
func (w *worker) happyBirthday() {
w.age += 2 // + 2 ,persion为 + 1
}
// 调用案例:
w := worker{person: person{name: "go", age: 18}, company: "google"}
w.working()
w.happyBirthday()
fmt.Println(w.age)
// 打印结果:
//go say Hi!
//work at google
//20