Golang的Tag语法_golang tag example,2024年最新不服不行
warning:
这篇文章距离上次修改已过192天,其中的内容可能已经有所变动。
package main
import (
"fmt"
"reflect"
)
type MyStruct struct {
Field1 int `json:"field_1" example:"1024"`
Field2 string `json:"field_2" example:"\"hello, world\""`
}
func main() {
s := MyStruct{
Field1: 1024,
Field2: "hello, world",
}
t := reflect.TypeOf(s)
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if exampleTag, ok := field.Tag.Lookup("example"); ok {
fmt.Printf("Example for field %s: %s\n", field.Name, exampleTag)
}
}
}
这段代码定义了一个结构体MyStruct
,其中每个字段都带有json
和example
标签。然后使用反射来遍历结构体的字段,并打印出每个字段的example
标签的值。这个例子展示了如何使用Golang的反射API来处理结构体字段的标签。
评论已关闭