1、嵌入类型是将已有的类型直接声明在新的结构类型里。被嵌入的类型被称为新的外部类型的内部类型。
2、通过嵌入类型,与内部类型相关的标识符(字段、方法)会提升到外部类型上。这些被提升的标识符就像直接声明在外部类型里的标识符一样,也是外部类型的一部分。外部类型也可以通过声明与内部类型标识符同名的标识符来覆盖内部标识符的字段或方法,例1:
type user struct {
name string
email string
}
func (u *user) notify(){ fmt.Printf("Sending user email to %s<%s>\n", u.name, u.email) }
type admin struct {
user
level string
}
func main(){
ad := admin{
user: user{
name: "john smith",
email: "john@yahoo.com",
},
level: "super",
}
ad.user.notify() //可以直接访问内部类型的方法
ad.notify() //内部类型的方法也可以提升到外部类型
ad.name = "tom" //内部类型的字段也可以提升到外部类型
ad.email = "tom@163.com"
ad.notify()
}
//运行结果:
Sending user email to john smith<john@yahoo.com>
Sending user email to john smith<john@yahoo.com>
Sending user email to tom<tom@163.com>
例2:
type notifier interface { notify() }
type user struct {
name string
email string
}
func (u *user) notify() { fmt.Printf("Sending user email to %s<%s>\n", u.name, u.email) }
type admin struct {
user
level string
}
func (a *admin) notify(){ fmt.Printf("Sending admin email to %s<%s>\n", a.name, a.email) }
func main() {
ad := admin{
user: user{
name: "john smith",
email: "john@yahoo.com",
},
level: "super",
}
sendNotification(&ad)
ad.user.notify()
ad.notify()
}
func sendNotification(n notifier){n.notify()}
// 运行结果:
Sending admin email to john smith<john@yahoo.com>
Sending user email to john smith<john@yahoo.com>
Sending admin email to john smith<john@yahoo.com>
// 注:外部类型实现了notify方法,内部类型的实现就不会被提升。不过内部类型的值一直存在。