Problem: You want to define metadata to describe the struct fields.
Solution: Use struct tags to define metadata and the reflect package to access the tags.
One very common place you find this is in the json package:
type Person struct { Id int `json:"id"` GivenName string `json:"given_name"` FamilyName string `json:"family_name"` Email string `json:"email"` }
Many packages that process structs use struct tags. For example, xml package, the protobuf package, and the sqlx package all use struct tags. You can also roll out your support for struct tags using the reflect package.
Struct tags are defined in name-value pairs within the string literal. In the preceding example, where the string literal is json:"given_name" , the name is json and the value is a string "given_name".
Here’s how you can extract the values:
func main() { person := Person{ Id: 1, GivenName: "Sau Sheong", FamilyName: "Chang", Email: "sausheong@email.com", } p := reflect.TypeOf(person) k := fmt.Sprint(reflect.ValueOf(person).Kind()) if k == "struct" { for i := 0; i < p.NumField(); i++ { field := p.Field(i) fmt.Println(field.Tag.Get("json")) } } }
To get the values from the struct tags, you use the reflect package. Start with getting the Type of the person variable, which is a struct. The NumField method on the struct Type tells you how many fields are in this struct , which is 4. Then you call the Field method on the struct Type with a given index to get the StructField . Call the Tag method on the StructField to get the StructTag , and finally call the Get method with the name to get the value.
Each struct tag can contain more than a single name-value pair, so you can call Get on different names to get to the corresponding values.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律