I've been trying to find out how to use mgo (MongoDB driver for Go) and I came across this struct declaration:
type Something struct { Id bson.ObjectId "_id,omitempty" Name string }
I don't quite understand the syntax of the first element (Id). I understand that it's being declared as type bson.ObjectId
, but what is the string literal doing there?
My question is not about the mgo driver functionality,
but about this strange <name> <type> <string_literal>
syntax.
I couldn't find anything on the Go specs, and I don't know how to google this either.
A string literal represents a string constant obtained from concatenating a sequence of characters. There are two forms: raw string literals and interpreted string literals. Raw string literals are character sequences between back quotes, as in `foo` .
string in Golang is a set of all strings that contain 8-bit bytes. By default, strings in Golang are UTF-8 encoded. Variable of type string is enclosed between double-quotes. The type string variable's value is immutable. The value assigned to the type string variable can be empty but cannot be nil.
A "string literal" is a sequence of characters from the source character set enclosed in double quotation marks (" "). String literals are used to represent a sequence of characters which, taken together, form a null-terminated string.
It's explained in the Struct types section of the language specification:
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.
// 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" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With