The Go Programming Language Specification
Version of May 8, 2013
Introduction
This is a reference manual for the Go programming language. For more information and other documents, see http://golang.org.
Go is a general-purpose language designed with systems programming in mind. It is strongly typed and garbage-collected and has explicit support for concurrent programming. Programs are constructed frompackages, whose properties allow efficient management of dependencies. The existing implementations use a traditional compile/link model to generate executable binaries.
The grammar is compact and regular, allowing for easy analysis by automatic tools such as integrated development environments.
Notation
The syntax is specified using Extended Backus-Naur Form (EBNF):
Production = production_name "=" [ Expression ] "." . Expression = Alternative { "|" Alternative } . Alternative = Term { Term } . Term = production_name | token [ "…" token ] | Group | Option | Repetition . Group = "(" Expression ")" . Option = "[" Expression "]" . Repetition = "{" Expression "}" .
Productions are expressions constructed from terms and the following operators, in increasing precedence:
| alternation () grouping [] option (0 or 1 times) {} repetition (0 to n times)
Lower-case production names are used to identify lexical tokens. Non-terminals are in CamelCase. Lexical tokens are enclosed in double quotes ""
or back quotes ``
.
The form a … b
represents the set of characters froma
through b
as alternatives. The horizontal ellipsis …
is also used elsewhere in the spec to informally denote various enumerations or code snippets that are not further specified. The character …
(as opposed to the three characters ...
) is not a token of the Go language.
Source code representation
Source code is Unicode text encoded inUTF-8. The text is not canonicalized, so a single accented code point is distinct from the same character constructed from combining an accent and a letter; those are treated as two code points. For simplicity, this document will use the unqualified term character to refer to a Unicode code point in the source text.
Each code point is distinct; for instance, upper and lower case letters are different characters.
Implementation restriction: For compatibility with other tools, a compiler may disallow the NUL character (U+0000) in the source text.
Implementation restriction: For compatibility with other tools, a compiler may ignore a UTF-8-encoded byte order mark (U+FEFF) if it is the first Unicode code point in the source text. A byte order mark may be disallowed anywhere else in the source.
Characters
The following terms are used to denote specific Unicode character classes:
newline = /* the Unicode code point U+000A */ . unicode_char = /* an arbitrary Unicode code point except newline */ . unicode_letter = /* a Unicode code point classified as "Letter" */ . unicode_digit = /* a Unicode code point classified as "Decimal Digit" */ .
In The Unicode Standard 6.2, Section 4.5 "General Category" defines a set of character categories. Go treats those characters in category Lu, Ll, Lt, Lm, or Lo as Unicode letters, and those in category Nd as Unicode digits.
Letters and digits
The underscore character _
(U+005F) is considered a letter.
letter = unicode_letter | "_" . decimal_digit = "0" … "9" . octal_digit = "0" … "7" . hex_digit = "0" … "9" | "A" … "F" | "a" … "f" .
Lexical elements
Comments
There are two forms of comments:
- Line comments start with the character sequence
//
and stop at the end of the line. A line comment acts like a newline. - General comments start with the character sequence
/*
and continue through the character sequence*/
. A general comment containing one or more newlines acts like a newline, otherwise it acts like a space.
Comments do not nest.
Tokens
Tokens form the vocabulary of the Go language. There are four classes: identifiers, keywords, operators and delimiters, and literals. White space, formed from spaces (U+0020), horizontal tabs (U+0009), carriage returns (U+000D), and newlines (U+000A), is ignored except as it separates tokens that would otherwise combine into a single token. Also, a newline or end of file may trigger the insertion of a semicolon. While breaking the input into tokens, the next token is the longest sequence of characters that form a valid token.
Semicolons
The formal grammar uses semicolons ";"
as terminators in a number of productions. Go programs may omit most of these semicolons using the following two rules:
-
When the input is broken into tokens, a semicolon is automatically inserted into the token stream at the end of a non-blank line if the line's final token is
- an identifier
- an integer, floating-point, imaginary, rune, or string literal
- one of the keywords
break
,continue
,fallthrough
, orreturn
- one of the operators and delimiters
++
,--
,)
,]
, or}
- To allow complex statements to occupy a single line, a semicolon may be omitted before a closing
")"
or"}"
.
To reflect idiomatic use, code examples in this document elide semicolons using these rules.
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 } .
a _x9 ThisVariableIsExported αβ
Some identifiers are predeclared.
Keywords
The following keywords are reserved and may not be used as identifiers.
break default func interface select case defer go map struct chan else goto package switch const fallthrough if range type continue for import return var
Operators and Delimiters
The following character sequences represent operators, delimiters, and other special tokens:
+ & += &= && == != ( ) - | -= |= || < <= [ ] * ^ *= ^= <- > >= { } / << /= <<= ++ = := , ; % >> %= >>= -- ! ... . : &^ &^=
Integer literals
An integer literal is a sequence of digits representing aninteger constant. An optional prefix sets a non-decimal base: 0
for octal, 0x
or0X
for hexadecimal. In hexadecimal literals, lettersa-f
and A-F
represent values 10 through 15.
int_lit = decimal_lit | octal_lit | hex_lit . decimal_lit = ( "1" … "9" ) { decimal_digit } . octal_lit = "0" { octal_digit } . hex_lit = "0" ( "x" | "X" ) hex_digit { hex_digit } .
42 0600 0xBadFace 170141183460469231731687303715884105727
Floating-point literals
A floating-point literal is a decimal representation of afloating-point constant. It has an integer part, a decimal point, a fractional part, and an exponent part. The integer and fractional part comprise decimal digits; the exponent part is an e
or E
followed by an optionally signed decimal exponent. One of the integer part or the fractional part may be elided; one of the decimal point or the exponent may be elided.
float_lit = decimals "." [ decimals ] [ exponent ] | decimals exponent | "." decimals [ exponent ] . decimals = decimal_digit { decimal_digit } . exponent = ( "e" | "E" ) [ "+" | "-" ] decimals .
0. 72.40 072.40 // == 72.40 2.71828 1.e+0 6.67428e-11 1E6 .25 .12345E+5
Imaginary literals
An imaginary literal is a decimal representation of the imaginary part of acomplex constant. It consists of afloating-point literalor decimal integer followed by the lower-case letter i
.
imaginary_lit = (decimals | float_lit) "i" .
0i 011i // == 11i 0.i 2.71828i 1.e+0i 6.67428e-11i 1E6i .25i .12345E+5i
Rune literals
A rune literal represents a rune constant, an integer value identifying a Unicode code point. A rune literal is expressed as one or more characters enclosed in single quotes. Within the quotes, any character may appear except single quote and newline. A single quoted character represents the Unicode value of the character itself, while multi-character sequences beginning with a backslash encode values in various formats.
The simplest form represents the single character within the quotes; since Go source text is Unicode characters encoded in UTF-8, multiple UTF-8-encoded bytes may represent a single integer value. For instance, the literal 'a'
holds a single byte representing a literal a
, Unicode U+0061, value 0x61
, while'ä'
holds two bytes (0xc3
0xa4
) representing a literal a
-dieresis, U+00E4, value 0xe4
.
Several backslash escapes allow arbitrary values to be encoded as ASCII text. There are four ways to represent the integer value as a numeric constant: \x
followed by exactly two hexadecimal digits; \u
followed by exactly four hexadecimal digits;\U
followed by exactly eight hexadecimal digits, and a plain backslash \
followed by exactly three octal digits. In each case the value of the literal is the value represented by the digits in the corresponding base.
Although these representations all result in an integer, they have different valid ranges. Octal escapes must represent a value between 0 and 255 inclusive. Hexadecimal escapes satisfy this condition by construction. The escapes \u
and \U
represent Unicode code points so within them some values are illegal, in particular those above 0x10FFFF
and surrogate halves.
After a backslash, certain single-character escapes represent special values:
\a U+0007 alert or bell \b U+0008 backspace \f U+000C form feed \n U+000A line feed or newline \r U+000D carriage return \t U+0009 horizontal tab \v U+000b vertical tab \\ U+005c backslash \' U+0027 single quote (valid escape only within rune literals) \" U+0022 double quote (valid escape only within string literals)
All other sequences starting with a backslash are illegal inside rune literals.
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" | `\` | "'" | `"` ) .
'a' 'ä' '本' '\t' '\000' '\007' '\377' '\x07' '\xff' '\u12e4' '\U00101234' 'aa' // illegal: too many characters '\xa' // illegal: too few hexadecimal digits '\0' // illegal: too few octal digits '\uDFFF' // illegal: surrogate half '\U00110000' // illegal: invalid Unicode code point
String literals
A string literal represents a string constantobtained 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``
. Within the quotes, any character is legal except back quote. The value of a raw string literal is the string composed of the uninterpreted (implicitly UTF-8-encoded) characters between the quotes; in particular, backslashes have no special meaning and the string may contain newlines. Carriage returns inside raw string literals are discarded from the raw string value.
Interpreted string literals are character sequences between double quotes ""
. The text between the quotes, which may not contain newlines, forms the value of the literal, with backslash escapes interpreted as they are in rune literals (except that \'
is illegal and\"
is legal), with the same restrictions. The three-digit octal (\
nnn) and two-digit hexadecimal (\x
nn) escapes represent individualbytes of the resulting string; all other escapes represent the (possibly multi-byte) UTF-8 encoding of individual characters. Thus inside a string literal \377
and \xFF
represent a single byte of value 0xFF
=255, while ÿ
,\u00FF
, \U000000FF
and \xc3\xbf
represent the two bytes 0xc3
0xbf
of the UTF-8 encoding of character U+00FF.
string_lit = raw_string_lit | interpreted_string_lit . raw_string_lit = "`" { unicode_char | newline } "`" . interpreted_string_lit = `"` { unicode_value | byte_value } `"` .
`abc` // same as "abc" `\n \n` // same as "\\n\n\\n" "\n" "" "Hello, world!\n" "日本語" "\u65e5本\U00008a9e" "\xff\u00FF" "\uD800" // illegal: surrogate half "\U00110000" // illegal: invalid Unicode code point
These examples all represent the same string:
"日本語" // UTF-8 input text `日本語` // UTF-8 input text as a raw literal "\u65e5\u672c\u8a9e" // 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
If the source code represents a character as two code points, such as a combining form involving an accent and a letter, the result will be an error if placed in a rune literal (it is not a single code point), and will appear as two code points if placed in a string literal.
Constants
There are boolean constants,rune constants,integer constants,floating-point constants, complex constants, and string constants. Character, integer, floating-point, and complex constants are collectively called numeric constants.
A constant value is represented by arune,integer,floating-point,imaginary, orstring literal, an identifier denoting a constant, a constant expression, a conversion with a result that is a constant, or the result value of some built-in functions such asunsafe.Sizeof
applied to any value,cap
or len
applied tosome expressions,real
and imag
applied to a complex constant and complex
applied to numeric constants. The boolean truth values are represented by the predeclared constantstrue
and false
. The predeclared identifieriota denotes an integer constant.
In general, complex constants are a form ofconstant expressionand are discussed in that section.
Numeric constants represent values of arbitrary precision and do not overflow.
Constants may be typed or untyped. Literal constants, true
, false
, iota
, and certain constant expressionscontaining only untyped constant operands are untyped.
A constant may be given a type explicitly by a constant declarationor conversion, or implicitly when used in avariable declaration or anassignment or as an operand in an expression. It is an error if the constant value cannot be represented as a value of the respective type. For instance, 3.0
can be given any integer or any floating-point type, while 2147483648.0
(equal to 1<<31
) can be given the types float32
, float64
, or uint32
but not int32
or string
.
There are no constants denoting the IEEE-754 infinity and not-a-number values, but the math
package'sInf,NaN,IsInf, andIsNaNfunctions return and test for those values at run time.
Implementation restriction: Although numeric constants have arbitrary precision in the language, a compiler may implement them using an internal representation with limited precision. That said, every implementation must:
- Represent integer constants with at least 256 bits.
- Represent floating-point constants, including the parts of a complex constant, with a mantissa of at least 256 bits and a signed exponent of at least 32 bits.
- Give an error if unable to represent an integer constant precisely.
- Give an error if unable to represent a floating-point or complex constant due to overflow.
- Round to the nearest representable constant if unable to represent a floating-point or complex constant due to limits on precision.
These requirements apply both to literal constants and to the result of evaluating constant expressions.
Types
A type determines the set of values and operations specific to values of that type. A type may be specified by a (possibly qualified)type name or a type literal, which composes a new type from previously declared types.
Type = TypeName | TypeLit | "(" Type ")" . TypeName = identifier | QualifiedIdent . TypeLit = ArrayType | StructType | PointerType | FunctionType | InterfaceType | SliceType | MapType | ChannelType .
Named instances of the boolean, numeric, and string types arepredeclared.Composite types—array, struct, pointer, function, interface, slice, map, and channel types—may be constructed using type literals.
The static type (or just type) of a variable is the type defined by its declaration. Variables of interface type also have a distinct dynamic type, which is the actual type of the value stored in the variable at run time. The dynamic type may vary during execution but is alwaysassignableto the static type of the interface variable. For non-interface types, the dynamic type is always the static type.
Each type T
has an underlying type: If T
is a predeclared type or a type literal, the corresponding underlying type is T
itself. Otherwise, T
's underlying type is the underlying type of the type to which T
refers in itstype declaration.
type T1 string type T2 T1 type T3 []T1 type T4 T3
The underlying type of string
, T1
, and T2
is string
. The underlying type of []T1
, T3
, and T4
is []T1
.
Method sets
A type may have a method set associated with it (§Interface types, §Method declarations). The method set of an interface type is its interface. The method set of any other type T
consists of all methods with receiver type T
. The method set of the corresponding pointer type *T
is the set of all methods with receiver *T
or T
(that is, it also contains the method set of T
). Further rules apply to structs containing anonymous fields, as described in the section on struct types. Any other type has an empty method set. In a method set, each method must have aunique method name.
The method set of a type determines the interfaces that the type implementsand the methods that can be calledusing a receiver of that type.
Boolean types
A boolean type represents the set of Boolean truth values denoted by the predeclared constants true
and false
. The predeclared boolean type is bool
.
Numeric types
A numeric type represents sets of integer or floating-point values. The predeclared architecture-independent numeric types are:
uint8 the set of all unsigned 8-bit integers (0 to 255) uint16 the set of all unsigned 16-bit integers (0 to 65535) uint32 the set of all unsigned 32-bit integers (0 to 4294967295) uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615) int8 the set of all signed 8-bit integers (-128 to 127) int16 the set of all signed 16-bit integers (-32768 to 32767) int32 the set of all signed 32-bit integers (-2147483648 to 2147483647) int64 the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807) float32 the set of all IEEE-754 32-bit floating-point numbers float64 the set of all IEEE-754 64-bit floating-point numbers complex64 the set of all complex numbers with float32 real and imaginary parts complex128 the set of all complex numbers with float64 real and imaginary parts byte alias for uint8 rune alias for int32
The value of an n-bit integer is n bits wide and represented usingtwo's complement arithmetic.
There is also a set of predeclared numeric types with implementation-specific sizes:
uint either 32 or 64 bits int same size as uint uintptr an unsigned integer large enough to store the uninterpreted bits of a pointer value
To avoid portability issues all numeric types are distinct exceptbyte
, which is an alias for uint8
, andrune
, which is an alias for int32
. Conversions are required when different numeric types are mixed in an expression or assignment. For instance, int32
and int
are not the same type even though they may have the same size on a particular architecture.
String types
A string type represents the set of string values. A string value is a (possibly empty) sequence of bytes. Strings are immutable: once created, it is impossible to change the contents of a string. The predeclared string type is string
.
The length of a string s
(its size in bytes) can be discovered using the built-in function len
. The length is a compile-time constant if the string is a constant. A string's bytes can be accessed by integer indices0 through len(s)-1
. It is illegal to take the address of such an element; ifs[i]
is the i
'th byte of a string, &s[i]
is invalid.
Array types
An array is a numbered sequence of elements of a single type, called the element type. The number of elements is called the length and is never negative.
ArrayType = "[" ArrayLength "]" ElementType . ArrayLength = Expression . ElementType = Type .
The length is part of the array's type; it must evaluate to a non- negative constant representable by a value of type int
. The length of array a
can be discovered using the built-in function len
. The elements can be addressed by integer indices0 through len(a)-1
. Array types are always one-dimensional but may be composed to form multi-dimensional types.
[32]byte [2*N] struct { x, y int32 } [1000]*float64 [3][5]int [2][2][2]float64 // same as [2]([2]([2]float64))
Slice types
A slice is a descriptor for a contiguous segment of an array and provides access to a numbered sequence of elements from that array. A slice type denotes the set of all slices of arrays of its element type. The value of an uninitialized slice is nil
.
SliceType = "[" "]" ElementType .
Like arrays, slices are indexable and have a length. The length of a slice s
can be discovered by the built-in functionlen
; unlike with arrays it may change during execution. The elements can be addressed by integer indices0 through len(s)-1
. The slice index of a given element may be less than the index of the same element in the underlying array.
A slice, once initialized, is always associated with an underlying array that holds its elements. A slice therefore shares storage with its array and with other slices of the same array; by contrast, distinct arrays always represent distinct storage.
The array underlying a slice may extend past the end of the slice. The capacity is a measure of that extent: it is the sum of the length of the slice and the length of the array beyond the slice; a slice of length up to that capacity can be created byslicing a new one from the original slice. The capacity of a slice a
can be discovered using the built-in function cap(a)
.
A new, initialized slice value for a given element type T
is made using the built-in functionmake
, which takes a slice type and parameters specifying the length and optionally the capacity:
make([]T, length) make([]T, length, capacity)
A call to make
allocates a new, hidden array to which the returned slice value refers. That is, executing
make([]T, length, capacity)
produces the same slice as allocating an array and slicing it, so these two examples result in the same slice:
make([]int, 50, 100) new([100]int)[0:50]
Like arrays, slices are always one-dimensional but may be composed to construct higher-dimensional objects. With arrays of arrays, the inner arrays are, by construction, always the same length; however with slices of slices (or arrays of slices), the lengths may vary dynamically. Moreover, the inner slices must be allocated individually (with make
).
Struct types
A struct is a sequence of named elements, called fields, each of which has a name and a type. Field names may be specified explicitly (IdentifierList) or implicitly (AnonymousField). Within a struct, non-blank field names must be unique.
StructType = "struct" "{" { FieldDecl ";" } "}" . FieldDecl = (IdentifierList Type | AnonymousField) [ Tag ] . AnonymousField = [ "*" ] TypeName . Tag = string_lit .
// An empty struct. struct {} // A struct with 6 fields. struct { x, y int u float32 _ float32 // padding A *[]int F func() }
A field declared with a type but no explicit field name is an anonymous field, also called an embedded field or an embedding of the type in the struct. An embedded type must be specified as a type name T
or as a pointer to a non-interface type name *T
, and T
itself may not be a pointer type. The unqualified type name acts as the field name.
// A struct with four anonymous fields of type T1, *T2, P.T3 and *P.T4 struct { T1 // field name is T1 *T2 // field name is T2 P.T3 // field name is T3 *P.T4 // field name is T4 x, y int // field names are x and y }
The following declaration is illegal because field names must be unique in a struct type:
struct { T // conflicts with anonymous field *T and *P.T *T // conflicts with anonymous field T and *P.T *P.T // conflicts with anonymous field T and *T }
A field or method f
of an anonymous field in a struct x
is called promoted ifx.f
is a legal selector that denotes that field or method f
.
Promoted fields act like ordinary fields of a struct except that they cannot be used as field names incomposite literals of the struct.
Given a struct type S
and a type named T
, promoted methods are included in the method set of the struct as follows:
- If
S
contains an anonymous fieldT
, the method sets ofS
and*S
both include promoted methods with receiverT
. The method set of*S
also includes promoted methods with receiver*T
. - If
S
contains an anonymous field*T
, the method sets ofS
and*S
both include promoted methods with receiverT
or*T
.
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 interfacebut 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" }
Pointer types
A pointer type denotes the set of all pointers to variables of a given type, called the base type of the pointer. The value of an uninitialized pointer is nil
.
PointerType = "*" BaseType . BaseType = Type .
*Point *[4]int
Function types
A function type denotes the set of all functions with the same parameter and result types. The value of an uninitialized variable of function type is nil
.
FunctionType = "func" Signature . Signature = Parameters [ Result ] . Result = Parameters | Type . Parameters = "(" [ ParameterList [ "," ] ] ")" . ParameterList = ParameterDecl { "," ParameterDecl } . ParameterDecl = [ IdentifierList ] [ "..." ] Type .
Within a list of parameters or results, the names (IdentifierList) must either all be present or all be absent. If present, each name stands for one item (parameter or result) of the specified type and all non-blank names in the signature must be unique. If absent, each type stands for one item of that type. Parameter and result lists are always parenthesized except that if there is exactly one unnamed result it may be written as an unparenthesized type.
The final parameter in a function signature may have a type prefixed with ...
. A function with such a parameter is called variadic and may be invoked with zero or more arguments for that parameter.
func() func(x int) int func(a, _ int, z float32) bool func(a, b int, z float32) (bool) func(prefix string, values ...int) func(a, b int, z float64, opt ...interface{}) (success bool) func(int, int, float64) (float64, *[]int) func(n int) func(p *T)
Interface types
An interface type specifies a method set called its interface. A variable of interface type can store a value of any type with a method set that is any superset of the interface. Such a type is said toimplement the interface. The value of an uninitialized variable of interface type is nil
.
InterfaceType = "interface" "{" { MethodSpec ";" } "}" . MethodSpec = MethodName Signature | InterfaceTypeName . MethodName = identifier . InterfaceTypeName = TypeName .
As with all method sets, in an interface type, each method must have aunique name.
// A simple File interface interface { Read(b Buffer) bool Write(b Buffer) bool Close() }
More than one type may implement an interface. For instance, if two types S1
and S2
have the method set
func (p T) Read(b Buffer) bool { return … } func (p T) Write(b Buffer) bool { return … } func (p T) Close() { … }
(where T
stands for either S1
or S2
) then the File
interface is implemented by both S1
andS2
, regardless of what other methodsS1
and S2
may have or share.
A type implements any interface comprising any subset of its methods and may therefore implement several distinct interfaces. For instance, all types implement the empty interface:
interface{}
Similarly, consider this interface specification, which appears within a type declarationto define an interface called Lock
:
type Lock interface { Lock() Unlock() }
If S1
and S2
also implement
func (p T) Lock() { … } func (p T) Unlock() { … }
they implement the Lock
interface as well as the File
interface.
An interface may use an interface type name T
in place of a method specification. The effect, called embedding an interface, is equivalent to enumerating the methods of T
explicitly in the interface.
type ReadWrite interface { Read(b Buffer) bool Write(b Buffer) bool } type File interface { ReadWrite // same as enumerating the methods in ReadWrite Lock // same as enumerating the methods in Lock Close() }
An interface type T
may not embed itself or any interface type that embeds T
, recursively.
// illegal: Bad cannot embed itself type Bad interface { Bad } // illegal: Bad1 cannot embed itself using Bad2 type Bad1 interface { Bad2 } type Bad2 interface { Bad1 }
Map types
A map is an unordered group of elements of one type, called the element type, indexed by a set of unique keys of another type, called the key type. The value of an uninitialized map is nil
.
MapType = "map" "[" KeyType "]" ElementType . KeyType = Type .
The comparison operators==
and !=
must be fully defined for operands of the key type; thus the key type must not be a function, map, or slice. If the key type is an interface type, these comparison operators must be defined for the dynamic key values; failure will cause a run-time panic.
map[string]int map[*T]struct{ x, y float64 } map[string]interface{}
The number of map elements is called its length. For a map m
, it can be discovered using the built-in function len
and may change during execution. Elements may be added during execution using assignments and retrieved withindex expressions; they may be removed with thedelete
built-in function.
A new, empty map value is made using the built-in function make
, which takes the map type and an optional capacity hint as arguments:
make(map[string]int) make(map[string]int, 100)
The initial capacity does not bound its size: maps grow to accommodate the number of items stored in them, with the exception of nil
maps. A nil
map is equivalent to an empty map except that no elements may be added.
Channel types
A channel provides a mechanism for two concurrently executing functions to synchronize execution and communicate by passing a value of a specified element type. The value of an uninitialized channel is nil
.
ChannelType = ( "chan" [ "<-" ] | "<-" "chan" ) ElementType .
The <-
operator specifies the channel direction,send or receive. If no direction is given, the channel isbi-directional. A channel may be constrained only to send or only to receive byconversion or assignment.
chan T // can be used to send and receive values of type T chan<- float64 // can only be used to send float64s <-chan int // can only be used to receive ints
The <-
operator associates with the leftmost chan
possible:
chan<- chan int // same as chan<- (chan int) chan<- <-chan int // same as chan<- (<-chan int) <-chan <-chan int // same as <-chan (<-chan int) chan (<-chan int)
A new, initialized channel value can be made using the built-in functionmake
, which takes the channel type and an optional capacity as arguments:
make(chan int, 100)
The capacity, in number of elements, sets the size of the buffer in the channel. If the capacity is greater than zero, the channel is asynchronous: communication operations succeed without blocking if the buffer is not full (sends) or not empty (receives), and elements are received in the order they are sent. If the capacity is zero or absent, the communication succeeds only when both a sender and receiver are ready. A nil
channel is never ready for communication.
A channel may be closed with the built-in functionclose
; the multi-valued assignment form of thereceive operatortests whether a channel has been closed.
Properties of types and values
Type identity
Two types are either identical or different.
Two named types are identical if their type names originate in the sameTypeSpec. A named and an unnamed type are always different. Two unnamed types are identical if the corresponding type literals are identical, that is, if they have the same literal structure and corresponding components have identical types. In detail:
- Two array types are identical if they have identical element types and the same array length.
- Two slice types are identical if they have identical element types.
- Two struct types are identical if they have the same sequence of fields, and if corresponding fields have the same names, and identical types, and identical tags. Two anonymous fields are considered to have the same name. Lower-case field names from different packages are always different.
- Two pointer types are identical if they have identical base types.
- Two function types are identical if they have the same number of parameters and result values, corresponding parameter and result types are identical, and either both functions are variadic or neither is. Parameter and result names are not required to match.
- Two interface types are identical if they have the same set of methods with the same names and identical function types. Lower-case method names from different packages are always different. The order of the methods is irrelevant.
- Two map types are identical if they have identical key and value types.
- Two channel types are identical if they have identical value types and the same direction.
Given the declarations
type ( T0 []string T1 []string T2 struct{ a, b int } T3 struct{ a, c int } T4 func(int, float64) *T0 T5 func(x int, y float64) *[]string )
these types are identical:
T0 and T0 []int and []int struct{ a, b *T5 } and struct{ a, b *T5 } func(x int, y float64) *[]string and func(int, float64) (result *[]string)
T0
and T1
are different because they are named types with distinct declarations; func(int, float64) *T0
andfunc(x int, y float64) *[]string
are different because T0
is different from []string
.
Assignability
A value x
is assignable to a variable of type T
("x
is assignable to T
") in any of these cases:
x
's type is identical toT
.x
's typeV
andT
have identicalunderlying types and at least one ofV
orT
is not a named type.T
is an interface type andx
implementsT
.x
is a bidirectional channel value,T
is a channel type,x
's typeV
andT
have identical element types, and at least one ofV
orT
is not a named type.x
is the predeclared identifiernil
andT
is a pointer, function, slice, map, channel, or interface type.x
is an untyped constant representable by a value of typeT
.
Any value may be assigned to the blank identifier.
Blocks
A block is a possibly empty sequence of declarations and statements within matching brace brackets.
Block = "{" StatementList "}" . StatementList = { Statement ";" } .
In addition to explicit blocks in the source code, there are implicit blocks:
- The universe block encompasses all Go source text.
- Each package has a package block containing all Go source text for that package.
- Each file has a file block containing all Go source text in that file.
- Each "if", "for", and "switch" statement is considered to be in its own implicit block.
- Each clause in a "switch" or "select" statement acts as an implicit block.
Blocks nest and influence scoping.
Declarations and scope
A declaration binds a non-blankidentifier to a constant, type, variable, function, or package. Every identifier in a program must be declared. No identifier may be declared twice in the same block, and no identifier may be declared in both the file and package block.
Declaration = ConstDecl | TypeDecl | VarDecl . TopLevelDecl = Declaration | FunctionDecl | MethodDecl .
The scope of a declared identifier is the extent of source text in which the identifier denotes the specified constant, type, variable, function, or package.
Go is lexically scoped using blocks:
- The scope of a predeclared identifier is the universe block.
- The scope of an identifier denoting a constant, type, variable, or function (but not method) declared at top level (outside any function) is the package block.
- The scope of the package name of an imported package is the file block of the file containing the import declaration.
- The scope of an identifier denoting a method receiver, function parameter, or result variable is the function body.
- The scope of a constant or variable identifier declared inside a function begins at the end of the ConstSpec or VarSpec (ShortVarDecl for short variable declarations) and ends at the end of the innermost containing block.
- The scope of a type identifier declared inside a function begins at the identifier in the TypeSpec and ends at the end of the innermost containing block.
An identifier declared in a block may be redeclared in an inner block. While the identifier of the inner declaration is in scope, it denotes the entity declared by the inner declaration.
The package clause is not a declaration; the package name does not appear in any scope. Its purpose is to identify the files belonging to the same package and to specify the default package name for import declarations.
Label scopes
Labels are declared by labeled statements and are used in the "break","continue", and"goto" statements. It is illegal to define a label that is never used. In contrast to other identifiers, labels are not block scoped and do not conflict with identifiers that are not labels. The scope of a label is the body of the function in which it is declared and excludes the body of any nested function.
Blank identifier
The blank identifier, represented by the underscore character _
, may be used in a declaration like any other identifier but the declaration does not introduce a new binding.
Predeclared identifiers
The following identifiers are implicitly declared in theuniverse block:
Types: bool byte complex64 complex128 error float32 float64 int int8 int16 int32 int64 rune string uint uint8 uint16 uint32 uint64 uintptr Constants: true false iota Zero value: nil Functions: append cap close complex copy delete imag len make new panic print println real recover
Exported identifiers
An identifier may be exported to permit access to it from another package. An identifier is exported if both:
- the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu"); and
- the identifier is declared in the package block or it is a field name or method name.
All other identifiers are not exported.
Uniqueness of identifiers
Given a set of identifiers, an identifier is called unique if it isdifferent from every other in the set. Two identifiers are different if they are spelled differently, or if they appear in different packages and are notexported. Otherwise, they are the same.
Constant declarations
A constant declaration binds a list of identifiers (the names of the constants) to the values of a list of constant expressions. The number of identifiers must be equal to the number of expressions, and the nth identifier on the left is bound to the value of the nth expression on the right.
ConstDecl = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) . ConstSpec = IdentifierList [ [ Type ] "=" ExpressionList ] . IdentifierList = identifier { "," identifier } . ExpressionList = Expression { "," Expression } .
If the type is present, all constants take the type specified, and the expressions must be assignable to that type. If the type is omitted, the constants take the individual types of the corresponding expressions. If the expression values are untyped constants, the declared constants remain untyped and the constant identifiers denote the constant values. For instance, if the expression is a floating-point literal, the constant identifier denotes a floating-point constant, even if the literal's fractional part is zero.
const Pi float64 = 3.14159265358979323846 const zero = 0.0 // untyped floating-point constant const ( size int64 = 1024 eof = -1 // untyped integer constant ) const a, b, c = 3, 4, "foo" // a = 3, b = 4, c = "foo", untyped integer and string constants const u, v float32 = 0, 3 // u = 0.0, v = 3.0
Within a parenthesized const
declaration list the expression list may be omitted from any but the first declaration. Such an empty list is equivalent to the textual substitution of the first preceding non-empty expression list and its type if any. Omitting the list of expressions is therefore equivalent to repeating the previous list. The number of identifiers must be equal to the number of expressions in the previous list. Together with the iota
constant generatorthis mechanism permits light-weight declaration of sequential values:
const ( Sunday = iota Monday Tuesday Wednesday Thursday Friday Partyday numberOfDays // this constant is not exported )
Iota
Within a constant declaration, the predeclared identifieriota
represents successive untyped integer constants. It is reset to 0 whenever the reserved word const
appears in the source and increments after each ConstSpec. It can be used to construct a set of related constants:
const ( // iota is reset to 0 c0 = iota // c0 == 0 c1 = iota // c1 == 1 c2 = iota // c2 == 2 ) const ( a = 1 << iota // a == 1 (iota has been reset) b = 1 << iota // b == 2 c = 1 << iota // c == 4 ) const ( u = iota * 42 // u == 0 (untyped integer constant) v float64 = iota * 42 // v == 42.0 (float64 constant) w = iota * 42 // w == 84 (untyped integer constant) ) const x = iota // x == 0 (iota has been reset) const y = iota // y == 0 (iota has been reset)
Within an ExpressionList, the value of each iota
is the same because it is only incremented after each ConstSpec:
const ( bit0, mask0 = 1 << iota, 1<<iota - 1 // bit0 == 1, mask0 == 0 bit1, mask1 // bit1 == 2, mask1 == 1 _, _ // skips iota == 2 bit3, mask3 // bit3 == 8, mask3 == 7 )
This last example exploits the implicit repetition of the last non-empty expression list.
Type declarations
A type declaration binds an identifier, the type name, to a new type that has the same underlying type as an existing type. The new type is different from the existing type.
TypeDecl = "type" ( TypeSpec | "(" { TypeSpec ";" } ")" ) . TypeSpec = identifier Type .
type IntArray [16]int type ( Point struct{ x, y float64 } Polar Point ) type TreeNode struct { left, right *TreeNode value *Comparable } type Block interface { BlockSize() int Encrypt(src, dst []byte) Decrypt(src, dst []byte) }
The declared type does not inherit any methodsbound to the existing type, but the method setof an interface type or of elements of a composite type remains unchanged:
// A Mutex is a data type with two methods, Lock and Unlock. type Mutex struct { /* Mutex fields */ } func (m *Mutex) Lock() { /* Lock implementation */ } func (m *Mutex) Unlock() { /* Unlock implementation */ } // NewMutex has the same composition as Mutex but its method set is empty. type NewMutex Mutex // The method set of the base type of PtrMutex remains unchanged, // but the method set of PtrMutex is empty. type PtrMutex *Mutex // The method set of *PrintableMutex contains the methods // Lock and Unlock bound to its anonymous field Mutex. type PrintableMutex struct { Mutex } // MyBlock is an interface type that has the same method set as Block. type MyBlock Block
A type declaration may be used to define a different boolean, numeric, or string type and attach methods to it:
type TimeZone int const ( EST TimeZone = -(5 + iota) CST MST PST ) func (tz TimeZone) String() string { return fmt.Sprintf("GMT+%dh", tz) }
Variable declarations
A variable declaration creates a variable, binds an identifier to it and gives it a type and optionally an initial value.
VarDecl = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) . VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .
var i int var U, V, W float64 var k = 0 var x, y float32 = -1, -2 var ( i int u, v, s = 2.0, 3.0, "bar" ) var re, im = complexSqrt(-1) var _, found = entries[name] // map lookup; only interested in "found"
If a list of expressions is given, the variables are initialized by assigning the expressions to the variables in order; all expressions must be consumed and all variables initialized from them. Otherwise, each variable is initialized to its zero value.
If the type is present, each variable is given that type. Otherwise, the types are deduced from the assignment of the expression list.
If the type is absent and the corresponding expression evaluates to an untyped constant, the type of the declared variable is as described in §Assignments.
Implementation restriction: A compiler may make it illegal to declare a variable inside a function body if the variable is never used.
Short variable declarations
A short variable declaration uses the syntax:
ShortVarDecl = IdentifierList ":=" ExpressionList .
It is a shorthand for a regular variable declarationwith initializer expressions but no types:
"var" IdentifierList = ExpressionList .
i, j := 0, 10 f := func() int { return 7 } ch := make(chan int) r, w := os.Pipe(fd) // os.Pipe() returns two values _, y, _ := coord(p) // coord() returns three values; only interested in y coordinate
Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block with the same type, and at least one of the non-blank variables is new. As a consequence, redeclaration can only appear in a multi-variable short declaration. Redeclaration does not introduce a new variable; it just assigns a new value to the original.
field1, offset := nextField(str, 0) field2, offset := nextField(str, offset) // redeclares offset a, a := 1, 2 // illegal: double declaration of a or no new variable if a was declared elsewhere
Short variable declarations may appear only inside functions. In some contexts such as the initializers for"if","for", or"switch" statements, they can be used to declare local temporary variables.
Function declarations
A function declaration binds an identifier, the function name, to a function.
FunctionDecl = "func" FunctionName ( Function | Signature ) . FunctionName = identifier . Function = Signature FunctionBody . FunctionBody = Block .
If the function's signature declares result parameters, the function body's statement list must end in a terminating statement.
func findMarker(c <-chan int) int { for i := range c { if x := <-c; isMarker(x) { return x } } // invalid: missing return statement. }
A function declaration may omit the body. Such a declaration provides the signature for a function implemented outside Go, such as an assembly routine.
func min(x int, y int) int { if x < y { return x } return y } func flushICache(begin, end uintptr) // implemented externally
Method declarations
A method is a function with a receiver. A method declaration binds an identifier, the method name, to a method, and associates the method with the receiver's base type.
MethodDecl = "func" Receiver MethodName ( Function | Signature ) . Receiver = "(" [ identifier ] [ "*" ] BaseTypeName ")" . BaseTypeName = identifier .
The receiver type must be of the form T
or *T
whereT
is a type name. The type denoted by T
is called the receiver base type; it must not be a pointer or interface type and it must be declared in the same package as the method. The method is said to be bound to the base type and the method name is visible only within selectors for that type.
A non-blank receiver identifier must beunique in the method signature. If the receiver's value is not referenced inside the body of the method, its identifier may be omitted in the declaration. The same applies in general to parameters of functions and methods.
For a base type, the non-blank names of methods bound to it must be unique. If the base type is a struct type, the non-blank method and field names must be distinct.
Given type Point
, the declarations
func (p *Point) Length() float64 { return math.Sqrt(p.x * p.x + p.y * p.y) } func (p *Point) Scale(factor float64) { p.x *= factor p.y *= factor }
bind the methods Length
and Scale
, with receiver type *Point
, to the base type Point
.
The type of a method is the type of a function with the receiver as first argument. For instance, the method Scale
has type
func(p *Point, factor float64)
However, a function declared this way is not a method.
Expressions
An expression specifies the computation of a value by applying operators and functions to operands.
Operands
Operands denote the elementary values in an expression. An operand may be a literal, a (possibly qualified) identifier denoting aconstant,variable, orfunction, a method expression yielding a function, or a parenthesized expression.
Operand = Literal | OperandName | MethodExpr | "(" Expression ")" . Literal = BasicLit | CompositeLit | FunctionLit . BasicLit = int_lit | float_lit | imaginary_lit | rune_lit | string_lit . OperandName = identifier | QualifiedIdent.
Qualified identifiers
A qualified identifier is an identifier qualified with a package name prefix. Both the package name and the identifier must not beblank.
QualifiedIdent = PackageName "." identifier .
A qualified identifier accesses an identifier in a different package, which must be imported. The identifier must be exported and declared in the package block of that package.
math.Sin // denotes the Sin function in package math
Composite literals
Composite literals construct values for structs, arrays, slices, and maps and create a new value each time they are evaluated. They consist of the type of the value followed by a brace-bound list of composite elements. An element may be a single expression or a key-value pair.
CompositeLit = LiteralType LiteralValue . LiteralType = StructType | ArrayType | "[" "..." "]" ElementType | SliceType | MapType | TypeName . LiteralValue = "{" [ ElementList [ "," ] ] "}" . ElementList = Element { "," Element } . Element = [ Key ":" ] Value . Key = FieldName | ElementIndex . FieldName = identifier . ElementIndex = Expression . Value = Expression | LiteralValue .
The LiteralType must be a struct, array, slice, or map type (the grammar enforces this constraint except when the type is given as a TypeName). The types of the expressions must be assignableto the respective field, element, and key types of the LiteralType; there is no additional conversion. The key is interpreted as a field name for struct literals, an index for array and slice literals, and a key for map literals. For map literals, all elements must have a key. It is an error to specify multiple elements with the same field name or constant key value.
For struct literals the following rules apply:
- A key must be a field name declared in the LiteralType.
- An element list that does not contain any keys must list an element for each struct field in the order in which the fields are declared.
- If any element has a key, every element must have a key.
- An element list that contains keys does not need to have an element for each struct field. Omitted fields get the zero value for that field.
- A literal may omit the element list; such a literal evaluates to the zero value for its type.
- It is an error to specify an element for a non-exported field of a struct belonging to a different package.
Given the declarations
type Point3D struct { x, y, z float64 } type Line struct { p, q Point3D }
one may write
origin := Point3D{} // zero value for Point3D line := Line{origin, Point3D{y: -4, z: 12.3}} // zero value for line.q.x
For array and slice literals the following rules apply:
- Each element has an associated integer index marking its position in the array.
- An element with a key uses the key as its index; the key must be a constant integer expression.
- An element without a key uses the previous element's index plus one. If the first element has no key, its index is zero.
Taking the address of a composite literal generates a pointer to a unique instance of the literal's value.
var pointer *Point3D = &Point3D{y: 1000}
The length of an array literal is the length specified in the LiteralType. If fewer elements than the length are provided in the literal, the missing elements are set to the zero value for the array element type. It is an error to provide elements with index values outside the index range of the array. The notation ...
specifies an array length equal to the maximum element index plus one.
buffer := [10]string{} // len(buffer) == 10 intSet := [6]int{1, 2, 3, 5} // len(intSet) == 6 days := [...]string{"Sat", "Sun"} // len(days) == 2
A slice literal describes the entire underlying array literal. Thus, the length and capacity of a slice literal are the maximum element index plus one. A slice literal has the form
[]T{x1, x2, … xn}
and is a shortcut for a slice operation applied to an array:
tmp := [n]T{x1, x2, … xn} tmp[0 : n]
Within a composite literal of array, slice, or map type T
, elements that are themselves composite literals may elide the respective literal type if it is identical to the element type of T
. Similarly, elements that are addresses of composite literals may elide the &T
when the element type is *T
.
[...]Point{{1.5, -3.5}, {0, 0}} // same as [...]Point{Point{1.5, -3.5}, Point{0, 0}} [][]int{{1, 2, 3}, {4, 5}} // same as [][]int{[]int{1, 2, 3}, []int{4, 5}} [...]*Point{{1.5, -3.5}, {0, 0}} // same as [...]*Point{&Point{1.5, -3.5}, &Point{0, 0}}
A parsing ambiguity arises when a composite literal using the TypeName form of the LiteralType appears between thekeyword and the opening brace of the block of an "if", "for", or "switch" statement, because the braces surrounding the expressions in the literal are confused with those introducing the block of statements. To resolve the ambiguity in this rare case, the composite literal must appear within parentheses.
if x == (T{a,b,c}[i]) { … } if (x == T{a,b,c}[i]) { … }
Examples of valid array, slice, and map literals:
// list of prime numbers primes := []int{2, 3, 5, 7, 9, 2147483647} // vowels[ch] is true if ch is a vowel vowels := [128]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true, 'y': true} // the array [10]float32{-1, 0, 0, 0, -0.1, -0.1, 0, 0, 0, -1} filter := [10]float32{-1, 4: -0.1, -0.1, 9: -1} // frequencies in Hz for equal-tempered scale (A4 = 440Hz) noteFrequency := map[string]float32{ "C0": 16.35, "D0": 18.35, "E0": 20.60, "F0": 21.83, "G0": 24.50, "A0": 27.50, "B0": 30.87, }
Function literals
A function literal represents an anonymous function.
FunctionLit = "func" Function .
func(a, b int, z float64) bool { return a*b < int(z) }
A function literal can be assigned to a variable or invoked directly.
f := func(x, y int) int { return x + y } func(ch chan int) { ch <- ACK }(replyChan)
Function literals are closures: they may refer to variables defined in a surrounding function. Those variables are then shared between the surrounding function and the function literal, and they survive as long as they are accessible.
Primary expressions
Primary expressions are the operands for unary and binary expressions.
PrimaryExpr = Operand | Conversion | BuiltinCall | PrimaryExpr Selector | PrimaryExpr Index | PrimaryExpr Slice | PrimaryExpr TypeAssertion | PrimaryExpr Call . Selector = "." identifier . Index = "[" Expression "]" . Slice = "[" [ Expression ] ":" [ Expression ] "]" . TypeAssertion = "." "(" Type ")" . Call = "(" [ ArgumentList [ "," ] ] ")" . ArgumentList = ExpressionList [ "..." ] .
x 2 (s + ".txt") f(3.1415, true) Point{1, 2} m["foo"] s[i : j + 1] obj.color f.p[i].x()
Selectors
For a primary expression x
that is not a package name, theselector expression
x.f
denotes the field or method f
of the value x
(or sometimes *x
; see below). The identifier f
is called the (field or method) selector; it must not be the blank identifier. The type of the selector expression is the type of f
. If x
is a package name, see the section onqualified identifiers.
A selector f
may denote a field or method f
of a type T
, or it may refer to a field or method f
of a nestedanonymous field of T
. The number of anonymous fields traversed to reach f
is called its depth in T
. The depth of a field or method f
declared in T
is zero. The depth of a field or method f
declared in an anonymous field A
in T
is the depth of f
in A
plus one.
The following rules apply to selectors:
- For a value
x
of typeT
or*T
whereT
is not an interface type,x.f
denotes the field or method at the shallowest depth inT
where there is such anf
. If there is not exactly onef
with shallowest depth, the selector expression is illegal. - For a variable
x
of typeI
whereI
is an interface type,x.f
denotes the actual method with namef
of the value assigned tox
. If there is no method with namef
in themethod set ofI
, the selector expression is illegal. - In all other cases,
x.f
is illegal. - If
x
is of pointer type and has the valuenil
andx.f
denotes a struct field, assigning to or evaluatingx.f
causes a run-time panic. - If
x
is of interface type and has the valuenil
, calling orevaluating the methodx.f
causes a run-time panic.
Selectors automatically dereferencepointers to structs. If x
is a pointer to a struct, x.y
is shorthand for (*x).y
; if the field y
is also a pointer to a struct, x.y.z
is shorthand for (*(*x).y).z
, and so on. If x
contains an anonymous field of type *A
, where A
is also a struct type,x.f
is a shortcut for (*x.A).f
.
For example, given the declarations:
type T0 struct { x int } func (recv *T0) M0() type T1 struct { y int } func (recv T1) M1() type T2 struct { z int T1 *T0 } func (recv *T2) M2() var p *T2 // with p != nil and p.T0 != nil
one may write:
p.z // (*p).z p.y // ((*p).T1).y p.x // (*(*p).T0).x p.M2() // (*p).M2() p.M1() // ((*p).T1).M1() p.M0() // ((*p).T0).M0()
- A call to the built-in function
panic
. - A block in which the statement list ends in a terminating statement.
- An "if" statement in which:
- the "else" branch is present, and
- both branches are terminating statements.
- A "for" statement in which:
- there are no "break" statements referring to the "for" statement, and
- the loop condition is absent.
- A "switch" statement in which:
- there are no "break" statements referring to the "switch" statement,
- there is a default case, and
- the statement lists in each case, including the default, end in a terminating statement, or a possibly labeled "fallthrough" statement.
- A "select" statement in which:
- there are no "break" statements referring to the "select" statement, and
- the statement lists in each case, including the default if present, end in a terminating statement.
- A labeled statement labeling a terminating statement.
All other statements are not terminating.
A statement list ends in a terminating statement if the list is not empty and its final statement is terminating.
Empty statements
The empty statement does nothing.
EmptyStmt = .
Labeled statements
A labeled statement may be the target of a
goto
,break
orcontinue
statement.LabeledStmt = Label ":" Statement . Label = identifier .
Error: log.Panic("error encountered")
Expression statements
With the exception of specific built-in functions, function and method calls andreceive operationscan appear in statement context. Such statements may be parenthesized.
ExpressionStmt = Expression .
The following built-in functions are not permitted in statement context:
append cap complex imag len make new real unsafe.Alignof unsafe.Offsetof unsafe.Sizeof
h(x+y) f.Close() <-ch (<-ch) len("foo") // illegal if len is the built-in function
Send statements
A send statement sends a value on a channel. The channel expression must be of channel type, the channel direction must permit send operations, and the type of the value to be sent must be assignableto the channel's element type.
SendStmt = Channel "<-" Expression . Channel = Expression .
Both the channel and the value expression are evaluated before communication begins. Communication blocks until the send can proceed. A send on an unbuffered channel can proceed if a receiver is ready. A send on a buffered channel can proceed if there is room in the buffer. A send on a closed channel proceeds by causing a run-time panic. A send on a
nil
channel blocks forever.ch <- 3
IncDec statements
The "++" and "--" statements increment or decrement their operands by the untyped constant
1
. As with an assignment, the operand must be addressableor a map index expression.IncDecStmt = Expression ( "++" | "--" ) .
The following assignment statements are semantically equivalent:
IncDec statement Assignment x++ x += 1 x-- x -= 1
Assignments
Assignment = ExpressionList assign_op ExpressionList . assign_op = [ add_op | mul_op ] "=" .
Each left-hand side operand must be addressable, a map index expression, or the blank identifier. Operands may be parenthesized.
x = 1 *p = f() a[i] = 23 (k) = <-ch // same as: k = <-ch
An assignment operation
x
op=
y
where op is a binary arithmetic operation is equivalent tox
=
x
opy
but evaluatesx
only once. The op=
construct is a single token. In assignment operations, both the left- and right-hand expression lists must contain exactly one single-valued expression.a[i] <<= 2 i &^= 1<<n
A tuple assignment assigns the individual elements of a multi-valued operation to a list of variables. There are two forms. In the first, the right hand operand is a single multi-valued expression such as a function evaluation or channel ormap operation or a type assertion. The number of operands on the left hand side must match the number of values. For instance, if
f
is a function returning two values,x, y = f()
assigns the first value to
x
and the second toy
. The blank identifier provides a way to ignore values returned by a multi-valued expression:x, _ = f() // ignore second value returned by f()
In the second form, the number of operands on the left must equal the number of expressions on the right, each of which must be single-valued, and thenth expression on the right is assigned to the nth operand on the left.
The assignment proceeds in two phases. First, the operands of index expressionsand pointer indirections(including implicit pointer indirections in selectors) on the left and the expressions on the right are allevaluated in the usual order. Second, the assignments are carried out in left-to-right order.
a, b = b, a // exchange a and b x := []int{1, 2, 3} i := 0 i, x[i] = 1, 2 // set i = 1, x[0] = 2 i = 0 x[i], i = 2, 1 // set x[0] = 2, i = 1 x[0], x[0] = 1, 2 // set x[0] = 1, then x[0] = 2 (so x[0] == 2 at end) x[1], x[3] = 4, 5 // set x[1] = 4, then panic setting x[3] = 5. type Point struct { x, y int } var p *Point x[2], p.x = 6, 7 // set x[2] = 6, then panic setting p.x = 7 i = 2 x = []int{3, 5, 7} for i, x[i] = range x { // set i, x[2] = 0, x[0] break } // after this loop, i == 0 and x == []int{3, 5, 3}
In assignments, each value must beassignable to the type of the operand to which it is assigned. If an untyped constantis assigned to a variable of interface type, the constant is convertedto type
bool
,rune
,int
,float64
,complex128
orstring
respectively, depending on whether the value is a boolean, rune, integer, floating-point, complex, or string constant.If statements
"If" statements specify the conditional execution of two branches according to the value of a boolean expression. If the expression evaluates to true, the "if" branch is executed, otherwise, if present, the "else" branch is executed.
IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" ( IfStmt | Block ) ] .
if x > max { x = max }
The expression may be preceded by a simple statement, which executes before the expression is evaluated.
if x := f(); x < y { return x } else if x > z { return z } else { return y }
Switch statements
"Switch" statements provide multi-way execution. An expression or type specifier is compared to the "cases" inside the "switch" to determine which branch to execute.
SwitchStmt = ExprSwitchStmt | TypeSwitchStmt .
There are two forms: expression switches and type switches. In an expression switch, the cases contain expressions that are compared against the value of the switch expression. In a type switch, the cases contain types that are compared against the type of a specially annotated switch expression.
Expression switches
In an expression switch, the switch expression is evaluated and the case expressions, which need not be constants, are evaluated left-to-right and top-to-bottom; the first one that equals the switch expression triggers execution of the statements of the associated case; the other cases are skipped. If no case matches and there is a "default" case, its statements are executed. There can be at most one default case and it may appear anywhere in the "switch" statement. A missing switch expression is equivalent to the expression
true
.ExprSwitchStmt = "switch" [ SimpleStmt ";" ] [ Expression ] "{" { ExprCaseClause } "}" . ExprCaseClause = ExprSwitchCase ":" StatementList . ExprSwitchCase = "case" ExpressionList | "default" .
In a case or default clause, the last non-empty statement may be a (possibly labeled)"fallthrough" statement to indicate that control should flow from the end of this clause to the first statement of the next clause. Otherwise control flows to the end of the "switch" statement. A "fallthrough" statement may appear as the last statement of all but the last clause of an expression switch.
The expression may be preceded by a simple statement, which executes before the expression is evaluated.
switch tag { default: s3() case 0, 1, 2, 3: s1() case 4, 5, 6, 7: s2() } switch x := f(); { // missing switch expression means "true" case x < 0: return -x default: return x } switch { case x < y: f1() case x < z: f2() case x == 4: f3() }
Type switches
A type switch compares types rather than values. It is otherwise similar to an expression switch. It is marked by a special switch expression that has the form of a type assertionusing the reserved word
type
rather than an actual type:switch x.(type) { // cases }
Cases then match actual types
T
against the dynamic type of the expressionx
. As with type assertions,x
must be ofinterface type, and each non-interface typeT
listed in a case must implement the type ofx
.TypeSwitchStmt = "switch" [ SimpleStmt ";" ] TypeSwitchGuard "{" { TypeCaseClause } "}" . TypeSwitchGuard = [ identifier ":=" ] PrimaryExpr "." "(" "type" ")" . TypeCaseClause = TypeSwitchCase ":" StatementList . TypeSwitchCase = "case" TypeList | "default" . TypeList = Type { "," Type } .
The TypeSwitchGuard may include ashort variable declaration. When that form is used, the variable is declared at the beginning of the implicit block in each clause. In clauses with a case listing exactly one type, the variable has that type; otherwise, the variable has the type of the expression in the TypeSwitchGuard.
The type in a case may be
nil
; that case is used when the expression in the TypeSwitchGuard is anil
interface value.Given an expression
x
of typeinterface{}
, the following type switch:switch i := x.(type) { case nil: printString("x is nil") // type of i is type of x (interface{}) case int: printInt(i) // type of i is int case float64: printFloat64(i) // type of i is float64 case func(int) float64: printFunction(i) // type of i is func(int) float64 case bool, string: printString("type is bool or string") // type of i is type of x (interface{}) default: printString("don't know the type") // type of i is type of x (interface{}) }
could be rewritten:
v := x // x is evaluated exactly once if v == nil { i := v // type of i is type of x (interface{}) printString("x is nil") } else if i, isInt := v.(int); isInt { printInt(i) // type of i is int } else if i, isFloat64 := v.(float64); isFloat64 { printFloat64(i) // type of i is float64 } else if i, isFunc := v.(func(int) float64); isFunc { printFunction(i) // type of i is func(int) float64 } else { _, isBool := v.(bool) _, isString := v.(string) if isBool || isString { i := v // type of i is type of x (interface{}) printString("type is bool or string") } else { i := v // type of i is type of x (interface{}) printString("don't know the type") } }
The type switch guard may be preceded by a simple statement, which executes before the guard is evaluated.
The "fallthrough" statement is not permitted in a type switch.
For statements
A "for" statement specifies repeated execution of a block. The iteration is controlled by a condition, a "for" clause, or a "range" clause.
ForStmt = "for" [ Condition | ForClause | RangeClause ] Block . Condition = Expression .
In its simplest form, a "for" statement specifies the repeated execution of a block as long as a boolean condition evaluates to true. The condition is evaluated before each iteration. If the condition is absent, it is equivalent to
true
.for a < b { a *= 2 }
A "for" statement with a ForClause is also controlled by its condition, but additionally it may specify an initand a post statement, such as an assignment, an increment or decrement statement. The init statement may be ashort variable declaration, but the post statement must not.
ForClause = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] . InitStmt = SimpleStmt . PostStmt = SimpleStmt .
for i := 0; i < 10; i++ { f(i) }
If non-empty, the init statement is executed once before evaluating the condition for the first iteration; the post statement is executed after each execution of the block (and only if the block was executed). Any element of the ForClause may be empty but thesemicolons are required unless there is only a condition. If the condition is absent, it is equivalent to
true
.for cond { S() } is the same as for ; cond ; { S() } for { S() } is the same as for true { S() }
A "for" statement with a "range" clause iterates through all entries of an array, slice, string or map, or values received on a channel. For each entry it assigns iteration valuesto corresponding iteration variables and then executes the block.
RangeClause = ( ExpressionList "=" | IdentifierList ":=" ) "range" Expression .
The expression on the right in the "range" clause is called the range expression, which may be an array, pointer to an array, slice, string, map, or channel permittingreceive operations. As with an assignment, the operands on the left must beaddressable or map index expressions; they denote the iteration variables. If the range expression is a channel, only one iteration variable is permitted, otherwise there may be one or two. In the latter case, if the second iteration variable is the blank identifier, the range clause is equivalent to the same clause with only the first variable present.
The range expression is evaluated once before beginning the loop, with one exception. If the range expression is an array or a pointer to an array and only the first iteration value is present, only the range expression's length is evaluated; if that length is constantby definition, the range expression itself will not be evaluated.
Function calls on the left are evaluated once per iteration. For each iteration, iteration values are produced as follows:
Range expression 1st value 2nd value (if 2nd variable is present) array or slice a [n]E, *[n]E, or []E index i int a[i] E string s string type index i int see below rune map m map[K]V key k K m[k] V channel c chan E, <-chan E element e E
- For an array, pointer to array, or slice value
a
, the index iteration values are produced in increasing order, starting at element index 0. If only the first iteration variable is present, the range loop produces iteration values from 0 up tolen(a)
and does not index into the array or slice itself. For anil
slice, the number of iterations is 0. - For a string value, the "range" clause iterates over the Unicode code points in the string starting at byte index 0. On successive iterations, the index value will be the index of the first byte of successive UTF-8-encoded code points in the string, and the second value, of type
rune
, will be the value of the corresponding code point. If the iteration encounters an invalid UTF-8 sequence, the second value will be0xFFFD
, the Unicode replacement character, and the next iteration will advance a single byte in the string. - The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next. If map entries that have not yet been reached are removed during iteration, the corresponding iteration values will not be produced. If map entries are created during iteration, that entry may be produced during the iteration or may be skipped. The choice may vary for each entry created and from one iteration to the next. If the map is
nil
, the number of iterations is 0. - For channels, the iteration values produced are the successive values sent on the channel until the channel is closed. If the channel is
nil
, the range expression blocks forever.
The iteration values are assigned to the respective iteration variables as in an assignment statement.
The iteration variables may be declared by the "range" clause using a form ofshort variable declaration(
:=
). In this case their types are set to the types of the respective iteration values and their scope ends at the end of the "for" statement; they are re-used in each iteration. If the iteration variables are declared outside the "for" statement, after execution their values will be those of the last iteration.var testdata *struct { a *[7]int } for i, _ := range testdata.a { // testdata.a is never evaluated; len(testdata.a) is constant // i ranges from 0 to 6 f(i) } var a [10]string m := map[string]int{"mon":0, "tue":1, "wed":2, "thu":3, "fri":4, "sat":5, "sun":6} for i, s := range a { // type of i is int // type of s is string // s == a[i] g(i, s) } var key string var val interface {} // value type of m is assignable to val for key, val = range m { h(key, val) } // key == last map key encountered in iteration // val == map[key] var ch chan Work = producer() for w := range ch { doWork(w) }
Go statements
A "go" statement starts the execution of a function call as an independent concurrent thread of control, or goroutine, within the same address space.
GoStmt = "go" Expression .
The expression must be a function or method call; it cannot be parenthesized. Calls of built-in functions are restricted as forexpression statements.
The function value and parameters areevaluated as usualin the calling goroutine, but unlike with a regular call, program execution does not wait for the invoked function to complete. Instead, the function begins executing independently in a new goroutine. When the function terminates, its goroutine also terminates. If the function has any return values, they are discarded when the function completes.
go Server() go func(ch chan<- bool) { for { sleep(10); ch <- true; }} (c)
Select statements
A "select" statement chooses which of a set of possible communications will proceed. It looks similar to a "switch" statement but with the cases all referring to communication operations.
SelectStmt = "select" "{" { CommClause } "}" . CommClause = CommCase ":" StatementList . CommCase = "case" ( SendStmt | RecvStmt ) | "default" . RecvStmt = [ ExpressionList "=" | IdentifierList ":=" ] RecvExpr . RecvExpr = Expression .
RecvExpr must be a receive operation. For all the cases in the "select" statement, the channel expressions are evaluated in top-to-bottom order, along with any expressions that appear on the right hand side of send statements. A channel may be
nil
, which is equivalent to that case not being present in the select statement except, if a send, its expression is still evaluated. If any of the resulting operations can proceed, one of those is chosen and the corresponding communication and statements are evaluated. Otherwise, if there is a default case, that executes; if there is no default case, the statement blocks until one of the communications can complete. There can be at most one default case and it may appear anywhere in the "select" statement. If there are no cases with non-nil
channels, the statement blocks forever. Even if the statement blocks, the channel and send expressions are evaluated only once, upon entering the select statement.Since all the channels and send expressions are evaluated, any side effects in that evaluation will occur for all the communications in the "select" statement.
If multiple cases can proceed, a uniform pseudo-random choice is made to decide which single communication will execute.
The receive case may declare one or two new variables using ashort variable declaration.
var c, c1, c2, c3 chan int var i1, i2 int select { case i1 = <-c1: print("received ", i1, " from c1\n") case c2 <- i2: print("sent ", i2, " to c2\n") case i3, ok := (<-c3): // same as: i3, ok := <-c3 if ok { print("received ", i3, " from c3\n") } else { print("c3 is closed\n") } default: print("no communication\n") } for { // send random sequence of bits to c select { case c <- 0: // note: no statement, no fallthrough, no folding of cases case c <- 1: } } select {} // block forever
Return statements
A "return" statement in a function
F
terminates the execution ofF
, and optionally provides one or more result values. Any functions deferred byF
are executed beforeF
returns to its caller.ReturnStmt = "return" [ ExpressionList ] .
In a function without a result type, a "return" statement must not specify any result values.
func noResult() { return }
There are three ways to return values from a function with a result type:
- The return value or values may be explicitly listed in the "return" statement. Each expression must be single-valued and assignable to the corresponding element of the function's result type.
func simpleF() int { return 2 } func complexF1() (re float64, im float64) { return -7.0, -4.0 }
- The expression list in the "return" statement may be a single call to a multi-valued function. The effect is as if each value returned from that function were assigned to a temporary variable with the type of the respective value, followed by a "return" statement listing these variables, at which point the rules of the previous case apply.
func complexF2() (re float64, im float64) { return complexF1() }
- The expression list may be empty if the function's result type specifies names for its result parameters. The result parameters act as ordinary local variables and the function may assign values to them as necessary. The "return" statement returns the values of these variables.
func complexF3() (re float64, im float64) { re = 7.0 im = 4.0 return } func (devnull) Write(p []byte) (n int, _ error) { n = len(p) return }
Regardless of how they are declared, all the result values are initialized to the zero values for their type upon entry to the function. A "return" statement that specifies results sets the result parameters before any deferred functions are executed.
- For an array, pointer to array, or slice value