What is the use of reverse in golang structs definition?

type NetworkInterface struct { Gateway string `json:"gateway"` IPAddress string `json:"ip"` IPPrefixLen int `json:"ip_prefix_len"` MacAddress string `json:"mac"` ... } 

I'm pretty confused that the content function is in a backtick, like json:"gateway" .

Is this just a comment, for example //this is the gateway ?

+53
go
Jun 06 '15 at 9:15
source share
2 answers

You can add additional meta information to Go structures as tags. Here are some examples of use .

In this case, json:"gateway" used by the json package to encode the Gateway value in the Gateway key in the corresponding json object.

Example:

 n := NetworkInterface{ Gateway : "foo" } json.Marshal(n) // will output `{"gateway":"foo",...}` 
+31
Jun 06 '15 at 9:23
source share

They are tags :

The field declaration may be followed by an optional string literal tag, which becomes an attribute for all fields of the corresponding field declaration. Tags become visible through the reflection interface and take part in identifying types for structures, 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.

backticks are used to create source string literals that can contain any type of character:

String string literals are sequences of characters between the back quotes ``. In quotation marks, any character is legal except quotation back.

+35
Jun 06 '15 at 9:23
source share



All Articles