After the source text is read as UTF-8 (see
File structure) it is broken into
tokens: identifiers, keywords, operators and punctuation, and literals (spec: Tokens).
Scanning takes the longest sequence of characters that forms a valid token, so
a+++b is a, ++, +, b.
Characters and white space
newline = /* the Unicode code point U+000A */ .
unicode_char = /* an arbitrary Unicode code point except newline */ .
unicode_letter = /* a Unicode code point categorized as "Letter" */ .
unicode_digit = /* a Unicode code point categorized as "Number, decimal digit" */ .
letter = unicode_letter | "_" .
decimal_digit = "0" … "9" .
binary_digit = "0" | "1" .
octal_digit = "0" … "7" .
hex_digit = "0" … "9" | "A" … "F" | "a" … "f" .
White space is the space (U+0020), horizontal tab (U+0009), carriage return (U+000D) and newline (U+000A). It is ignored except that it separates tokens and that a newline or end of file may trigger a semicolon. Letters are the Unicode categories Lu, Ll, Lt, Lm and Lo. Digits are category Nd. The underscore counts as a lower-case letter.
Comments
| Form | Name | Ends at |
|---|---|---|
// text | Line comment | The end of the line |
/* text */ | General comment | The first */; may span lines |
A comment cannot start inside a rune literal, a string literal or another comment, so general comments do not nest. A general comment that contains no newlines acts like a space. Any other comment acts like a newline, which matters for semicolons.
Comments carry meaning for tools: documentation comments and directives are comments. The language ignores them.
Semicolons
The grammar uses semicolons as terminators, but programs omit most of them (spec: Semicolons). Two rules apply:
- When the input is broken into tokens, a semicolon is inserted immediately after a
line’s final token if that token is one of:
- an identifier;
- an integer, floating-point, imaginary, rune or string literal;
- one of the keywords
break,continue,fallthroughorreturn; - one of the tokens
++,--,),]or}.
- A semicolon may be omitted before a closing
)or}.
Rule 1 is why an opening brace cannot go on its own line. The line before it ends in
), so a semicolon is inserted, and the brace then starts a stray block:
func main() // a semicolon is inserted here: syntax error
{
}
x := []int{
1,
2, // this comma is required: 2 would otherwise end the line
}
s := a +
b // break after an operator; a line ending in a or b would end the statement
A newline or the end of the file triggers insertion, and a general comment containing a newline counts as a newline. A line that ends with a literal or a closing bracket gets a semicolon, which is why the last element of a multi-line composite literal or argument list needs a trailing comma.
Identifiers
identifier = letter { letter | unicode_digit } .
- An identifier is one or more letters and digits; the first must be a letter. Length is not limited.
- Identifiers are case-sensitive and compared by code points, with no Unicode normalisation.
- An identifier is exported if its first character is a Unicode upper-case letter (category Lu) and it is declared in the package block or is a field or method name (spec: Exported identifiers). See Declarations and scope.
_on its own is the blank identifier, which binds nothing.- The predeclared
identifiers such as
int,trueandlenare not keywords. They can be redeclared, though it is rarely a good idea.
a
_x9
ThisVariableIsExported
αβ
Keywords
Go has 25 keywords, which are reserved and cannot be identifiers (spec: Keywords):
| Group | Keywords |
|---|---|
| Declarations | const func import package type var |
| Composite types | chan interface map struct |
| Control flow | break case continue default else fallthrough for goto if range return select switch |
| Goroutines and defer | defer go |
In alphabetical order: break case chan const continue default defer else fallthrough
for func go goto if import interface map package range return select struct switch type
var. Go has no contextual keywords. Words such as true,
nil and any are predeclared identifiers.
Operators and punctuation
+ & += &= && == != ( )
- | -= |= || < <= [ ]
* ^ *= ^= <- > >= { }
/ << /= <<= ++ = := , ;
% >> %= >>= -- ! ... . :
&^ &^= ~
Their meanings and precedence are on the
Expressions page. Some tokens do
several jobs: * is multiplication and pointer indirection, &
is bitwise AND and the address operator, ^ is XOR and bitwise complement,
<- sends and receives, and ... marks variadic parameters and
array lengths in composite literals. ~ (Go 1.18) appears only in type
elements (see Interfaces).
Literals
| Kind | Examples | Default type |
|---|---|---|
| Integer | 42 0x2A 0o52 0b101010 1_000_000 | int |
| Floating-point | 1.5 1e10 .5 0x1p-2 | float64 |
| Imaginary | 3i 2.5i 0x1p-2i | complex128 |
| Rune | 'a' '本' '\n' '\x41' | rune |
| String | "hello\n" and raw strings between back quotes | string |
true, false and nil are predeclared identifiers,
not literals. Numeric literals are untyped constants with exact values of arbitrary
precision (spec: Constants; see
Constants).
Integer literals
int_lit = decimal_lit | binary_lit | octal_lit | hex_lit .
decimal_lit = "0" | ( "1" … "9" ) [ [ "_" ] decimal_digits ] .
binary_lit = "0" ( "b" | "B" ) [ "_" ] binary_digits .
octal_lit = "0" [ "o" | "O" ] [ "_" ] octal_digits .
hex_lit = "0" ( "x" | "X" ) [ "_" ] hex_digits .
decimal_digits = decimal_digit { [ "_" ] decimal_digit } .
binary_digits = binary_digit { [ "_" ] binary_digit } .
octal_digits = octal_digit { [ "_" ] octal_digit } .
hex_digits = hex_digit { [ "_" ] hex_digit } .
| Base | Prefix | Example | Since |
|---|---|---|---|
| Decimal | none | 42 | 1.0 |
| Hexadecimal | 0x or 0X | 0xBadFace | 1.0 |
| Octal | 0, 0o or 0O | 0600, 0o600 | 1.0 (0o: 1.13) |
| Binary | 0b or 0B | 0b1011 | 1.13 |
- A single
0is a decimal zero. A longer literal starting with0and using only digits is octal, so0600is 384. - Underscores (Go 1.13) may appear after a base prefix or between
successive digits, one at a time.
0x_67_7aand4_2are valid._42is an identifier, and42_,4__2and0_xBadFaceare invalid. - The value is exact. Integer constants are held with at least 256 bits, so
170141183460469231731687303715884105727is a valid constant until it is used where a smaller type is required.
Floating-point literals
float_lit = decimal_float_lit | hex_float_lit .
decimal_float_lit = decimal_digits "." [ decimal_digits ] [ decimal_exponent ] |
decimal_digits decimal_exponent |
"." decimal_digits [ decimal_exponent ] .
decimal_exponent = ( "e" | "E" ) [ "+" | "-" ] decimal_digits .
hex_float_lit = "0" ( "x" | "X" ) hex_mantissa hex_exponent .
hex_mantissa = [ "_" ] hex_digits "." [ hex_digits ] |
[ "_" ] hex_digits |
"." hex_digits .
hex_exponent = ( "p" | "P" ) [ "+" | "-" ] decimal_digits .
- Examples:
0.,72.40,072.40(the same as 72.40),1.e+0,6.67428e-11,.25. - Hexadecimal floats (Go 1.13) must have a
pexponent, which scales by a power of two:0x1p-2is 0.25,0x2.p10is 2048.0,0X.8p-0is 0.5. 0x15e-2is not a hexadecimal float. It is the integer subtraction0x15e - 2.0x.p1has no digits and1p-2has no hexadecimal mantissa, so both are invalid.- Underscores follow the integer rules:
1_5.is 15.0, and1_.5,1._5,1.5_e1,1.5e_1and1.5e1_are invalid. - Literals have no suffixes. There are no literals for infinity or NaN.
Imaginary literals
imaginary_lit = (decimal_digits | int_lit | float_lit) "i" .
An integer or floating-point literal followed by i is the imaginary part
of a complex constant. Since Go 1.13 it may be written in any base. For backward
compatibility an integer part made only of decimal digits is decimal even with a leading
0, so 0123i is 123i, while
0o123i is 83i.
Rune literals
A rune literal is one character or one escape in single quotes. It is a constant integer
naming a Unicode code point, not a character type; its default type is
rune, an alias for int32.
rune_lit = "'" ( unicode_value | byte_value ) "'" .
unicode_value = unicode_char | little_u_value | big_u_value | escaped_char .
byte_value = octal_byte_value | hex_byte_value .
octal_byte_value = `\` octal_digit octal_digit octal_digit .
hex_byte_value = `\` "x" hex_digit hex_digit .
little_u_value = `\` "u" hex_digit hex_digit hex_digit hex_digit .
big_u_value = `\` "U" hex_digit hex_digit hex_digit hex_digit
hex_digit hex_digit hex_digit hex_digit .
escaped_char = `\` ( "a" | "b" | "f" | "n" | "r" | "t" | "v" | `\` | "'" | `"` ) .
| Escape | Meaning | In runes | In strings |
|---|---|---|---|
\a | U+0007 alert or bell | Yes | Yes |
\b | U+0008 backspace | Yes | Yes |
\f | U+000C form feed | Yes | Yes |
\n | U+000A line feed | Yes | Yes |
\r | U+000D carriage return | Yes | Yes |
\t | U+0009 horizontal tab | Yes | Yes |
\v | U+000B vertical tab | Yes | Yes |
\\ | U+005C backslash | Yes | Yes |
\' | U+0027 single quote | Yes | No |
\" | U+0022 double quote | No | Yes |
\nnn | Exactly three octal digits, 0 to 255 | Yes | Yes (one byte) |
\xnn | Exactly two hexadecimal digits | Yes | Yes (one byte) |
\unnnn | Exactly four hexadecimal digits, a code point | Yes | Yes (UTF-8) |
\Unnnnnnnn | Exactly eight hexadecimal digits, a code point | Yes | Yes (UTF-8) |
\uand\Umust give a valid code point: not above0x10FFFFand not a surrogate half (excluded since Go 1.1).- A rune literal holds exactly one code point.
'aa'is invalid, and so is a character written as a base letter and combining accent.'\400'is invalid because the value is over 255, and'\k'becausekis not an escape. 'ä'is the code point U+00E4, value0xe4, even though its source text is the two UTF-8 bytes0xc3 0xa4.
String literals
string_lit = raw_string_lit | interpreted_string_lit .
raw_string_lit = "`" { unicode_char | newline } "`" .
interpreted_string_lit = `"` { unicode_value | byte_value } `"` .
| Form | Quotes | Contents |
|---|---|---|
| Raw | Back quotes | Any character but a back quote. No escapes; may span lines. Carriage returns are discarded from the value |
| Interpreted | Double quotes | No newlines or unescaped double quotes. Escapes as for runes, except that \' is illegal and \" is legal |
In an interpreted string, \nnn and \xnn escapes are single
bytes of the result; all other escapes are the UTF-8 encoding of one
character. So \377 and \xFF are the one byte
0xFF, while ÿ, ÿ and \xc3\xbf
are the two bytes 0xc3 0xbf.
"日本語" // UTF-8 input text
`日本語` // UTF-8 input text as a raw literal
"日本語" // the explicit Unicode code points
"\U000065e5\U0000672c\U00008a9e" // the explicit Unicode code points
"\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e" // the explicit UTF-8 bytes
A string value is a sequence of bytes and need not be valid UTF-8. Ranging over a string
decodes it as UTF-8 (see Statements),
and indexing gives bytes. Adjacent string literals are not joined; use +,
which on constants produces a constant.