Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange type definition syntax in Golang (name, then type, then string literal)

Tags:

go

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.

like image 857
Sebastián Grignoli Avatar asked Jul 13 '12 18:07

Sebastián Grignoli


People also ask

What are string literals in Golang?

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

What is type string in Golang?

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.

Is string a literal?

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.


1 Answers

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" } 
like image 144
Keith Thompson Avatar answered Sep 17 '22 14:09

Keith Thompson