summaryrefslogtreecommitdiff
path: root/doc/go_spec.html
diff options
context:
space:
mode:
Diffstat (limited to 'doc/go_spec.html')
-rw-r--r--doc/go_spec.html751
1 files changed, 478 insertions, 273 deletions
diff --git a/doc/go_spec.html b/doc/go_spec.html
index 90acc1704..0cb9f54b1 100644
--- a/doc/go_spec.html
+++ b/doc/go_spec.html
@@ -1,6 +1,6 @@
<!--{
"Title": "The Go Programming Language Specification",
- "Subtitle": "Version of June 4, 2012",
+ "Subtitle": "Version of March 1, 2013",
"Path": "/ref/spec"
}-->
@@ -15,7 +15,6 @@ TODO
[ ] need explicit language about the result type of operations
[ ] should probably write something about evaluation order of statements even
though obvious
-[ ] review language on implicit dereferencing
-->
@@ -89,7 +88,8 @@ Source code is Unicode text encoded in
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 term <i>character</i> to refer to a Unicode code point.
+will use the unqualified term <i>character</i> to refer to a Unicode code point
+in the source text.
</p>
<p>
Each code point is distinct; for instance, upper and lower case letters
@@ -99,6 +99,11 @@ are different characters.
Implementation restriction: For compatibility with other tools, a
compiler may disallow the NUL character (U+0000) in the source text.
</p>
+<p>
+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.
+</p>
<h3 id="Characters">Characters</h3>
@@ -113,7 +118,7 @@ unicode_digit = /* a Unicode code point classified as "Decimal Digit" */ .
</pre>
<p>
-In <a href="http://www.unicode.org/versions/Unicode6.0.0/">The Unicode Standard 6.0</a>,
+In <a href="http://www.unicode.org/versions/Unicode6.2.0/">The Unicode Standard 6.2</a>,
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,
@@ -198,7 +203,7 @@ token is
<a href="#Integer_literals">integer</a>,
<a href="#Floating-point_literals">floating-point</a>,
<a href="#Imaginary_literals">imaginary</a>,
- <a href="#Character_literals">character</a>, or
+ <a href="#Rune_literals">rune</a>, or
<a href="#String_literals">string</a> literal
</li>
@@ -360,13 +365,15 @@ imaginary_lit = (decimals | float_lit) "i" .
</pre>
-<h3 id="Character_literals">Character literals</h3>
+<h3 id="Rune_literals">Rune literals</h3>
<p>
-A character literal represents a <a href="#Constants">character constant</a>,
-typically a Unicode code point, 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 itself,
+A rune literal represents a <a href="#Constants">rune constant</a>,
+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.
</p>
@@ -380,8 +387,8 @@ a literal <code>a</code>, Unicode U+0061, value <code>0x61</code>, while
a literal <code>a</code>-dieresis, U+00E4, value <code>0xe4</code>.
</p>
<p>
-Several backslash escapes allow arbitrary values to be represented
-as ASCII text. There are four ways to represent the integer value
+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: <code>\x</code> followed by exactly two hexadecimal
digits; <code>\u</code> followed by exactly four hexadecimal digits;
<code>\U</code> followed by exactly eight hexadecimal digits, and a
@@ -409,14 +416,14 @@ After a backslash, certain single-character escapes represent special values:
\t U+0009 horizontal tab
\v U+000b vertical tab
\\ U+005c backslash
-\' U+0027 single quote (valid escape only within character literals)
+\' U+0027 single quote (valid escape only within rune literals)
\" U+0022 double quote (valid escape only within string literals)
</pre>
<p>
-All other sequences starting with a backslash are illegal inside character literals.
+All other sequences starting with a backslash are illegal inside rune literals.
</p>
<pre class="ebnf">
-char_lit = "'" ( unicode_value | byte_value ) "'" .
+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 .
@@ -439,6 +446,11 @@ escaped_char = `\` ( "a" | "b" | "f" | "n" | "r" | "t" | "v" | `\` | "'" | `
'\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
</pre>
@@ -453,7 +465,8 @@ raw string literals and interpreted string literals.
Raw string literals are character sequences between back quotes
<code>``</code>. Within the quotes, any character is legal except
back quote. The value of a raw string literal is the
-string composed of the uninterpreted characters between the quotes;
+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
@@ -464,8 +477,9 @@ Interpreted string literals are character sequences between double
quotes <code>&quot;&quot;</code>. The text between the quotes,
which may not contain newlines, forms the
value of the literal, with backslash escapes interpreted as they
-are in character literals (except that <code>\'</code> is illegal and
-<code>\"</code> is legal). The three-digit octal (<code>\</code><i>nnn</i>)
+are in rune literals (except that <code>\'</code> is illegal and
+<code>\"</code> is legal), with the same restrictions.
+The three-digit octal (<code>\</code><i>nnn</i>)
and two-digit hexadecimal (<code>\x</code><i>nn</i>) escapes represent individual
<i>bytes</i> of the resulting string; all other escapes represent
the (possibly multi-byte) UTF-8 encoding of individual <i>characters</i>.
@@ -492,6 +506,8 @@ interpreted_string_lit = `"` { unicode_value | byte_value } `"` .
"日本語"
"\u65e5本\U00008a9e"
"\xff\u00FF"
+"\uD800" // illegal: surrogate half
+"\U00110000" // illegal: invalid Unicode code point
</pre>
<p>
@@ -501,15 +517,15 @@ These examples all represent the same string:
<pre>
"日本語" // 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
+"\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
</pre>
<p>
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 character literal (it is not a single code
+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.
</p>
@@ -518,7 +534,7 @@ literal.
<h2 id="Constants">Constants</h2>
<p>There are <i>boolean constants</i>,
-<i>character constants</i>,
+<i>rune constants</i>,
<i>integer constants</i>,
<i>floating-point constants</i>, <i>complex constants</i>,
and <i>string constants</i>. Character, integer, floating-point,
@@ -528,7 +544,7 @@ collectively called <i>numeric constants</i>.
<p>
A constant value is represented by a
-<a href="#Character_literals">character</a>,
+<a href="#Rune_literals">rune</a>,
<a href="#Integer_literals">integer</a>,
<a href="#Floating-point_literals">floating-point</a>,
<a href="#Imaginary_literals">imaginary</a>,
@@ -622,14 +638,15 @@ expressions</a>.
<p>
A type determines the set of values and operations specific to values of that
-type. A type may be specified by a (possibly qualified) <i>type name</i>
-(§<a href="#Qualified_identifiers">Qualified identifier</a>, §<a href="#Type_declarations">Type declarations</a>) or a <i>type literal</i>,
+type. A type may be specified by a
+(possibly <a href="#Qualified_identifiers">qualified</a>) <i>type name</i>
+(§<a href="#Type_declarations">Type declarations</a>) or a <i>type literal</i>,
which composes a new type from previously declared types.
</p>
<pre class="ebnf">
Type = TypeName | TypeLit | "(" Type ")" .
-TypeName = QualifiedIdent .
+TypeName = identifier | QualifiedIdent .
TypeLit = ArrayType | StructType | PointerType | FunctionType | InterfaceType |
SliceType | MapType | ChannelType .
</pre>
@@ -646,7 +663,7 @@ type literals.
The <i>static type</i> (or just <i>type</i>) of a variable is the
type defined by its declaration. Variables of interface type
also have a distinct <i>dynamic type</i>, which
-is the actual type of the value stored in the variable at run-time.
+is the actual type of the value stored in the variable at run time.
The dynamic type may vary during execution but is always
<a href="#Assignability">assignable</a>
to the static type of the interface variable. For non-interface
@@ -764,19 +781,21 @@ particular architecture.
<p>
A <i>string type</i> represents the set of string values.
-Strings behave like slices of bytes but are immutable: once created,
+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 <code>string</code>.
+</p>
<p>
-The elements of strings have type <code>byte</code> and may be
-accessed using the usual <a href="#Indexes">indexing operations</a>. It is
-illegal to take the address of such an element; if
-<code>s[i]</code> is the <i>i</i>th byte of a
-string, <code>&amp;s[i]</code> is invalid. The length of string
-<code>s</code> can be discovered using the built-in function
-<code>len</code>. The length is a compile-time constant if <code>s</code>
-is a string literal.
+The length of a string <code>s</code> (its size in bytes) can be discovered using
+the built-in function <a href="#Length_and_capacity"><code>len</code></a>.
+The length is a compile-time constant if the string is a constant.
+A string's bytes can be accessed by integer <a href="#Index_expressions">indices</a>
+0 through <code>len(s)-1</code>.
+It is illegal to take the address of such an element; if
+<code>s[i]</code> is the <code>i</code>'th byte of a
+string, <code>&amp;s[i]</code> is invalid.
</p>
@@ -796,12 +815,13 @@ ElementType = Type .
</pre>
<p>
-The length is part of the array's type and must be a
-<a href="#Constant_expressions">constant expression</a> that evaluates to a non-negative
-integer value. The length of array <code>a</code> can be discovered
-using the built-in function <a href="#Length_and_capacity"><code>len(a)</code></a>.
-The elements can be indexed by integer
-indices 0 through <code>len(a)-1</code> (§<a href="#Indexes">Indexes</a>).
+The length is part of the array's type; it must evaluate to a non-
+negative <a href="#Constants">constant</a> representable by a value
+of type <code>int</code>.
+The length of array <code>a</code> can be discovered
+using the built-in function <a href="#Length_and_capacity"><code>len</code></a>.
+The elements can be addressed by integer <a href="#Index_expressions">indices</a>
+0 through <code>len(a)-1</code>.
Array types are always one-dimensional but may be composed to form
multi-dimensional types.
</p>
@@ -830,9 +850,9 @@ SliceType = "[" "]" ElementType .
<p>
Like arrays, slices are indexable and have a length. The length of a
slice <code>s</code> can be discovered by the built-in function
-<a href="#Length_and_capacity"><code>len(s)</code></a>; unlike with arrays it may change during
-execution. The elements can be addressed by integer indices 0
-through <code>len(s)-1</code> (§<a href="#Indexes">Indexes</a>). The slice index of a
+<a href="#Length_and_capacity"><code>len</code></a>; unlike with arrays it may change during
+execution. The elements can be addressed by integer <a href="#Index_expressions">indices</a>
+0 through <code>len(s)-1</code>. The slice index of a
given element may be less than the index of the same element in the
underlying array.
</p>
@@ -981,7 +1001,7 @@ promoted methods are included in the method set of the struct as follows:
<code>T</code>. The method set of <code>*S</code> also
includes promoted methods with receiver <code>*T</code>.
</li>
-
+
<li>
If <code>S</code> contains an anonymous field <code>*T</code>,
the method sets of <code>S</code> and <code>*S</code> both
@@ -994,7 +1014,7 @@ promoted methods are included in the method set of the struct as follows:
A field declaration may be followed by an optional string literal <i>tag</i>,
which becomes an attribute for all the fields in the corresponding
field declaration. The tags are made
-visible through a <a href="#Package_unsafe">reflection interface</a>
+visible through a <a href="/pkg/reflect/#StructTag">reflection interface</a>
but are otherwise ignored.
</p>
@@ -1046,8 +1066,11 @@ ParameterDecl = [ IdentifierList ] [ "..." ] Type .
<p>
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; if absent, each
-type stands for one item of that type. Parameter and result
+stands for one item (parameter or result) of the specified type and
+all non-<a href="#Blank_identifier">blank</a> names in the signature
+must be <a href="#Uniqueness_of_identifiers">unique</a>.
+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.
</p>
@@ -1232,10 +1255,10 @@ map[string]interface{}
<p>
The number of map elements is called its length.
For a map <code>m</code>, it can be discovered using the
-built-in function <a href="#Length_and_capacity"><code>len(m)</code></a>
+built-in function <a href="#Length_and_capacity"><code>len</code></a>
and may change during execution. Elements may be added during execution
using <a href="#Assignments">assignments</a> and retrieved with
-<a href="#Indexes">index</a> expressions; they may be removed with the
+<a href="#Index_expressions">index expressions</a>; they may be removed with the
<a href="#Deletion_of_map_elements"><code>delete</code></a> built-in function.
</p>
<p>
@@ -1510,11 +1533,11 @@ Go is lexically scoped using blocks:
or function (but not method) declared at top level (outside any
function) is the package block.</li>
- <li>The scope of an imported package identifier is the file block
+ <li>The scope of the package name of an imported package is the file block
of the file containing the import declaration.</li>
- <li>The scope of an identifier denoting a function parameter or
- result variable is the function body.</li>
+ <li>The scope of an identifier denoting a method receiver, function parameter,
+ or result variable is the function body.</li>
<li>The scope of a constant or variable identifier declared
inside a function begins at the end of the ConstSpec or VarSpec
@@ -1897,7 +1920,7 @@ _, y, _ := coord(p) // coord() returns three values; only interested in y coord
<p>
Unlike regular variable declarations, a short variable declaration may redeclare variables provided they
-were originally declared in the same block with the same type, and at
+were originally declared earlier in the same block with the same type, and at
least one of the non-<a href="#Blank_identifier">blank</a> variables is new. As a consequence, redeclaration
can only appear in a multi-variable short declaration.
Redeclaration does not introduce a new
@@ -1907,6 +1930,7 @@ variable; it just assigns a new value to the original.
<pre>
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
</pre>
<p>
@@ -1969,8 +1993,15 @@ is visible only within selectors for that type.
</p>
<p>
-For a base type, the non-<a href="#Blank_identifier">blank</a> names of
-methods bound to it must be <a href="#Uniqueness_of_identifiers">unique</a>.
+A non-<a href="#Blank_identifier">blank</a> receiver identifier must be
+<a href="#Uniqueness_of_identifiers">unique</a> 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.
+</p>
+
+<p>
+For a base type, the non-blank names of methods bound to it must be unique.
If the base type is a <a href="#Struct_types">struct type</a>,
the non-blank method and field names must be distinct.
</p>
@@ -1997,12 +2028,6 @@ to the base type <code>Point</code>.
</p>
<p>
-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.
-</p>
-
-<p>
The type of a method is the type of a function with the receiver as first
argument. For instance, the method <code>Scale</code> has type
</p>
@@ -2026,25 +2051,33 @@ operators and functions to operands.
<h3 id="Operands">Operands</h3>
<p>
-Operands denote the elementary values in an expression.
+Operands denote the elementary values in an expression. An operand may be a
+literal, a (possibly <a href="#Qualified_identifiers">qualified</a>) identifier
+denoting a
+<a href="#Constant_declarations">constant</a>,
+<a href="#Variable_declarations">variable</a>, or
+<a href="#Function_declarations">function</a>,
+a <a href="#Method_expressions">method expression</a> yielding a function,
+or a parenthesized expression.
</p>
<pre class="ebnf">
-Operand = Literal | QualifiedIdent | MethodExpr | "(" Expression ")" .
+Operand = Literal | OperandName | MethodExpr | "(" Expression ")" .
Literal = BasicLit | CompositeLit | FunctionLit .
-BasicLit = int_lit | float_lit | imaginary_lit | char_lit | string_lit .
+BasicLit = int_lit | float_lit | imaginary_lit | rune_lit | string_lit .
+OperandName = identifier | QualifiedIdent.
</pre>
-
<h3 id="Qualified_identifiers">Qualified identifiers</h3>
<p>
-A qualified identifier is a non-<a href="#Blank_identifier">blank</a> identifier
-qualified by a package name prefix.
+A qualified identifier is an identifier qualified with a package name prefix.
+Both the package name and the identifier must not be
+<a href="#Blank_identifier">blank</a>.
</p>
<pre class="ebnf">
-QualifiedIdent = [ PackageName "." ] identifier .
+QualifiedIdent = PackageName "." identifier .
</pre>
<p>
@@ -2089,7 +2122,7 @@ The types of the expressions must be <a href="#Assignability">assignable</a>
to 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 expression for array and slice literals, and a key for map 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.
@@ -2101,18 +2134,18 @@ For struct literals the following rules apply:
<ul>
<li>A key must be a field name declared in the LiteralType.
</li>
- <li>A literal that does not contain any keys must
+ <li>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.
</li>
<li>If any element has a key, every element must have a key.
</li>
- <li>A literal that contains keys does not need to
+ <li>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.
</li>
<li>A literal may omit the element list; such a literal evaluates
- to the zero value for its type.
+ to the zero value for its type.
</li>
<li>It is an error to specify an element for a non-exported
field of a struct belonging to a different package.
@@ -2198,7 +2231,7 @@ Within a composite literal of array, slice, or map type <code>T</code>,
elements that are themselves composite literals may elide the respective
literal type if it is identical to the element type of <code>T</code>.
Similarly, elements that are addresses of composite literals may elide
-the <code>&amp;T</code> when the the element type is <code>*T</code>.
+the <code>&amp;T</code> when the element type is <code>*T</code>.
</p>
@@ -2315,7 +2348,6 @@ Point{1, 2}
m["foo"]
s[i : j + 1]
obj.color
-math.Sin
f.p[i].x()
</pre>
@@ -2323,7 +2355,9 @@ f.p[i].x()
<h3 id="Selectors">Selectors</h3>
<p>
-A primary expression of the form
+For a <a href="#Primary_expressions">primary expression</a> <code>x</code>
+that is not a <a href="#Package_clause">package name</a>, the
+<i>selector expression</i>
</p>
<pre>
@@ -2331,17 +2365,20 @@ x.f
</pre>
<p>
-denotes the field or method <code>f</code> of the value denoted by <code>x</code>
-(or sometimes <code>*x</code>; see below). The identifier <code>f</code>
-is called the (field or method)
-<i>selector</i>; it must not be the <a href="#Blank_identifier">blank identifier</a>.
-The type of the expression is the type of <code>f</code>.
+denotes the field or method <code>f</code> of the value <code>x</code>
+(or sometimes <code>*x</code>; see below).
+The identifier <code>f</code> is called the (field or method) <i>selector</i>;
+it must not be the <a href="#Blank_identifier">blank identifier</a>.
+The type of the selector expression is the type of <code>f</code>.
+If <code>x</code> is a package name, see the section on
+<a href="#Qualified_identifiers">qualified identifiers</a>.
</p>
+
<p>
A selector <code>f</code> may denote a field or method <code>f</code> of
a type <code>T</code>, or it may refer
-to a field or method <code>f</code> of a nested anonymous field of
-<code>T</code>.
+to a field or method <code>f</code> of a nested
+<a href="#Struct_types">anonymous field</a> of <code>T</code>.
The number of anonymous fields traversed
to reach <code>f</code> is called its <i>depth</i> in <code>T</code>.
The depth of a field or method <code>f</code>
@@ -2350,9 +2387,11 @@ The depth of a field or method <code>f</code> declared in
an anonymous field <code>A</code> in <code>T</code> is the
depth of <code>f</code> in <code>A</code> plus one.
</p>
+
<p>
The following rules apply to selectors:
</p>
+
<ol>
<li>
For a value <code>x</code> of type <code>T</code> or <code>*T</code>
@@ -2364,18 +2403,26 @@ If there is not exactly <a href="#Uniqueness_of_identifiers">one <code>f</code><
with shallowest depth, the selector expression is illegal.
</li>
<li>
-For a variable <code>x</code> of type <code>I</code>
-where <code>I</code> is an interface type,
-<code>x.f</code> denotes the actual method with name <code>f</code> of the value assigned
-to <code>x</code> if there is such a method.
-If no value or <code>nil</code> was assigned to <code>x</code>, <code>x.f</code> is illegal.
+For a variable <code>x</code> of type <code>I</code> where <code>I</code>
+is an interface type, <code>x.f</code> denotes the actual method with name
+<code>f</code> of the value assigned to <code>x</code>.
+If there is no method with name <code>f</code> in the
+<a href="#Method_sets">method set</a> of <code>I</code>, the selector
+expression is illegal.
</li>
<li>
In all other cases, <code>x.f</code> is illegal.
</li>
+<li>
+If <code>x</code> is of pointer or interface type and has the value
+<code>nil</code>, assigning to, evaluating, or calling <code>x.f</code>
+causes a <a href="#Run_time_panics">run-time panic</a>.
+</li>
</ol>
+
<p>
-Selectors automatically dereference pointers to structs.
+Selectors automatically <a href="#Address_operators">dereference</a>
+pointers to structs.
If <code>x</code> is a pointer to a struct, <code>x.y</code>
is shorthand for <code>(*x).y</code>; if the field <code>y</code>
is also a pointer to a struct, <code>x.y.z</code> is shorthand
@@ -2384,6 +2431,7 @@ If <code>x</code> contains an anonymous field of type <code>*A</code>,
where <code>A</code> is also a struct type,
<code>x.f</code> is a shortcut for <code>(*x.A).f</code>.
</p>
+
<p>
For example, given the declarations:
</p>
@@ -2421,9 +2469,9 @@ 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
+p.M2() // (*p).M2()
+p.M1() // ((*p).T1).M1()
+p.M0() // ((*p).T0).M0()
</pre>
@@ -2434,7 +2482,7 @@ TODO: Specify what happens to receivers.
-->
-<h3 id="Indexes">Indexes</h3>
+<h3 id="Index_expressions">Index expressions</h3>
<p>
A primary expression of the form
@@ -2452,16 +2500,35 @@ rules apply:
</p>
<p>
+If <code>a</code> is not a map:
+</p>
+<ul>
+ <li>the index <code>x</code> must be an integer value; it is <i>in range</i> if <code>0 &lt;= x &lt; len(a)</code>,
+ otherwise it is <i>out of range</i></li>
+ <li>a <a href="#Constants">constant</a> index must be non-negative
+ and representable by a value of type <code>int</code>
+</ul>
+
+<p>
For <code>a</code> of type <code>A</code> or <code>*A</code>
-where <code>A</code> is an <a href="#Array_types">array type</a>,
-or for <code>a</code> of type <code>S</code> where <code>S</code> is a <a href="#Slice_types">slice type</a>:
+where <code>A</code> is an <a href="#Array_types">array type</a>:
</p>
<ul>
- <li><code>x</code> must be an integer value and <code>0 &lt;= x &lt; len(a)</code></li>
+ <li>a <a href="#Constants">constant</a> index must be in range</li>
+ <li>if <code>a</code> is <code>nil</code> or if <code>x</code> is out of range at run time,
+ a <a href="#Run_time_panics">run-time panic</a> occurs</li>
<li><code>a[x]</code> is the array element at index <code>x</code> and the type of
- <code>a[x]</code> is the element type of <code>A</code></li>
- <li>if <code>a</code> is <code>nil</code> or if the index <code>x</code> is out of range,
- a <a href="#Run_time_panics">run-time panic</a> occurs</li>
+ <code>a[x]</code> is the element type of <code>A</code></li>
+</ul>
+
+<p>
+For <code>a</code> of type <code>S</code> where <code>S</code> is a <a href="#Slice_types">slice type</a>:
+</p>
+<ul>
+ <li>if the slice is <code>nil</code> or if <code>x</code> is out of range at run time,
+ a <a href="#Run_time_panics">run-time panic</a> occurs</li>
+ <li><code>a[x]</code> is the slice element at index <code>x</code> and the type of
+ <code>a[x]</code> is the element type of <code>S</code></li>
</ul>
<p>
@@ -2469,12 +2536,13 @@ For <code>a</code> of type <code>T</code>
where <code>T</code> is a <a href="#String_types">string type</a>:
</p>
<ul>
- <li><code>x</code> must be an integer value and <code>0 &lt;= x &lt; len(a)</code></li>
+ <li>a <a href="#Constants">constant</a> index must be in range
+ if the string <code>a</code> is also constant</li>
+ <li>if <code>x</code> is out of range at run time,
+ a <a href="#Run_time_panics">run-time panic</a> occurs</li>
<li><code>a[x]</code> is the byte at index <code>x</code> and the type of
- <code>a[x]</code> is <code>byte</code></li>
+ <code>a[x]</code> is <code>byte</code></li>
<li><code>a[x]</code> may not be assigned to</li>
- <li>if the index <code>x</code> is out of range,
- a <a href="#Run_time_panics">run-time panic</a> occurs</li>
</ul>
<p>
@@ -2483,14 +2551,14 @@ where <code>M</code> is a <a href="#Map_types">map type</a>:
</p>
<ul>
<li><code>x</code>'s type must be
- <a href="#Assignability">assignable</a>
- to the key type of <code>M</code></li>
+ <a href="#Assignability">assignable</a>
+ to the key type of <code>M</code></li>
<li>if the map contains an entry with key <code>x</code>,
- <code>a[x]</code> is the map value with key <code>x</code>
- and the type of <code>a[x]</code> is the value type of <code>M</code></li>
+ <code>a[x]</code> is the map value with key <code>x</code>
+ and the type of <code>a[x]</code> is the value type of <code>M</code></li>
<li>if the map is <code>nil</code> or does not contain such an entry,
- <code>a[x]</code> is the <a href="#The_zero_value">zero value</a>
- for the value type of <code>M</code></li>
+ <code>a[x]</code> is the <a href="#The_zero_value">zero value</a>
+ for the value type of <code>M</code></li>
</ul>
<p>
@@ -2533,9 +2601,9 @@ a[low : high]
</pre>
<p>
-constructs a substring or slice. The index expressions <code>low</code> and
+constructs a substring or slice. The indices <code>low</code> and
<code>high</code> select which elements appear in the result. The result has
-indexes starting at 0 and length equal to
+indices starting at 0 and length equal to
<code>high</code>&nbsp;-&nbsp;<code>low</code>.
After slicing the array <code>a</code>
</p>
@@ -2556,7 +2624,7 @@ s[2] == 4
</pre>
<p>
-For convenience, any of the index expressions may be omitted. A missing <code>low</code>
+For convenience, any of the indices may be omitted. A missing <code>low</code>
index defaults to zero; a missing <code>high</code> index defaults to the length of the
sliced operand:
</p>
@@ -2568,9 +2636,15 @@ a[:] // same as a[0 : len(a)]
</pre>
<p>
-For arrays or strings, the indexes <code>low</code> and <code>high</code> must
-satisfy 0 &lt;= <code>low</code> &lt;= <code>high</code> &lt;= length; for
-slices, the upper bound is the capacity rather than the length.
+For arrays or strings, the indices <code>low</code> and <code>high</code> are
+<i>in range</i> if <code>0</code> &lt;= <code>low</code> &lt;= <code>high</code> &lt;= <code>len(a)</code>,
+otherwise they are <i>out of range</i>.
+For slices, the upper index bound is the slice capacity <code>cap(a)</code> rather than the length.
+A <a href="#Constants">constant</a> index must be non-negative and representable by a value of type
+<code>int</code>.
+If both indices
+are constant, they must satisfy <code>low &lt;= high</code>. If <code>a</code> is <code>nil</code>
+or if the indices are out of range at run time, a <a href="#Run_time_panics">run-time panic</a> occurs.
</p>
<p>
@@ -2601,19 +2675,33 @@ The notation <code>x.(T)</code> is called a <i>type assertion</i>.
More precisely, if <code>T</code> is not an interface type, <code>x.(T)</code> asserts
that the dynamic type of <code>x</code> is <a href="#Type_identity">identical</a>
to the type <code>T</code>.
+In this case, <code>T</code> must <a href="#Method_sets">implement</a> the (interface) type of <code>x</code>;
+otherwise the type assertion is invalid since it is not possible for <code>x</code>
+to store a value of type <code>T</code>.
If <code>T</code> is an interface type, <code>x.(T)</code> asserts that the dynamic type
-of <code>x</code> implements the interface <code>T</code> (§<a href="#Interface_types">Interface types</a>).
+of <code>x</code> implements the interface <code>T</code>.
</p>
<p>
If the type assertion holds, the value of the expression is the value
stored in <code>x</code> and its type is <code>T</code>. If the type assertion is false,
a <a href="#Run_time_panics">run-time panic</a> occurs.
In other words, even though the dynamic type of <code>x</code>
-is known only at run-time, the type of <code>x.(T)</code> is
+is known only at run time, the type of <code>x.(T)</code> is
known to be <code>T</code> in a correct program.
</p>
+
+<pre>
+var x interface{} = 7 // x has dynamic type int and value 7
+i := x.(int) // i has type int and value 7
+
+type I interface { m() }
+var y I
+s := y.(string) // illegal: string does not implement I (missing method m)
+r := y.(io.Reader) // r has type io.Reader and y must implement both I and io.Reader
+</pre>
+
<p>
-If a type assertion is used in an assignment or initialization of the form
+If a type assertion is used in an <a href="#Assignments">assignment</a> or initialization of the form
</p>
<pre>
@@ -2629,7 +2717,7 @@ otherwise, the expression returns <code>(Z, false)</code> where <code>Z</code>
is the <a href="#The_zero_value">zero value</a> for type <code>T</code>.
No run-time panic occurs in this case.
The type assertion in this construct thus acts like a function call
-returning a value and a boolean indicating success. (§<a href="#Assignments">Assignments</a>)
+returning a value and a boolean indicating success.
</p>
@@ -2677,13 +2765,14 @@ causes a <a href="#Run_time_panics">run-time panic</a>.
</p>
<p>
-As a special case, if the return parameters of a function or method
+As a special case, if the return values of a function or method
<code>g</code> are equal in number and individually
assignable to the parameters of another function or method
<code>f</code>, then the call <code>f(g(<i>parameters_of_g</i>))</code>
will invoke <code>f</code> after binding the return values of
<code>g</code> to the parameters of <code>f</code> in order. The call
-of <code>f</code> must contain no parameters other than the call of <code>g</code>.
+of <code>f</code> must contain no parameters other than the call of <code>g</code>,
+and <code>g</code> must have at least one return value.
If <code>f</code> has a final <code>...</code> parameter, it is
assigned the return values of <code>g</code> that remain after
assignment of regular parameters.
@@ -2834,8 +2923,8 @@ As a consequence, statement <code>*p++</code> is the same as <code>(*p)++</code>
<p>
There are five precedence levels for binary operators.
Multiplication operators bind strongest, followed by addition
-operators, comparison operators, <code>&amp;&amp;</code> (logical and),
-and finally <code>||</code> (logical or):
+operators, comparison operators, <code>&amp;&amp;</code> (logical AND),
+and finally <code>||</code> (logical OR):
</p>
<pre class="grammar">
@@ -2878,10 +2967,10 @@ to strings. All other arithmetic operators apply to integers only.
/ quotient integers, floats, complex values
% remainder integers
-&amp; bitwise and integers
-| bitwise or integers
-^ bitwise xor integers
-&amp;^ bit clear (and not) integers
+&amp; bitwise AND integers
+| bitwise OR integers
+^ bitwise XOR integers
+&amp;^ bit clear (AND NOT) integers
&lt;&lt; left shift integer &lt;&lt; unsigned integer
&gt;&gt; right shift integer &gt;&gt; unsigned integer
@@ -2938,10 +3027,11 @@ int64 -9223372036854775808
</pre>
<p>
-If the divisor is zero, a <a href="#Run_time_panics">run-time panic</a> occurs.
-If the dividend is positive and the divisor is a constant power of 2,
+If the divisor is a <a href="#Constants">constant</a>, it must not be zero.
+If the divisor is zero at run time, a <a href="#Run_time_panics">run-time panic</a> occurs.
+If the dividend is non-negative and the divisor is a constant power of 2,
the division may be replaced by a right shift, and computing the remainder may
-be replaced by a bitwise "and" operation:
+be replaced by a bitwise AND operation:
</p>
<pre>
@@ -2976,10 +3066,10 @@ follows:
</pre>
<p>
-For floating-point numbers,
+For floating-point and complex numbers,
<code>+x</code> is the same as <code>x</code>,
while <code>-x</code> is the negation of <code>x</code>.
-The result of a floating-point division by zero is not specified beyond the
+The result of a floating-point or complex division by zero is not specified beyond the
IEEE-754 standard; whether a <a href="#Run_time_panics">run-time panic</a>
occurs is implementation-specific.
</p>
@@ -3142,9 +3232,9 @@ The right operand is evaluated conditionally.
</p>
<pre class="grammar">
-&amp;&amp; conditional and p &amp;&amp; q is "if p then q else false"
-|| conditional or p || q is "if p then true else q"
-! not !p is "not p"
+&amp;&amp; conditional AND p &amp;&amp; q is "if p then q else false"
+|| conditional OR p || q is "if p then true else q"
+! NOT !p is "not p"
</pre>
@@ -3158,6 +3248,7 @@ that is, either a variable, pointer indirection, or slice indexing
operation; or a field selector of an addressable struct operand;
or an array indexing operation of an addressable array.
As an exception to the addressability requirement, <code>x</code> may also be a
+(possibly parenthesized)
<a href="#Composite_literals">composite literal</a>.
</p>
<p>
@@ -3171,6 +3262,7 @@ will cause a <a href="#Run_time_panics">run-time panic</a>.
<pre>
&amp;x
&amp;a[f(2)]
+&amp;Point{2, 3}
*p
*pf(x)
</pre>
@@ -3181,9 +3273,13 @@ will cause a <a href="#Run_time_panics">run-time panic</a>.
<p>
For an operand <code>ch</code> of <a href="#Channel_types">channel type</a>,
the value of the receive operation <code>&lt;-ch</code> is the value received
-from the channel <code>ch</code>. The type of the value is the element type of
-the channel. The expression blocks until a value is available.
+from the channel <code>ch</code>. The channel direction must permit receive operations,
+and the type of the receive operation is the element type of the channel.
+The expression blocks until a value is available.
Receiving from a <code>nil</code> channel blocks forever.
+Receiving from a <a href="#Close">closed</a> channel always succeeds,
+immediately returning the element type's <a href="#The_zero_value">zero
+value</a>.
</p>
<pre>
@@ -3204,11 +3300,11 @@ var x, ok = &lt;-ch
</pre>
<p>
-yields an additional result.
-The boolean variable <code>ok</code> indicates whether
-the received value was sent on the channel (<code>true</code>)
-or is a <a href="#The_zero_value">zero value</a> returned
-because the channel is closed and empty (<code>false</code>).
+yields an additional result of type <code>bool</code> reporting whether the
+communication succeeded. The value of <code>ok</code> is <code>true</code>
+if the value received was delivered by a successful send operation to the
+channel, or <code>false</code> if it is a zero value generated because the
+channel is closed and empty.
</p>
<!--
@@ -3230,7 +3326,7 @@ argument that is the receiver of the method.
<pre class="ebnf">
MethodExpr = ReceiverType "." MethodName .
-ReceiverType = TypeName | "(" "*" TypeName ")" .
+ReceiverType = TypeName | "(" "*" TypeName ")" | "(" ReceiverType ")" .
</pre>
<p>
@@ -3267,13 +3363,15 @@ func(tv T, a int) int
<p>
That function may be called normally with an explicit receiver, so
-these three invocations are equivalent:
+these five invocations are equivalent:
</p>
<pre>
t.Mv(7)
T.Mv(t, 7)
-f := T.Mv; f(t, 7)
+(T).Mv(t, 7)
+f1 := T.Mv; f1(t, 7)
+f2 := (T).Mv; f2(t, 7)
</pre>
<p>
@@ -3345,18 +3443,25 @@ that can be converted to type <code>T</code>.
</p>
<pre class="ebnf">
-Conversion = Type "(" Expression ")" .
+Conversion = Type "(" Expression [ "," ] ")" .
</pre>
<p>
-If the type starts with an operator it must be parenthesized:
+If the type starts with the operator <code>*</code> or <code>&lt;-</code>,
+or if the type starts with the keyword <code>func</code>
+and has no result list, it must be parenthesized when
+necessary to avoid ambiguity:
</p>
<pre>
*Point(p) // same as *(Point(p))
-(*Point)(p) // p is converted to (*Point)
+(*Point)(p) // p is converted to *Point
&lt;-chan int(c) // same as &lt;-(chan int(c))
-(&lt;-chan int)(c) // c is converted to (&lt;-chan int)
+(&lt;-chan int)(c) // c is converted to &lt;-chan int
+func()(x) // function signature func() x
+(func())(x) // x is converted to func()
+(func() int)(x) // x is converted to func() int
+func() int(x) // x is converted to func() int (unambiguous)
</pre>
<p>
@@ -3369,6 +3474,14 @@ type <code>T</code> in any of these cases:
<code>x</code> is representable by a value of type <code>T</code>.
</li>
<li>
+ <code>x</code> is a floating-point constant,
+ <code>T</code> is a floating-point type,
+ and <code>x</code> is representable by a value
+ of type <code>T</code> after rounding using
+ IEEE 754 round-to-even rules.
+ The constant <code>T(x)</code> is the rounded value.
+ </li>
+ <li>
<code>x</code> is an integer constant and <code>T</code> is a
<a href="#String_types">string type</a>.
The same rule as for non-constant <code>x</code> applies in this case
@@ -3384,6 +3497,7 @@ Converting a constant yields a typed constant as result.
uint(iota) // iota value of type uint
float32(2.718281828) // 2.718281828 of type float32
complex128(1) // 1.0 + 0.0i of type complex128
+float32(0.49999999) // 0.5 of type float32
string('x') // "x" of type string
string(0x266c) // "♬" of type string
MyString("foo" + "bar") // "foobar" of type MyString
@@ -3419,12 +3533,11 @@ in any of these cases:
<code>x</code>'s type and <code>T</code> are both complex types.
</li>
<li>
- <code>x</code> is an integer or has type <code>[]byte</code> or
- <code>[]rune</code> and <code>T</code> is a string type.
+ <code>x</code> is an integer or a slice of bytes or runes
+ and <code>T</code> is a string type.
</li>
<li>
- <code>x</code> is a string and <code>T</code> is <code>[]byte</code> or
- <code>[]rune</code>.
+ <code>x</code> is a string and <code>T</code> is a slice of bytes or runes.
</li>
</ul>
@@ -3490,7 +3603,7 @@ the range of valid Unicode code points are converted to <code>"\uFFFD"</code>.
<pre>
string('a') // "a"
-string(-1) // "\ufffd" == "\xef\xbf\xbd "
+string(-1) // "\ufffd" == "\xef\xbf\xbd"
string(0xf8) // "\u00f8" == "ø" == "\xc3\xb8"
type MyString string
MyString(0x65e5) // "\u65e5" == "日" == "\xe6\x97\xa5"
@@ -3551,7 +3664,7 @@ MyRunes("白鵬翔") // []rune{0x767d, 0x9d6c, 0x7fd4}
<p>
Constant expressions may contain only <a href="#Constants">constant</a>
-operands and are evaluated at compile-time.
+operands and are evaluated at compile time.
</p>
<p>
@@ -3560,7 +3673,7 @@ wherever it is legal to use an operand of boolean, numeric, or string type,
respectively.
Except for shift operations, if the operands of a binary operation are
different kinds of untyped constants, the operation and, for non-boolean operations, the result use
-the kind that appears later in this list: integer, character, floating-point, complex.
+the kind that appears later in this list: integer, rune, floating-point, complex.
For example, an untyped integer constant divided by an
untyped complex constant yields an untyped complex constant.
</p>
@@ -3581,14 +3694,15 @@ complex, or string constant).
const a = 2 + 3.0 // a == 5.0 (untyped floating-point constant)
const b = 15 / 4 // b == 3 (untyped integer constant)
const c = 15 / 4.0 // c == 3.75 (untyped floating-point constant)
-const Θ float64 = 3/2 // Θ == 1.5 (type float64)
+const Θ float64 = 3/2 // Θ == 1.0 (type float64, 3/2 is integer division)
+const Π float64 = 3/2. // Π == 1.5 (type float64, 3/2. is float division)
const d = 1 &lt;&lt; 3.0 // d == 8 (untyped integer constant)
const e = 1.0 &lt;&lt; 3 // e == 8 (untyped integer constant)
const f = int32(1) &lt;&lt; 33 // f == 0 (type int32)
const g = float64(2) &gt;&gt; 1 // illegal (float64(2) is a typed floating-point constant)
const h = "foo" &gt; "bar" // h == true (untyped boolean constant)
const j = true // j == true (untyped boolean constant)
-const k = 'w' + 1 // k == 'x' (untyped character constant)
+const k = 'w' + 1 // k == 'x' (untyped rune constant)
const l = "hi" // l == "hi" (untyped string constant)
const m = string(k) // m == "x" (type string)
const Σ = 1 - 0.707i // (untyped complex constant)
@@ -3598,13 +3712,13 @@ const Φ = iota*1i - 1/1i // (untyped complex constant)
<p>
Applying the built-in function <code>complex</code> to untyped
-integer, character, or floating-point constants yields
+integer, rune, or floating-point constants yields
an untyped complex constant.
</p>
<pre>
-const ic = complex(0, c) // ic == 3.75i (untyped complex constant)
-const iΘ = complex(0, Θ) // iΘ == 1.5i (type complex128)
+const ic = complex(0, c) // ic == 3.75i (untyped complex constant)
+const iΘ = complex(0, Θ) // iΘ == 1.5i (type complex128)
</pre>
<p>
@@ -3614,8 +3728,16 @@ by any predeclared type in the language. The following are legal declarations:
</p>
<pre>
-const Huge = 1 &lt;&lt; 100
-const Four int8 = Huge &gt;&gt; 98
+const Huge = 1 &lt;&lt; 100 // Huge == 1267650600228229401496703205376 (untyped integer constant)
+const Four int8 = Huge &gt;&gt; 98 // Four == 4 (type int8)
+</pre>
+
+<p>
+The divisor of a constant division or remainder operation must not be zero:
+</p>
+
+<pre>
+3.14 / 0.0 // illegal: division by zero
</pre>
<p>
@@ -3626,9 +3748,9 @@ of the constant type. The following constant expressions are illegal:
<pre>
uint(-1) // -1 cannot be represented as a uint
int(3.14) // 3.14 cannot be represented as an int
-int64(Huge) // 1&lt;&lt;100 cannot be represented as an int64
-Four * 300 // 300 cannot be represented as an int8
-Four * 100 // 400 cannot be represented as an int8
+int64(Huge) // 1267650600228229401496703205376 cannot be represented as an int64
+Four * 300 // operand 300 cannot be represented as an int8 (type of Four)
+Four * 100 // product 400 cannot be represented as an int8 (type of Four)
</pre>
<p>
@@ -3639,7 +3761,7 @@ and -1 for signed and untyped constants.
<pre>
^1 // untyped integer constant, equal to -2
-uint8(^1) // error, same as uint8(-2), out of range
+uint8(^1) // illegal: same as uint8(-2), -2 cannot be represented as a uint8
^uint8(1) // typed uint8 constant, same as 0xFF ^ uint8(1) = uint8(0xFE)
int8(^1) // same as int8(-2)
^int8(1) // same as -1 ^ int8(1) = -2
@@ -3668,8 +3790,10 @@ overflow etc. errors being caught.
<h3 id="Order_of_evaluation">Order of evaluation</h3>
<p>
-When evaluating the elements of an assignment or expression,
-all function calls, method calls and
+When evaluating the <a href="#Operands">operands</a> of an expression,
+<a href="#Assignments">assignment</a>, or
+<a href="#Return_statements">return statement</a>,
+all function calls, method calls, and
communication operations are evaluated in lexical left-to-right
order.
</p>
@@ -3689,6 +3813,12 @@ and indexing of <code>x</code> and the evaluation
of <code>y</code> is not specified.
</p>
+<pre>
+a := 1
+f := func() int { a = 2; return 3 }
+x := []int{a, f()} // x may be [1, 3] or [2, 3]: evaluation order between a and f() is not specified
+</pre>
+
<p>
Floating-point operations within a single expression are evaluated according to
the associativity of the operators. Explicit parentheses affect the evaluation
@@ -3745,7 +3875,9 @@ Error: log.Panic("error encountered")
<h3 id="Expression_statements">Expression statements</h3>
<p>
-Function calls, method calls, and receive operations
+With the exception of specific built-in functions,
+function and method <a href="#Calls">calls</a> and
+<a href="#Receive_operator">receive operations</a>
can appear in statement context. Such statements may be parenthesized.
</p>
@@ -3753,11 +3885,21 @@ can appear in statement context. Such statements may be parenthesized.
ExpressionStmt = Expression .
</pre>
+<p>
+The following built-in functions are not permitted in statement context:
+</p>
+
+<pre>
+append cap complex imag len make new real
+unsafe.Alignof unsafe.Offsetof unsafe.Sizeof
+</pre>
+
<pre>
h(x+y)
f.Close()
&lt;-ch
(&lt;-ch)
+len("foo") // illegal if len is the built-in function
</pre>
@@ -3765,8 +3907,9 @@ f.Close()
<p>
A send statement sends a value on a channel.
-The channel expression must be of <a href="#Channel_types">channel type</a>
-and the type of the value must be <a href="#Assignability">assignable</a>
+The channel expression must be of <a href="#Channel_types">channel type</a>,
+the channel direction must permit send operations,
+and the type of the value to be sent must be <a href="#Assignability">assignable</a>
to the channel's element type.
</p>
@@ -3884,7 +4027,7 @@ operand on the left.
<p>
The assignment proceeds in two phases.
-First, the operands of <a href="#Indexes">index expressions</a>
+First, the operands of <a href="#Index_expressions">index expressions</a>
and <a href="#Address_operators">pointer indirections</a>
(including implicit pointer indirections in <a href="#Selectors">selectors</a>)
on the left and the expressions on the right are all
@@ -3926,7 +4069,7 @@ is assigned to a variable of interface type, the constant is <a href="#Conversio
to type <code>bool</code>, <code>rune</code>, <code>int</code>, <code>float64</code>,
<code>complex128</code> or <code>string</code>
respectively, depending on whether the value is a
-boolean, character, integer, floating-point, complex, or string constant.
+boolean, rune, integer, floating-point, complex, or string constant.
</p>
@@ -4011,12 +4154,14 @@ ExprSwitchCase = "case" ExpressionList | "default" .
</pre>
<p>
-In a case or default clause,
-the last statement only may be a "fallthrough" statement
-(§<a href="#Fallthrough_statements">Fallthrough statement</a>) to
+In a case or default clause, the last non-empty statement
+may be a (possibly <a href="#Labeled_statements">labeled</a>)
+<a href="#Fallthrough_statements">"fallthrough" statement</a> 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.
</p>
<p>
@@ -4049,9 +4194,20 @@ case x == 4: f3()
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 <a href="#Type_assertions">type assertion</a>
-using the reserved word <code>type</code> rather than an actual type.
-Cases then match literal types against the dynamic type of the expression
-in the type assertion.
+using the reserved word <code>type</code> rather than an actual type:
+</p>
+
+<pre>
+switch x.(type) {
+// cases
+}
+</pre>
+
+<p>
+Cases then match actual types <code>T</code> against the dynamic type of the
+expression <code>x</code>. As with type assertions, <code>x</code> must be of
+<a href="#Interface_types">interface type</a>, and each non-interface type
+<code>T</code> listed in a case must implement the type of <code>x</code>.
</p>
<pre class="ebnf">
@@ -4087,17 +4243,17 @@ the following type switch:
<pre>
switch i := x.(type) {
case nil:
- printString("x is nil")
+ printString("x is nil") // type of i is type of x (interface{})
case int:
- printInt(i) // i is an int
+ printInt(i) // type of i is int
case float64:
- printFloat64(i) // i is a float64
+ printFloat64(i) // type of i is float64
case func(int) float64:
- printFunction(i) // i is a function
+ printFunction(i) // type of i is func(int) float64
case bool, string:
- printString("type is bool or string") // i is an interface{}
+ printString("type is bool or string") // type of i is type of x (interface{})
default:
- printString("don't know the type")
+ printString("don't know the type") // type of i is type of x (interface{})
}
</pre>
@@ -4108,22 +4264,23 @@ could be rewritten:
<pre>
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) // i is an int
+ printInt(i) // type of i is int
} else if i, isFloat64 := v.(float64); isFloat64 {
- printFloat64(i) // i is a float64
+ printFloat64(i) // type of i is float64
} else if i, isFunc := v.(func(int) float64); isFunc {
- printFunction(i) // i is a function
+ printFunction(i) // type of i is func(int) float64
} else {
- i1, isBool := v.(bool)
- i2, isString := v.(string)
+ _, isBool := v.(bool)
+ _, isString := v.(string)
if isBool || isString {
- i := v
- printString("type is bool or string") // i is an interface{}
+ i := v // type of i is type of x (interface{})
+ printString("type is bool or string")
} else {
- i := v
- printString("don't know the type") // i is an interface{}
+ i := v // type of i is type of x (interface{})
+ printString("don't know the type")
}
}
</pre>
@@ -4206,24 +4363,31 @@ to corresponding <i>iteration variables</i> and then executes the block.
</p>
<pre class="ebnf">
-RangeClause = Expression [ "," Expression ] ( "=" | ":=" ) "range" Expression .
+RangeClause = ( ExpressionList "=" | IdentifierList ":=" ) "range" Expression .
</pre>
<p>
The expression on the right in the "range" clause is called the <i>range expression</i>,
-which may be an array, pointer to an array, slice, string, map, or channel.
+which may be an array, pointer to an array, slice, string, map, or channel permitting
+<a href="#Receive_operator">receive operations</a>.
As with an assignment, the operands on the left must be
<a href="#Address_operators">addressable</a> 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.
-If the second iteration variable is the <a href="#Blank_identifier">blank identifier</a>,
+one iteration variable is permitted, otherwise there may be one or two. In the latter case,
+if the second iteration variable is the <a href="#Blank_identifier">blank identifier</a>,
the range clause is equivalent to the same clause with only the first variable present.
</p>
<p>
-The range expression is evaluated once before beginning the loop
-except if the expression is an array, in which case, depending on
-the expression, it might not be evaluated (see below).
+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 constant by definition
+(see §<a href="#Length_and_capacity">Length and capacity</a>),
+the range expression itself will not be evaluated.
+</p>
+
+<p>
Function calls on the left are evaluated once per iteration.
For each iteration, iteration values are produced as follows:
</p>
@@ -4234,14 +4398,14 @@ Range expression 1st value 2nd value (if 2nd v
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 element e E
+channel c chan E, &lt;-chan E element e E
</pre>
<ol>
<li>
For an array, pointer to array, or slice value <code>a</code>, the index iteration
-values are produced in increasing order, starting at element index 0. As a special
-case, if only the first iteration variable is present, the range loop produces
+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 to <code>len(a)</code> and does not index into the array
or slice itself. For a <code>nil</code> slice, the number of iterations is 0.
</li>
@@ -4260,11 +4424,12 @@ a single byte in the string.
<li>
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 deleted during iteration,
+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
-inserted during iteration, the behavior is implementation-dependent, but the
-iteration values for each entry will be produced at most once. If the map
-is <code>nil</code>, the number of iterations is 0.
+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 <code>nil</code>, the number of iterations is 0.
</li>
<li>
@@ -4327,7 +4492,7 @@ for w := range ch {
<h3 id="Go_statements">Go statements</h3>
<p>
-A "go" statement starts the execution of a function or method call
+A "go" statement starts the execution of a function call
as an independent concurrent thread of control, or <i>goroutine</i>,
within the same address space.
</p>
@@ -4337,7 +4502,12 @@ GoStmt = "go" Expression .
</pre>
<p>
-The expression must be a call.
+The expression must be a function or method call; it cannot be parenthesized.
+Calls of built-in functions are restricted as for
+<a href="#Expression_statements">expression statements</a>.
+</p>
+
+<p>
The function value and parameters are
<a href="#Calls">evaluated as usual</a>
in the calling goroutine, but
@@ -4368,7 +4538,7 @@ cases all referring to communication operations.
SelectStmt = "select" "{" { CommClause } "}" .
CommClause = CommCase ":" { Statement ";" } .
CommCase = "case" ( SendStmt | RecvStmt ) | "default" .
-RecvStmt = [ Expression [ "," Expression ] ( "=" | ":=" ) ] RecvExpr .
+RecvStmt = [ ExpressionList "=" | IdentifierList ":=" ] RecvExpr .
RecvExpr = Expression .
</pre>
@@ -4385,7 +4555,8 @@ 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.
+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-<code>nil</code> channels,
the statement blocks forever.
Even if the statement blocks,
@@ -4437,8 +4608,10 @@ select {} // block forever
<h3 id="Return_statements">Return statements</h3>
<p>
-A "return" statement terminates execution of the containing function
-and optionally provides a result value or values to the caller.
+A "return" statement in a function <code>F</code> terminates the execution
+of <code>F</code>, and optionally provides one or more result values.
+Any functions <a href="#Defer_statements">deferred</a> by <code>F</code>
+are executed before <code>F</code> returns to its caller.
</p>
<pre class="ebnf">
@@ -4488,7 +4661,7 @@ func complexF2() (re float64, im float64) {
</pre>
</li>
<li>The expression list may be empty if the function's result
- type specifies names for its result parameters (§<a href="#Function_types">Function Types</a>).
+ type specifies names for its result parameters (§<a href="#Function_types">Function types</a>).
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.
@@ -4508,7 +4681,10 @@ func (devnull) Write(p []byte) (n int, _ error) {
</ol>
<p>
-Regardless of how they are declared, all the result values are initialized to the zero values for their type (§<a href="#The_zero_value">The zero value</a>) upon entry to the function.
+Regardless of how they are declared, all the result values are initialized to the zero
+values for their type (§<a href="#The_zero_value">The zero value</a>) upon entry to the
+function. A "return" statement that specifies results sets the result parameters before
+any deferred functions are executed.
</p>
<!--
@@ -4534,7 +4710,8 @@ BreakStmt = "break" [ Label ] .
If there is a label, it must be that of an enclosing
"for", "switch" or "select" statement, and that is the one whose execution
terminates
-(§<a href="#For_statements">For statements</a>, §<a href="#Switch_statements">Switch statements</a>, §<a href="#Select_statements">Select statements</a>).
+(§<a href="#For_statements">For statements</a>, §<a href="#Switch_statements">Switch statements</a>,
+§<a href="#Select_statements">Select statements</a>).
</p>
<pre>
@@ -4623,9 +4800,8 @@ the "for" statement's block but the <code>goto</code> is not.
<p>
A "fallthrough" statement transfers control to the first statement of the
-next case clause in a expression "switch" statement (§<a href="#Expression_switches">Expression switches</a>). It may
-be used only as the final non-empty statement in a case or default clause in an
-expression "switch" statement.
+next case clause in a <a href="#Expression_switches">expression "switch" statement</a>.
+It may be used only as the final non-empty statement in such a clause.
</p>
<pre class="ebnf">
@@ -4636,8 +4812,11 @@ FallthroughStmt = "fallthrough" .
<h3 id="Defer_statements">Defer statements</h3>
<p>
-A "defer" statement invokes a function whose execution is deferred to the moment
-the surrounding function returns.
+A "defer" statement invokes a function whose execution is deferred
+to the moment the surrounding function returns, either because the
+surrounding function executed a <a href="#Return_statements">return statement</a>,
+reached the end of its <a href="#Function_declarations">function body</a>,
+or because the corresponding goroutine is <a href="#Handling_panics">panicking</a>.
</p>
<pre class="ebnf">
@@ -4645,22 +4824,30 @@ DeferStmt = "defer" Expression .
</pre>
<p>
-The expression must be a function or method call.
+The expression must be a function or method call; it cannot be parenthesized.
+Calls of built-in functions are restricted as for
+<a href="#Expression_statements">expression statements</a>.
+</p>
+
+<p>
Each time the "defer" statement
executes, the function value and parameters to the call are
<a href="#Calls">evaluated as usual</a>
-and saved anew but the
-actual function is not invoked.
-Instead, deferred calls are executed in LIFO order
-immediately before the surrounding function returns,
-after the return values, if any, have been evaluated, but before they
-are returned to the caller. For instance, if the deferred function is
+and saved anew but the actual function body is not executed.
+Instead, deferred functions are executed immediately before
+the surrounding function returns, in the reverse order
+they were deferred.
+</p>
+
+<p>
+For instance, if the deferred function is
a <a href="#Function_literals">function literal</a> and the surrounding
function has <a href="#Function_types">named result parameters</a> that
are in scope within the literal, the deferred function may access and modify
the result parameters before they are returned.
If the deferred function has any return values, they are discarded when
the function completes.
+(See also the section on <a href="#Handling_panics">handling panics</a>.)
</p>
<pre>
@@ -4698,7 +4885,7 @@ they cannot be used as function values.
<pre class="ebnf">
BuiltinCall = identifier "(" [ BuiltinArgs [ "," ] ] ")" .
-BuiltinArgs = Type [ "," ExpressionList ] | ExpressionList .
+BuiltinArgs = Type [ "," ArgumentList ] | ArgumentList .
</pre>
<h3 id="Close">Close</h3>
@@ -4750,7 +4937,8 @@ At any time the following relationship holds:
</pre>
<p>
-The length and capacity of a <code>nil</code> slice, map, or channel are 0.
+The length of a <code>nil</code> slice, map or channel is 0.
+The capacity of a <code>nil</code> slice and channel is 0.
</p>
<p>
@@ -4822,15 +5010,20 @@ make(T, n) channel asynchronous channel of type T, buffer size n
<p>
-The arguments <code>n</code> and <code>m</code> must be of integer type.
-A <a href="#Run_time_panics">run-time panic</a> occurs if <code>n</code>
-is negative or larger than <code>m</code>, or if <code>n</code> or
-<code>m</code> cannot be represented by an <code>int</code>.
+The size arguments <code>n</code> and <code>m</code> must be integer values.
+A <a href="#Constants">constant</a> size argument must be non-negative and
+representable by a value of type <code>int</code>.
+If both <code>n</code> and <code>m</code> are provided and are constant, then
+<code>n</code> must be no larger than <code>m</code>.
+If <code>n</code> is negative or larger than <code>m</code> at run time,
+a <a href="#Run_time_panics">run-time panic</a> occurs.
</p>
<pre>
s := make([]int, 10, 100) // slice with len(s) == 10, cap(s) == 100
-s := make([]int, 10) // slice with len(s) == cap(s) == 10
+s := make([]int, 1e3) // slice with len(s) == cap(s) == 1000
+s := make([]int, 1&lt;&lt;63) // illegal: len(s) is not representable by a value of type int
+s := make([]int, 10, 0) // illegal: len(s) > cap(s)
c := make(chan int, 10) // channel with a buffer size of 10
m := make(map[string]int, 100) // map with initial space for 100 elements
</pre>
@@ -4839,7 +5032,10 @@ m := make(map[string]int, 100) // map with initial space for 100 elements
<h3 id="Appending_and_copying_slices">Appending to and copying slices</h3>
<p>
-Two built-in functions assist in common slice operations.
+The built-in functions <code>append</code> and <code>copy</code> assist in
+common slice operations.
+For both functions, the result is independent of whether the memory referenced
+by the arguments overlaps.
</p>
<p>
@@ -4870,21 +5066,22 @@ slice may refer to a different underlying array.
<pre>
s0 := []int{0, 0}
-s1 := append(s0, 2) // append a single element s1 == []int{0, 0, 2}
-s2 := append(s1, 3, 5, 7) // append multiple elements s2 == []int{0, 0, 2, 3, 5, 7}
-s3 := append(s2, s0...) // append a slice s3 == []int{0, 0, 2, 3, 5, 7, 0, 0}
+s1 := append(s0, 2) // append a single element s1 == []int{0, 0, 2}
+s2 := append(s1, 3, 5, 7) // append multiple elements s2 == []int{0, 0, 2, 3, 5, 7}
+s3 := append(s2, s0...) // append a slice s3 == []int{0, 0, 2, 3, 5, 7, 0, 0}
+s4 := append(s3[3:6], s3[2:]...) // append overlapping slice s4 == []int{3, 5, 7, 2, 3, 5, 7, 0, 0}
var t []interface{}
-t = append(t, 42, 3.1415, "foo") t == []interface{}{42, 3.1415, "foo"}
+t = append(t, 42, 3.1415, "foo") t == []interface{}{42, 3.1415, "foo"}
var b []byte
-b = append(b, "bar"...) // append string contents b == []byte{'b', 'a', 'r' }
+b = append(b, "bar"...) // append string contents b == []byte{'b', 'a', 'r' }
</pre>
<p>
The function <code>copy</code> copies slice elements from
a source <code>src</code> to a destination <code>dst</code> and returns the
-number of elements copied. Source and destination may overlap.
+number of elements copied.
Both arguments must have <a href="#Type_identity">identical</a> element type <code>T</code> and must be
<a href="#Assignability">assignable</a> to a slice of type <code>[]T</code>.
The number of elements copied is the minimum of
@@ -4927,9 +5124,8 @@ delete(m, k) // remove element m[k] from map m
</pre>
<p>
-If the element <code>m[k]</code> does not exist, <code>delete</code> is
-a no-op. Calling <code>delete</code> with a nil map causes a
-<a href="#Run_time_panics">run-time panic</a>.
+If the map <code>m</code> is <code>nil</code> or the element <code>m[k]</code>
+does not exist, <code>delete</code> is a no-op.
</p>
@@ -4988,18 +5184,16 @@ func recover() interface{}
</pre>
<p>
-When a function <code>F</code> calls <code>panic</code>, normal
-execution of <code>F</code> stops immediately. Any functions whose
-execution was <a href="#Defer_statements">deferred</a> by the
-invocation of <code>F</code> are run in the usual way, and then
-<code>F</code> returns to its caller. To the caller, <code>F</code>
-then behaves like a call to <code>panic</code>, terminating its own
-execution and running deferred functions. This continues until all
-functions in the goroutine have ceased execution, in reverse order.
-At that point, the program is
-terminated and the error condition is reported, including the value of
-the argument to <code>panic</code>. This termination sequence is
-called <i>panicking</i>.
+A <code>panic</code> call in a function <code>F</code> terminates the execution
+of <code>F</code>.
+Any functions <a href="#Defer_statements">deferred</a> by <code>F</code>
+are executed before <code>F</code> returns to its caller. To the caller,
+the call of <code>F</code> then behaves itself like a call to <code>panic</code>,
+terminating its own execution and running deferred functions in the same manner.
+This continues until all functions in the goroutine have ceased execution,
+in reverse order. At that point, the program is terminated and the error
+condition is reported, including the value of the argument to <code>panic</code>.
+This termination sequence is called <i>panicking</i>.
</p>
<pre>
@@ -5112,7 +5306,7 @@ An implementation may require that all source files for a package inhabit the sa
An import declaration states that the source file containing the declaration
depends on functionality of the <i>imported</i> package
(<a href="#Program_initialization_and_execution">§Program initialization and execution</a>)
-and it enables access to <a href="#Exported_identifiers">exported</a> identifiers
+and enables access to <a href="#Exported_identifiers">exported</a> identifiers
of that package.
The import names an identifier (PackageName) to be used for access and an ImportPath
that specifies the package to be imported.
@@ -5145,7 +5339,7 @@ package and may be relative to a repository of installed packages.
<p>
Implementation restriction: A compiler may restrict ImportPaths to
non-empty strings using only characters belonging to
-<a href="http://www.unicode.org/versions/Unicode6.0.0/">Unicode's</a>
+<a href="http://www.unicode.org/versions/Unicode6.2.0/">Unicode's</a>
L, M, N, P, and S general categories (the Graphic characters without
spaces) and may also exclude the characters
<code>!"#$%&amp;'()*,:;&lt;=&gt;?[\]^`{|}</code>
@@ -5166,7 +5360,7 @@ various types of import declaration.
Import declaration Local name of Sin
import "lib/math" math.Sin
-import M "lib/math" M.Sin
+import m "lib/math" m.Sin
import . "lib/math" Sin
</pre>
@@ -5292,8 +5486,10 @@ func init()
</pre>
<p>
defined in its source.
-A package may contain multiple
-<code>init</code> functions, even
+A package-scope or file-scope identifier
+with name <code>init</code> may only be
+declared to be a function with this signature.
+Multiple such functions may be defined, even
within a single source file; they execute
in unspecified order.
</p>
@@ -5430,16 +5626,26 @@ func Sizeof(variable ArbitraryType) uintptr
</pre>
<p>
-Any pointer or value of <a href="#Types">underlying type</a> <code>uintptr</code> can be converted into
-a <code>Pointer</code> and vice versa.
+Any pointer or value of <a href="#Types">underlying type</a> <code>uintptr</code> can be converted to
+a <code>Pointer</code> type and vice versa.
</p>
+
+<pre>
+var f float64
+bits = *(*uint64)(unsafe.Pointer(&amp;f))
+
+type ptr unsafe.Pointer
+bits = *(*uint64)(ptr(&amp;f))
+</pre>
+
<p>
-The function <code>Sizeof</code> takes an expression denoting a
-variable of any type and returns the size of the variable in bytes.
+The functions <code>Alignof</code> and <code>Sizeof</code> take an expression <code>x</code>
+of any type and return the alignment or size, respectively, of a hypothetical variable <code>v</code>
+as if <code>v</code> was declared via <code>var v = x</code>.
</p>
<p>
-The function <code>Offsetof</code> takes a selector (§<a href="#Selectors">Selectors</a>) denoting a struct
-field of any type and returns the field offset in bytes relative to the
+The function <code>Offsetof</code> takes a (possibly parenthesized) <a href="#Selectors">selector</a>
+denoting a struct field of any type and returns the field offset in bytes relative to the
struct's address.
For a struct <code>s</code> with field <code>f</code>:
</p>
@@ -5465,7 +5671,6 @@ uintptr(unsafe.Pointer(&amp;x)) % unsafe.Alignof(x) == 0
Calls to <code>Alignof</code>, <code>Offsetof</code>, and
<code>Sizeof</code> are compile-time constant expressions of type <code>uintptr</code>.
</p>
-<p>
<h3 id="Size_and_alignment_guarantees">Size and alignment guarantees</h3>