一 struct类型
二 interface类型
面向对象3个特性:封装 继承 多态
1.封装(将方法或成员变量赋予一个结构体)
type cxx struct {
body string
}
func (c *cxx) work(){
fmt.Println(c.body)
}
func main(){
c := cxx{body: 'strong'}
c.work()
}
2.继承(子结构体拥有父级的方法)
type father struct {
body string
}
type son struct {
father
}
func (f *father) keep(){
fmt.Println(f.body)
}
func main(){
s := son{ father{ body:'strong' } }
s.keep()
}
3. interface (实现了这个接口的方法的结构体,该结构体的实例就和接口一个类型)(隐式声明)
type animal interface{
eat()
}
type cat struct {}
type dog struct {}
func (c cat) eat(){}
func (d dog) eat(){}
func main(){
var a animal
a = cat{}
a = dog{}
// cat 结构体 和 dog 结构体 和 animal 属于一个类型
}