使用反射检索结构体变量的注释。

huangapple go评论73阅读模式
英文:

Retrieve annotations on structs' variables using reflection

问题

在Go语言中,可以使用反射来获取结构体变量的注解。考虑以下结构体:

type AType struct {
    ID   string `xml:"my_id"`
    Date string `xml:"creation_ts"`
}

如何使用反射来获取ID字段的xml:"my_id"注解呢?下面的代码将打印变量的名称、类型和值,但不包括注解

s := reflect.ValueOf(&aType).Elem()
typeOfT := s.Type()
for i := 0; i < s.NumField(); i++ {
    f := s.Field(i)
    fmt.Printf("%d: %s %s = %v\n", i,
        typeOfT.Field(i).Name, f.Type(), f.Interface())
}

希望对你有帮助!

英文:

In go, is it possible to retrieve structs' variable annotation? Considering the following struct:

type AType struct {
	ID        string    `xml:&quot;my_id&quot;`
	Date      string    `xml:&quot;creation_ts&quot;`
}

How can I retrieve the xml:&quot;my_id&quot; part for the ID field using reflection ? The following will print the name, type and value of the variable but not the annotation.

s := reflect.ValueOf(&amp;aType).Elem()
typeOfT := s.Type()
for i := 0; i &lt; s.NumField(); i++ {
	s.Field(i).
	f := s.Field(i)
	fmt.Printf(&quot;%d: %s %s = %v\n&quot;, i,
		typeOfT.Field(i).Name, f.Type(), f.Interface())
}

Thanks,

答案1

得分: 2

StructField.Tag 可以用作 f.Tag

参考资料:

一个可运行的示例,由 @mkopriva 提供:https://play.golang.org/p/reY-IDCyaq

英文:

It is available as StructField.Tag, so

f.Tag

References:

A working example, credits @mkopriva: https://play.golang.org/p/reY-IDCyaq

huangapple
  • 本文由 发表于 2017年3月27日 07:58:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/43036010.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定