参考:
http://c.biancheng.net/view/74.html
结构体内嵌初始化时,将结构体内嵌的类型作为字段名像普通结构体一样进行初始化,详细实现过程请参考下面的代码。
package main
import "fmt"
type Wheel struct {
Size int
}
type Engine struct {
Power int
Type string
}
type Car struct {
Wheel
Engine
}
func main() {
c := Car{
Wheel : Wheel{
Size: 2,
},
Engine : Engine{
Power: 3,
Type: "12.3",
},
}
fmt.Printf("%+v\n", c)
}
初始化内嵌
结构体
在前面描述车辆和引擎的例子中,有时考虑编写代码的便利性,会将结构体直接定义在嵌入的结构体中。也就是说,结构体的定义不会被外部引用到。在初始化这个被嵌入的结构体时,就需要再次声明结构才能赋予数据。具体请参考下面的代码。
package main
import "fmt"
type Tree struct {
name string
}
type poplar struct {
Tree
Info struct {
Leaf string
Num int
}
}
func main() {
p := poplar{
Tree: Tree{
name: "small yellow",
},
Info: struct {
Leaf string
Num int
}{Leaf: "yellow", Num: 20},
}
fmt.Printf("poplar value:\t%v", p)
}

网友评论