dousi4900 2018-12-11 04:52
浏览 115
已采纳

此行“ 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.

  • 写回答

1条回答 默认 最新

  • duanlan7903 2018-12-11 05:02
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题