What is the usage of backtick in golang structs definition?

huangapple go评论89阅读模式
英文:

What is the usage of backtick in golang structs definition?

问题

这里的内容是用于标记字段在JSON序列化和反序列化时的名称。它不是注释,而是用于指定字段在JSON中的键名。在你提供的代码中,json:"gateway"表示该字段在JSON中的键名是"gateway"。这样做的目的是为了在将结构体转换为JSON字符串或将JSON字符串解析为结构体时,能够正确地映射字段。

英文:
type NetworkInterface struct {
    Gateway              string `json:"gateway"`
    IPAddress            string `json:"ip"`
    IPPrefixLen          int    `json:"ip_prefix_len"`
    MacAddress           string `json:"mac"`
    ...
}

I'm quite confused what's the function of contents in backtick, like json:"gateway".

Is it just comment, like //this is the gateway?

答案1

得分: 151

反引号(``)内的内容是标签

字段声明后可以跟一个可选的字符串字面标签,该标签将成为相应字段声明中所有字段的属性。这些标签通过反射接口可见,并参与结构体的类型标识,但在其他情况下会被忽略。

// 与 TimeStamp 协议缓冲区对应的结构体。
// 标签字符串定义了协议缓冲区字段的编号。
struct {
microsec uint64 "field 1"
serverIP6 uint64 "field 2"
process string "field 3"
}

有关更详细的解释和答案,请参见此问题和答案

反引号(``)用于创建原始字符串字面量,可以包含任何类型的字符:

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

英文:

The content inside the backticks are tags:

> A field declaration may be followed by an optional string literal tag,
> which becomes an attribute for all the fields in the corresponding
> field declaration. The tags are made visible through a reflection
> interface and take part in type identity for structs but are otherwise
> ignored.
>
> // 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"
> }

See this question and answer for a more detailed explanation and answer.

The back quotes are used to create raw string literals which can contain any type of character:

> Raw string literals are character sequences between back quotes ``.
> Within the quotes, any character is legal except back quote.

答案2

得分: 108

你可以通过标签(tags)的形式为Go结构体添加额外的元信息。这里有一些用例示例

在这个例子中,json:"gateway"json包用来将Gateway的值编码为相应JSON对象中的gateway键。

示例:

n := NetworkInterface{
   Gateway : "foo"
}
json.Marshal(n)
// 输出 `{ "gateway":"foo",...}`
英文:

You can add extra meta information to Go structs in the form of tags. Here are some examples of use cases.

In this case, the json:"gateway" is used by the json package to encode the value of Gateway into the key gateway in the corresponding json object.

Example:

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

huangapple
  • 本文由 发表于 2015年6月6日 17:15:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/30681054.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定