199
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
  • 2
    JSON is of course prolific. That the json library does not handle case conversion for the single most ubiquitous style (camel-case) both when serializing and deserializing, without this asinine hack, is really inexcusable. Jun 1, 2020 at 1:43

2 Answers 2

148

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.

0
105

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",...}`

Not the answer you're looking for? Browse other questions tagged or ask your own question.