【问题标题】:What is the usage of backtick in golang structs definition? [duplicate]golang结构定义中反引号的用途是什么? [复制]
【发布时间】:2015-08-21 06:16:23
【问题描述】:
type NetworkInterface struct {
    Gateway              string `json:"gateway"`
    IPAddress            string `json:"ip"`
    IPPrefixLen          int    `json:"ip_prefix_len"`
    MacAddress           string `json:"mac"`
    ...
}

我很困惑反引号中内容的功能是什么,例如json:"gateway"

只是评论吗,比如//this is the gateway

【问题讨论】:

  • JSON 当然是多产的。 json 库在序列化和反序列化时不处理最普遍的样式(驼峰式)的大小写转换,没有这种 asinine hack,真是不可原谅。

标签: go


【解决方案1】:

他们是tags:

字段声明后面可以跟一个可选的字符串文字标记, 它成为相应字段中所有字段的属性 字段声明。标签通过反射可见 接口并参与结构的类型标识,但除此之外 忽略。

// A struct corresponding to the TimeStamp protocol buffer.
// The tag strings define the protocol buffer field numbers.
struct {
  microsec  uint64 "field 1"
  serverIP6 uint64 "field 2"
  process   string "field 3"
}

查看this question and answer以获得更详细的解释和答案。

back quotes 用于创建可以包含任何类型字符的原始字符串文字:

原始字符串文字是反引号``之间的字符序列。 在引号内,任何字符都是合法的,除了反引号。

【讨论】:

  • 感谢您的反引号解释。
【解决方案2】:

您可以以标签的形式向 Go 结构添加额外的元信息。 Here are some examples of use cases.

在这种情况下,json package 使用json:"gateway"Gateway 的值编码为相应json 对象中的键gateway

例子:

n := NetworkInterface{
   Gateway : "foo"
}
json.Marshal(n)
// will output `{"gateway":"foo",...}`

【讨论】:

    猜你喜欢
    • 2017-10-01
    • 2021-10-09
    • 1970-01-01
    • 2016-09-17
    • 2018-09-11
    • 2011-12-16
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多