反勾在 golang 结构定义中的用法是什么?

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

66358 次浏览

反撇号中的内容是 标签:

字段声明后面可以跟一个可选的字符串文本标记, 中的所有字段的属性 字段声明。标记通过反射可见 接口,并参与结构的类型标识,但以其他方式参与 被忽略了。

// 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"
}

有关更详细的解释和答案,请参阅 这个问题和答案

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

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

您可以以标记的形式向 Go 结构添加额外的元信息。

在这种情况下,Json 包裹使用 json:"gateway"Gateway的值编码到相应 json 对象中的键 gateway中。

例如:

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