先看一段简单的代码:
package main
import (
"fmt"
)
type A struct {
B
m int
}
type B struct {
n int
}
func (b *B) my_print() {
fmt.Printf("print B.n=%d\n", b.n)
}
func main() {
a := &A{B{2}, 3}
fmt.Printf("A.n=%d, A.m=%d\n", a.n, a.m)
a.my_print()
}
执行结果:
D:/PROGRAM/Golang/src/study/anonymous_struct/anonymous_struct.exe [D:/PROGRAM/Golang/src/study/anonymous_struct]
A.n=2, A.m=3
print B.n=2
成功: 进程退出代码 0.
如上述所示,B是结构体A的匿名字段;所以B的成员n对于结构体A来说相当于是A自己的成员变量a.n,而且,B的方法也是A的方法, a.my_print()。