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

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?