- tag的作用:对字段的解释或补充信息
- tag的形式有两种:纯字符串形式、key-value形式
- tag信息的获取方式:反射
- 使用到tag的例子:json.Marshal、gorm等
import (
"fmt"
"reflect"
)
type Person struct {
Name string `a b c`
Age int64 `dasjhfas`
Class string `json:"class" a:"class-a" b:"class-b"`
}
func main() {
per := Person{"ccc", 23, "junior-class-one"}
perType := reflect.TypeOf(per)
fieldName, _ := perType.FieldByName("Name")
fieldAge, _ := perType.FieldByName("Age")
fieldClass, _ := perType.FieldByName("Class")
fmt.Println(fieldName.Tag)
fmt.Println(fieldAge.Tag)
fmt.Println(fieldClass.Tag)
fmt.Println(fieldClass.Tag.Lookup("json"))
fmt.Println(fieldClass.Tag.Lookup("a"))
fmt.Println(fieldClass.Tag.Lookup("b"))
bytes, err := json.Marshal(per)
if err != nil {
return
}
fmt.Println(string(bytes))
}
输出1:
a b c
dasjhfas
json:"class" a:"class-a" b:"class-b"
输出2:
class true
class-a true
class-b true
输出3:
{"Name":"ccc","Age":23,"class":"junior-class-one"}