type Teacher struct {
Name string `json:"name"`
Age int `json:"age"`
}
func getTag(i interface{}) string
getTag(teacher.Name) // print name
getTag(teacher.Age) // print age
我想像代码段一样滚动我的函数,但我找不到实现此目的的方法。有什么想法吗?
最佳答案
也许这会有所帮助。 https://play.golang.org/p/WtqdQAmsbi
x := struct {
Bar int `json:"bar"`
Foo string `json:"foo"`
}{2, "foo"}
v := reflect.ValueOf(x)
for i := 0; i < v.NumField(); i++ {
fmt.Println(v.Type().Field(i).Name)
fmt.Println(v.Type().Field(i).Tag)
}
获取结构字段的名称及其标签
关于Golang 反射 : passing a sturct member variable to a function and return its tag name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40879295/