From 53a973d0daf8508ba271b804cef44f7c272d2610 Mon Sep 17 00:00:00 2001 From: leisore Date: Sat, 4 Jul 2015 17:16:29 +0800 Subject: [PATCH] =?UTF-8?q?+=20ch10.4=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- eBook/10.3.md | 2 +- eBook/10.4.md | 42 ++++++++++++++++++++++++++++++++++++++++++ eBook/directory.md | 1 + 3 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 eBook/10.4.md diff --git a/eBook/10.3.md b/eBook/10.3.md index 2ee96d3..430fde6 100644 --- a/eBook/10.3.md +++ b/eBook/10.3.md @@ -37,4 +37,4 @@ func main() { ## 链接 - [目录](directory.md) - 上一节:[10.2 使用工厂方法创建结构体实例](10.2.md) -- 下一节:[10.4 Structs with tags](10.4.md) +- 下一节:[10.4 带标签的结构体](10.4.md) diff --git a/eBook/10.4.md b/eBook/10.4.md new file mode 100644 index 0000000..d6c759d --- /dev/null +++ b/eBook/10.4.md @@ -0,0 +1,42 @@ +# 10.4 带标签的结构体 + +结构体中的成员除了有名字和类型外,还可以有一个可选的标签(tag):它是一个附属于成员的字符串,可以是文档或其他的重要标记。标签的内容不可以在一般的编程中使用,只有包`reflect`能获取它。我们将在下一章(11.10)中深入的探讨`reflect`包,它可以在运行时自省类型、属性和方法,比如:在一个变量上调用` reflect.TypeOf()`可以获取变量的正确类型,如果变量是一个结构体类型,就可以通过Field来索引结构体的成员,然后就可以使用Tag属性。 + + Listing 10.7—struct_tag.go展示了如何使用它: + ```go + package main + +import ( + "fmt" + "reflect" +) + +type TagType struct { // tags + field1 bool "An important answer" + field2 string "The name of the thing" + field3 int "How much there are" +} + +func main() { + tt := TagType{true, "Barak Obama", 1} + for i := 0; i < 3; i++ { + refTag(tt, i) + } +} + +func refTag(tt TagType, ix int) { + ttType := reflect.TypeOf(tt) + ixField := ttType.Field(ix) + fmt.Printf("%v\n", ixField.Tag) +} + ``` + + 输出: + An important answer + The name of the thing + How much there are + +## 链接 +- [目录](directory.md) +- 上一节:[10.3 使用自定义包中的结构体](10.3.md) +- 下一节:[10.5 匿名成员和嵌套结构体](10.5.md) diff --git a/eBook/directory.md b/eBook/directory.md index b90b5bd..ef36281 100644 --- a/eBook/directory.md +++ b/eBook/directory.md @@ -88,6 +88,7 @@ - 10.1 [结构体定义](10.1.md) - 10.2 [使用工厂方法创建结构体实例](10.2.md) - 10.3 [使用自定义包中的结构体](10.3.md) + - 10.4 [带标签的结构体](10.4.md) - 第11章:接口(interface)与反射(reflection) ## 第三部分:Go 高级编程