Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

People also ask

What is backtick in Go?

Backtick strings are analogues of any multiline raw string within Python or else Scala: r""" text""" or within JavaScript: String. raw`Hello\u000A!` They are useful: For keeping huge text inside. For regular expressions, while you own many of backslashes.

What are tags in golang?

In the Go Language Specification, it mentions a brief overview of 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 but are otherwise ignored.


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