标签:
继承
package main
import (
"fmt"
)
type People struct {
name string
age int
weight int
}
type Student struct {
People
specialty string
}
// define sayHi method on People struct
func (p People) sayHi() {
fmt.Println(1)
}
func main() {
p := People{"syy", 1, 2}
s := Student{People{"syy", 1, 2}, "Seecialty"}
p.sayHi()
s.sayHi()
}
下面的方法,主要作用是在People结构体上定义一个sayHi的方法
// define sayHi method on People struct
func (p People) sayHi() {
fmt.Println(1)
}
People 结构体定义的,但是Student也有这个方法。或者可以说成"人可以问好,学生当然也可以问好"。
所以Strudent的sayhi方法是从People继承过来的。
复写
通过上面的代码,知道了继承,我们再往代码里面加入下面的代码
// define sayHi method on Student struct
func (s Student) sayHi() {
fmt.Println(2)
}
这段代码的作用是 在Student结构体上也增加一个sayHi的方法。
通过运行,可以看到输出的是2 而不是原来的1
故,Student的sayHi方法复写了People sayHi的方法。
标签:
原文地址:http://my.oschina.net/0x4ad/blog/373995