HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoCritical

What is the usage of backtick in golang structs definition?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
usagebacktickdefinitionstructsthegolangwhat

Problem

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?

Solution

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

Code Snippets

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

Context

Stack Overflow Q#30681054, score: 114

Revisions (0)

No revisions yet.