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

t j
  • 7,026
  • 12
  • 46
  • 66
harryz
  • 4,980
  • 6
  • 31
  • 34
  • 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. – Rick O'Shea Jun 01 '20 at 01:43

2 Answers2

151

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.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
IamNaN
  • 6,654
  • 5
  • 31
  • 47
108

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",...}`
Community
  • 1
  • 1
Johan Wikström
  • 4,033
  • 4
  • 28
  • 31