+ 添加ch10.5

This commit is contained in:
leisore
2015-07-06 15:53:48 +08:00
parent d4193467cd
commit b8f93a8b1d
2 changed files with 99 additions and 1 deletions

View File

@@ -40,4 +40,4 @@ func refTag(tt TagType, ix int) {
## 链接
- [目录](directory.md)
- 上一节:[10.3 使用自定义包中的结构体](10.3.md)
- 下一节:[10.5 匿名成员和嵌结构体](10.5.md)
- 下一节:[10.5 匿名成员和嵌结构体](10.5.md)

98
eBook/10.5.md Normal file
View File

@@ -0,0 +1,98 @@
# 10.5 匿名成员和内嵌结构体
## 10.5.1 定义
结构体可以包含一个或多个*匿名(或内嵌)成员*,即这些成员没有显式的名字,只有成员的类型是必须的,此时类型也就是成员的名字。匿名成员本身可以是一个结构体类型,即*结构体可以包含内嵌结构体*。
可以粗略地将这个和OO语言中的继承概念相比较随后将会看到它被用来模拟类似继承的行为。Go语言中的继承是通过内嵌或组合来实现的所以可以说在Go语言中相比较于继承组合更受青睐。
考虑如下的程序:
Listing 10.8—structs_anonymous_fields.go
```go
package main
import "fmt"
type innerS struct {
in1 int
in2 int
}
type outerS struct {
b int
c float32
int // anonymous field
innerS //anonymous field
}
func main() {
outer := new(outerS)
outer.b = 6
outer.c = 7.5
outer.int = 60
outer.in1 = 5
outer.in2 = 10
fmt.Printf("outer.b is: %d\n", outer.b)
fmt.Printf("outer.c is: %f\n", outer.c)
fmt.Printf("outer.int is: %d\n", outer.int)
fmt.Printf("outer.in1 is: %d\n", outer.in1)
fmt.Printf("outer.in2 is: %d\n", outer.in2)
// 使用结构体字面量
outer2 := outerS{6, 7.5, 60, innerS{5, 10}}
fmt.Printf("outer2 is:", outer2)
}
```
输出:
outer.b is: 6
outer.c is: 7.500000
outer.int is: 60
outer.in1 is: 5
outer.in2 is: 10
outer2 is:{6 7.5 60 {5 10}}
通过类型outer.int的名字来获取存储在匿名成员中的数据于是可以得出一个结论在一个结构体中对于每一种数据类型只能有一个匿名成员。
## 10.5.2 内嵌结构体
同样地结构体也是一种数据类型所以它也可以作为一个匿名成员来使用如同上面例子中那样。外层结构体通过outer.in1直接进入内层结构体的成员内嵌结构体甚至可以来自其他包。内层结构体被简单的插入或者内嵌进外层结构体。这个简单的“继承”机制提供了一种方式使得可以从另外一个或一些类型继承部分或全部实现。
另外一个例子:
Listing 10.9—embedd_struct.go
```go
package main
import "fmt"
type A struct {
ax, ay int
}
type B struct {
A
bx, by float32
}
func main() {
b := B{A{1, 2}, 3.0, 4.0}
fmt.Println(b.ax, b.ay, b.bx, b.by)
fmt.Println((b.A))
}
```
输出:
1 2 3 4
{1 2}
*练习 10.5* anonymous_struct.go
创建一个结构体它有一个具名的float成员2个匿名成员类型分别是int和string。通过结构体字面量新建一个结构体实例并打印它的内容。
## 链接
- [目录](directory.md)
- 上一节:[10.5 带标签的结构体](10.4.md)
- 下一节:[10.6 方法](10.6.md)