10.4 帶標籤的結構體

結構體中的字段除了有名字和類型外,還可以有一個可選的標籤(tag):它是一個附屬於字段的字符串,可以是文檔或其他的重要標記。標籤的內容不可以在一般的編程中使用,只有包 reflect 能獲取它。我們將在下一章(第 11.10 節)中深入的探討 reflect包,它可以在運行時自省類型、屬性和方法,比如:在一個變量上調用 reflect.TypeOf() 可以獲取變量的正確類型,如果變量是一個結構體類型,就可以通過 Field 來索引結構體的字段,然後就可以使用 Tag 屬性。

示例 10.7 struct_tag.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

鏈接

results matching ""

    No results matching ""