1.接口内嵌
内嵌是go语言中一种比较特别的用法,可以实现功能复用,代码如下:
package main
import (
"fmt"
)
type man interface {
height() int
weight() int
}
type property struct {
}
func (*property) height() int {
return 1
}
func (*property) weight() int {
return 2
}
type human struct {
man//需要被初始化
}
func main() {
p := &property{}
//hu := &human{man: p} //这种方式也可以
hu := &human{}
hu.man = p
re := hu.height()
fmt.Println(re)//1
}
2.结构体内嵌(匿名变量)
go语言支持结构体内嵌(可以省掉字段定义),功能类似c++的继承,是go比较特殊的功能。
参考资料:
本文介绍了Go语言中的两种内嵌机制:接口内嵌与结构体内嵌。通过具体代码示例展示了如何利用这两种机制来实现功能复用,并解释了其工作原理。文章适合有一定Go语言基础的读者。
3637





