翻譯自The way to go 10.4
在go語(yǔ)言的一個(gè)struct中,除了變量名和類(lèi)型之外,還可以選擇性的增加一些tag:tag可以在類(lèi)型的后面,用雙引號(hào)(double quote)或重音(backquote/grave accent)表示的字符串。這些符號(hào)能被用來(lái)做文檔或重要的標(biāo)簽。
tag里面的內(nèi)容在正常編程中沒(méi)有作用。只有在使用反射的時(shí)候才有作用。反射的包可以讓我們?cè)谶\(yùn)行時(shí)獲取到變量的類(lèi)型,屬性以及方法。比如reflect.TypeOf()就可以返回一個(gè)變量的類(lèi)型。如果是一個(gè)struct類(lèi)型,可以按照每一個(gè)變量索引,來(lái)查詢每一個(gè)的tag。
package main
import (
"fmt"
"reflect"
)
type TagType struct {
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}
var reflectType reflect.Type = reflect.TypeOf(tt)
var ixField reflect.StructField
for i := 0; i < 3; i++ {
ixField = reflectType.Field(i)
fmt.Printf("%s\n", ixField.Tag)
}
}
輸出
An important answer
The name of the thing
how much there are