golang 反射, 诡异的数据类型。 Type.Tag

golang 反射, 诡异的数据类型。 Type.Tag,第1张

概述最近再实现一些功能, 用到了protobuf 还有 xml 。从他们书写的类型或是测试用例中, 看到了大量这样的数据结构: type Person struct { Name string `xml:"name"` URI string `xml:"uri,attr"` Email string `xml:"email,omitempty"` InnerXML string `xml:",inne

最近再实现一些功能, 用到了protobuf 还有 xml 。从他们书写的类型或是测试用例中, 看到了大量这样的数据结构:

type Person struct {

name string `xml:"name"`

URI string `xml:"uri,attr"`

Email string `xml:"email,omitempty"`

InnerXML string `xml:",innerxml"`

}

源码可以见xml/marshal_test.go

http://golang.org/src/pkg/encoding/xml/marshal_test.go

Person 类型中, 红色字, 反引号括起来的这部分是什么?干什么用的?

从源码中顺藤摸瓜,一直找到了xml的私有库 typeinfo:

http://golang.org/src/pkg/encoding/xml/typeinfo.go

51行:

func getTypeInfo(typ reflect.Type) (*typeInfo,error) {

还有111行 :

func structFIEldInfo(typ reflect.Type,f *reflect.StructFIEld) (*fIEldInfo,error) {
看完这两个函数的使用后, 终于找到答案了。
重点在于 reflect.StructFIEld 数据类型。然后我们看怎么样通过一个简单的例子得到它。

函数库的 reflect.TypeOf 或者reflect.ValueOf(xx).Type() 返回的reflect.Type 数据类型。


package mainimport ("reflect""fmt")
type Info struct {
name string `abc:"type,attr,omitempty" nnn:"xxx"`
//pass struct{} `test`
}
func main() {
info := Info{"hello"}
ref := reflect.ValueOf(info)
fmt.Println(ref.Kind())
fmt.Println(reflect.Interface)
fmt.Println(ref.Type())
typ := reflect.TypeOf(info)
n := typ.NumFIEld()
for i := 0; i < n; i++ {
f := typ.FIEld(i)
fmt.Println(f.Tag)
fmt.Println(f.Tag.Get("nnn"))
fmt.Println(f.name)}}

http://play.golang.org/p/aPb9JBZaX5

structinterfacemain.Infoabc:"type,omitempty" nnn:"xxx"xxxname

GoLang 总结

以上是内存溢出为你收集整理的golang 反射, 诡异的数据类型。 Type.Tag全部内容,希望文章能够帮你解决golang 反射, 诡异的数据类型。 Type.Tag所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1292803.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-10
下一篇 2022-06-10

发表评论

登录后才能评论

评论列表(0条)

保存