小编典典

golang structs 定义中反引号的用法是什么?

go

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吗?


阅读 328

收藏
2021-11-07

共2个答案

小编典典

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

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

例子:

n := NetworkInterface{
   Gateway : "foo"
}
json.Marshal(n)
// will output `{"gateway":"foo",...}`
2021-11-07
小编典典

它们是标签

字段声明后可以跟一个可选的字符串文字标记,它成为相应字段声明中所有字段的属性。这些标签通过反射接口可见,并参与结构的类型标识,否则会被忽略。

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

反引号用来创建它可以包含任何类型的字符的原始字符串字面量:

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

2021-11-07