此行“ binTag:= field.Tag.Get(“ binary”)”之后分配给“ bintag”的值是什么,其中field是GOLang中的struct字段之一

问题描述:

I was trying to analyse the GO program, when I encountered this line
"binTag := field.Tag.Get("binary")"
I was confused with value that "binTag" will be assigned.

I searched in the GO reflect Package for the syntax explanation and I found this,

func (tag StructTag) Get(key string) string

Get returns the value associated with key in the tag string. If there is no such key in the tag, Get returns the empty string. If the tag does not have the conventional format, the value returned by Get is unspecified. To determine whether a tag is explicitly set to the empty string, use Lookup.

Then I searched what is Tag mean in Golang, as an example I got this

Tag

A field declaration may be followed by an optional string literal (tag) which becomes an attribute of all the fields in the corresponding field declaration.

type T struct {
    f1     string "f one"
    f2     string
    f3     string `f three`
    f4, f5 int64  `f four and five`
}

So, now I am bit confused on exact value assigned to "binTag" after execution.

Thanks in Advance.

当我遇到此行时,我试图分析GO程序
“ binTag := field.Tag.Get(“ binary”)“ em>
我被混淆了将分配” binTag“ em>的值。 p> 我在GO Reflection包中搜索了语法说明,然后发现了这个 p>

func(标记为StructTag)Get(关键字字符串)字符串 em> strong> p>

Get返回与标签字符串中的键关联的值。 如果标签中没有这样的键,则Get返回空字符串。 如果标签没有常规格式,则未指定Get返回的值。 要确定是否将标签明确设置为空字符串,请使用Lookup。 em> p>

然后我搜索了Golang中的Tag含义,作为示例,我得到了 p >

Tag em> p>

字段声明之后可能是可选的字符串文字(标记),该字符串文字成为所有内容的属性 em> p>

  type T struct {
 f1字符串“ f one” 
 f2字符串
 f3字符串`f 3`  
 f4,f5 int64`f四和五`
} 
  code>  pre> 
 
 

所以,现在我对分配给“ binTag”的确切值有些困惑 em>。 p>

先谢谢了。 strong> p> div>

See the StructTag documentation for a description of the tag format.

See the StructTag example and the StructTag.Lookup examples examples of tags.

The value of binTag is "" because the tag does not contain a value for the key "binary", nor does the tag following the convention for formatting struct tags.

This code shows how to access the tag:

v := reflect.TypeOf(T{})
sf, _ := v.FieldByName("f1")
fmt.Println(sf.Tag)               // prints "f one"
fmt.Println(sf.Tag.Get("binary")) // prints blank line

Here's an example with a valid tag with key "binary":

type U struct {
    g1 string `binary:"hello"`
}

v := reflect.TypeOf(U{})
sf, _ := v.FieldByName("g1")
fmt.Println(sf.Tag)               // prints binary:"hello"
fmt.Println(sf.Tag.Get("binary")) // prints hello