From b8f93a8b1d4e480659dbfe5310f5639be1dd9216 Mon Sep 17 00:00:00 2001 From: leisore Date: Mon, 6 Jul 2015 15:53:48 +0800 Subject: [PATCH] =?UTF-8?q?+=20=E6=B7=BB=E5=8A=A0ch10.5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- eBook/10.4.md | 2 +- eBook/10.5.md | 98 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+), 1 deletion(-) create mode 100644 eBook/10.5.md diff --git a/eBook/10.4.md b/eBook/10.4.md index 66c152d..d96be4e 100644 --- a/eBook/10.4.md +++ b/eBook/10.4.md @@ -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) diff --git a/eBook/10.5.md b/eBook/10.5.md new file mode 100644 index 0000000..3c0da73 --- /dev/null +++ b/eBook/10.5.md @@ -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)