What is the usage of backtick in golang structs definition? [duplicate]

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?


They 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.


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