实现说明
底层就是函数 Describe、main。
使用要点
- 执行文件,
main会按顺序走完Describe。
常见问题
「嵌入结构体提升字段与方法」这个示例怎么运行?
运行这个文件就行;脚本没有任何外部要求。
主要签名是 func (b Base) Describe() string
核心语句
func (b Base) Describe() string { return b.Name + " (#" + b.ID + ")" }
func main() {
a := Admin{Base: Base{"u1", "ada"}, Level: 9}
// 提升字段:像直接字段一样访问,无需 a.Base.Name
fmt.Println(a.Name, a.ID, a.Level)
// 提升方法:同样直达
fmt.Println(a.Describe())
d := Deep{Admin: a}
fmt.Println(d.Name, d.Level) // 两层嵌入依然可直达
fmt.Println(d.Describe())
}
代码示例
package main
import "fmt"
type Base struct {
ID string
Name string
}
func (b Base) Describe() string { return b.Name + " (#" + b.ID + ")" }
// 匿名嵌入(embedded):字段与方法被提升(promoted)到外层类型
type Admin struct {
Base
Level int
}
// 深层嵌入:提升逐级穿透
type Deep struct {
Admin
}
func main() {
a := Admin{Base: Base{"u1", "ada"}, Level: 9}
// 提升字段:像直接字段一样访问,无需 a.Base.Name
fmt.Println(a.Name, a.ID, a.Level)
// 提升方法:同样直达
fmt.Println(a.Describe())
d := Deep{Admin: a}
fmt.Println(d.Name, d.Level) // 两层嵌入依然可直达
fmt.Println(d.Describe())
}