Lexical elements: Identifiers

January 12, 2023

Identifiers

Identifiers name program entities such as variables and types. An identifier is a sequence of one or more letters and digits. The first character in an identifier must be a letter.

identifier = letter { letter | unicode_digit } .

So in other words, every identifier must begin with a letter, followed by zero or more letters and/or digits. Pretty simple.

The spec offers a few examples

a
_x9
ThisVariableIsExported
αβ

That second one looks a bit suspicious. _x9? We were just told that the first character of an identifier has to be a letter!

Ah, but remember last week (if you were reading then), we read in the section on Letters and digits that:

The underscore character _ (U+005F) is considered a lowercase letter.

So now the reason for that seemingly odd exception should make more sense.

Some identifiers are predeclared.

And finally the section ends by telling us that some identifiers are pre-declared. We’ll get to those in due time, but as a sneak peak, this refers to names of basic data types, constants, nil, and a few built-in function names.

Quotes from The Go Programming Language Specification, Version of June 29, 2022

Share this

Related Content

Empty structs

We finally we have enough knowledge for the EBNF format not to seem completely foreign, so let’s jump back and take a look at that, with the examples provided in the spec… Struct types … StructType = "struct" "{" { FieldDecl ";" } "}" . FieldDecl = (IdentifierList Type | EmbeddedField) [ Tag ] . EmbeddedField = [ "*" ] TypeName [ TypeArgs ] . Tag = string_lit . // An empty struct.

Struct tags

Struct types … 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. An empty tag string is equivalent to an absent tag. The tags are made visible through a reflection interface and take part in type identity for structs but are otherwise ignored. struct { x, y float64 "" // an empty tag string is like an absent tag name string "any string is permitted as a tag" _ [4]byte "ceci n'est pas un champ de structure" } // A struct corresponding to a TimeStamp protocol buffer.

Struct method promotion

Yesterday we saw an example of struct field promotion. But methods (which we haven’t really discussed yet) can also be promoted. Struct types … Given a struct type S and a named type T, promoted methods are included in the method set of the struct as follows: If S contains an embedded field T, the method sets of S and *S both include promoted methods with receiver T. The method set of *S also includes promoted methods with receiver *T.