加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 19:00:36 所属栏目:大数据 来源:网络整理
导读:最近再实现一些功能, 用到了protobuf 还有 xml 。从他们书写的类型或是测试用例中, 看到了大量这样的数据结构: type Person struct { Name string `xml:"name"` URI string `xml:"uri,attr"` Email string `xml:"email,omitempty"` InnerXML string `xml:

最近再实现一些功能, 用到了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 main
import (
"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

struct
interface
main.Info
abc:"type,omitempty" nnn:"xxx"
xxx
name

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读