Go 嵌入类型
什么事嵌入类型:可以把已有的类型声明在新的类型里面,在其他语言可以采用继承的方式,就可以拥有父类的方法以及属性,而go中结构体的属性嵌入组合会相识且更加方便
接口类型
代码案例
//这里 student 就是内部类型 | |
type student struct { | |
name string | |
email string | |
} | |
//people 是外部类型 | |
//通过嵌入类型,与内部类型相关联的所有字段、方法、标志符等等所有,都会被外包类型所拥有,就像外部类型自己的一样,这就达到了代码快捷复用组合的目的,而且定义非常简单,只需声明这个类型的名字就可以了。 | |
//同时,外部类型还可以添加自己的方法、字段属性等,可以很方便的扩展外部类型的功能。 | |
type teacher struct { | |
student | |
level string | |
} | |
func main() { | |
tea:=teacher{student{"董雷","donglei@qq.com"},"班长"} | |
fmt.Println("可以直接调用,名字为:",tea.name) | |
fmt.Println("也可以通过内部类型调用,名字为:",tea.student.name) | |
fmt.Println("但是新增加的属性只能直接调用,级别为:",tea.level) | |
} | |
//返回如下 | |
可以直接调用,名字为: 董雷 | |
也可以通过内部类型调用,名字为: 董雷 | |
但是新增加的属性只能直接调用,级别为: 班长 |
方法覆盖的问题
//这里 student 就是内部类型 | |
type student struct { | |
name string | |
email string | |
} | |
//people 是外部类型 | |
//通过嵌入类型,与内部类型相关联的所有字段、方法、标志符等等所有,都会被外包类型所拥有,就像外部类型自己的一样,这就达到了代码快捷复用组合的目的,而且定义非常简单,只需声明这个类型的名字就可以了。 | |
//同时,外部类型还可以添加自己的方法、字段属性等,可以很方便的扩展外部类型的功能。 | |
type teacher struct { | |
student | |
level string | |
} | |
func (s student) sayHello(){ | |
fmt.Println("Hello,i am a student") | |
} | |
func (t teacher) sayHello(){ | |
fmt.Println("Hello,i am a teacher") | |
} | |
func main() { | |
tea:=teacher{student{"董雷","donglei@qq.com"},"班长"} | |
//外部结构体对象调用方法,会覆盖子结构体 | |
tea.sayHello() | |
//如果想调用子结构体,需要多调用一层 | |
tea.student.sayHello() | |
} | |
//返回 | |
Hello,i am a teacher | |
Hello,i am a student |
实现接口
代码案例
//这里 student 就是内部类型 | |
type student struct { | |
name string | |
email string | |
} | |
//people 是外部类型 | |
//通过嵌入类型,与内部类型相关联的所有字段、方法、标志符等等所有,都会被外包类型所拥有,就像外部类型自己的一样,这就达到了代码快捷复用组合的目的,而且定义非常简单,只需声明这个类型的名字就可以了。 | |
//同时,外部类型还可以添加自己的方法、字段属性等,可以很方便的扩展外部类型的功能。 | |
type teacher struct { | |
student | |
level string | |
} | |
//定义一个接口,接口里面有一个hello抽象方法 | |
type Hello interface { | |
hello() | |
} | |
//为student结构体注册方法 | |
func (s student) hello() { | |
fmt.Println("Hello,i am a student") | |
} | |
//定义一个通用函数 | |
func sayHello(h Hello) { | |
h.hello() | |
} | |
func main() { | |
tea:=teacher{student{"董雷","donglei@qq.com"},"班长"} | |
sayHello(tea) | |
} | |
//返回结果 | |
Hello,i am a student |
这个例子原来的结构体类型student和teacher的定义不变,新增了一个接口Hello,然后让student类型实现这个接口,最后我们定义了一个sayHello方法,它接受一个Hello接口类型的参数,最终我们在main函数演示的时候,发现不管是student类型,还是teacher类型作为参数传递给sayHello方法的时候,都可以正常调用。