在Go语言中,我们可以使用结构体来定义一种组合数据类型。而Tag是Go语言中一个比较有特色的概念,它允许我们给结构体的字段附加元信息,这些元信息可以在运行期间通过反射来获取。
在结构体定义的字段后面,我们可以使用一组符号括起来的字符串来表示这个字段的tag,它可以是一个单独的标识符,也可以是一个列表,以空格分隔。Tag的语法如下:
type StructName struct {
FieldName FieldType `TagKey:"TagValue"`
}FieldNameFieldTypeTagKeyTagValuereflect.StructTagpackage main
import (
"fmt"
"reflect"
)
type User struct {
Name string `json:"name" log:"true"`
Age int `json:"age" log:"false"`
}
func main() {
user := User{
Name: "Alice",
Age: 18,
}
t := reflect.TypeOf(user)
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
fmt.Printf("%s: %s\n", field.Name, string(field.Tag))
fmt.Printf("json: %s\n", field.Tag.Get("json"))
fmt.Printf("log: %s\n", field.Tag.Get("log"))
}
}Tag.Get()Name: json:"name" log:"true" json: name log: true Age: json:"age" log:"false" json: age log: false
string()reflect.StructTagencodingtype Date struct {
Year int `json:"year"`
Month int `json:"month"`
Day int `json:"day"`
}YearMonthDayjson