diff options
Diffstat (limited to 'doc/go_spec.html')
-rw-r--r-- | doc/go_spec.html | 497 |
1 files changed, 302 insertions, 195 deletions
diff --git a/doc/go_spec.html b/doc/go_spec.html index f296c2a38..e1c7e90e2 100644 --- a/doc/go_spec.html +++ b/doc/go_spec.html @@ -1,5 +1,5 @@ <!-- title The Go Programming Language Specification --> -<!-- subtitle Version of June 7, 2010 --> +<!-- subtitle Version of January 7, 2011 --> <!-- TODO @@ -14,7 +14,6 @@ TODO [ ] should string(1<<s) and float(1<<s) be valid? [ ] should probably write something about evaluation order of statements even though obvious -[ ] specify iteration direction for range clause [ ] review language on implicit dereferencing [ ] clarify what it means for two functions to be "the same" when comparing them --> @@ -139,7 +138,7 @@ There are two forms of comments: <ol> <li> <i>Line comments</i> start with the character sequence <code>//</code> -and continue through the next newline. A line comment acts like a newline. +and stop at the end of the line. A line comment acts like a newline. </li> <li> <i>General comments</i> start with the character sequence <code>/*</code> @@ -163,7 +162,7 @@ and delimiters</i>, and <i>literals</i>. <i>White space</i>, 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 +that would otherwise combine into a single token. Also, a newline or end of file may trigger the insertion of a <a href="#Semicolons">semicolon</a>. While breaking the input into tokens, the next token is the longest sequence of characters that form a @@ -527,9 +526,10 @@ A constant value is represented by an <a href="#String_literals">string</a> literal, an identifier denoting a constant, a <a href="#Constant_expressions">constant expression</a>, or -the result value of some built-in functions such as <code>unsafe.Sizeof</code> -and <code>cap</code> or <code>len</code> applied to an array, -<code>len</code> applied to a string constant, +the result value of some built-in functions such as +<code>unsafe.Sizeof</code> applied to any value, +<code>cap</code> or <code>len</code> applied to +<a href="#Length_and_capacity">some expressions</a>, <code>real</code> and <code>imag</code> applied to a complex constant and <code>cmplx</code> applied to numeric constants. The boolean truth values are represented by the predeclared constants @@ -590,13 +590,13 @@ for floating-point values, both the mantissa and exponent must be twice as large <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_identifier">Qualified identifier</a>, §<a href="#Type_declarations">Type declarations</a>) or a <i>type literal</i>, +(§<a href="#Qualified_identifiers">Qualified identifier</a>, §<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 = QualifiedIdent . TypeLit = ArrayType | StructType | PointerType | FunctionType | InterfaceType | SliceType | MapType | ChannelType . </pre> @@ -754,8 +754,8 @@ ElementType = Type . 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 <code>len(a)</code>, which is a -compile-time constant. The elements can be indexed by integer +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 the <code>len(a)-1</code> (§<a href="#Indexes">Indexes</a>). Array types are always one-dimensional but may be composed to form multi-dimensional types. @@ -785,7 +785,7 @@ 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 -<code>len(s)</code>; unlike with arrays it may change during +<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 given element may be less than the index of the same element in the @@ -804,18 +804,14 @@ 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 by `slicing' a new one from the original slice (§<a href="#Slices">Slices</a>). The capacity of a slice <code>a</code> can be discovered using the -built-in function <code>cap(a)</code> and the relationship between -<code>len()</code> and <code>cap()</code> is: +built-in function <a href="#Length_and_capacity"><code>cap(a)</code></a>. </p> -<pre> -0 <= len(a) <= cap(a) -</pre> - <p> -The length and capacity of a <code>nil</code> slice -are 0. A new, initialized slice value for a given element type <code>T</code> is -made using the built-in function <code>make</code>, which takes a slice type +A new, initialized slice value for a given element type <code>T</code> is +made using the built-in function +<a href="#Making_slices_maps_and_channels"><code>make</code></a>, +which takes a slice type and parameters specifying the length and optionally the capacity: </p> @@ -883,9 +879,10 @@ struct { </pre> <p> -A field declared with a type but no explicit field name is an <i>anonymous field</i>. +A field declared with a type but no explicit field name is an <i>anonymous field</i> +(colloquially called an embedded field). Such a field type must be specified as -a type name <code>T</code> or as a pointer to a type name <code>*T</code>, +a type name <code>T</code> or as a pointer to a non-interface type name <code>*T</code>, and <code>T</code> itself may not be a pointer type. The unqualified type name acts as the field name. </p> @@ -959,7 +956,7 @@ struct { <p> A pointer type denotes the set of all pointers to variables of a given type, called the <i>base type</i> of the pointer. -The value of an unitialized pointer is <code>nil</code>. +The value of an uninitialized pointer is <code>nil</code>. </p> <pre class="ebnf"> @@ -976,7 +973,7 @@ BaseType = Type . <p> A function type denotes the set of all functions with the same parameter -and result types. The value of an unitialized variable of function type +and result types. The value of an uninitialized variable of function type is <code>nil</code>. </p> @@ -995,15 +992,14 @@ 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 lists are always parenthesized except that if there is exactly -one unnamed result it may written as an unparenthesized type. +one unnamed result it may be written as an unparenthesized type. </p> -<p> -If the function's last parameter has a type prefixed with <code>...</code>, -the function may be invoked with zero or more arguments for that parameter, -each of which must be <a href="#Assignability">assignable</a> -to the type that follows the <code>...</code>. -Such a function is called <i>variadic</i>. +<p> +The final parameter in a function signature may have +a type prefixed with <code>...</code>. +A function with such a parameter is called <i>variadic</i> and +may be invoked with zero or more arguments for that parameter. </p> <pre> @@ -1026,7 +1022,7 @@ An interface type specifies a <a href="#Types">method set</a> called its <i>inte 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 to <i>implement the interface</i>. -The value of an unitialized variable of interface type is <code>nil</code>. +The value of an uninitialized variable of interface type is <code>nil</code>. </p> <pre class="ebnf"> @@ -1155,16 +1151,16 @@ map [string] interface {} </pre> <p> -The number of elements is called the length and is never negative. -The length of a map <code>m</code> can be discovered using the -built-in function <code>len(m)</code> and may change during execution. -Values may be added and removed +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> +and may change during execution. Values may be added and removed during execution using special forms of <a href="#Assignments">assignment</a>. </p> <p> A new, empty map value is made using the built-in -function <code>make</code>, which takes the map type and an optional -capacity hint as arguments: +function <a href="#Making_slices_maps_and_channels"><code>make</code></a>, +which takes the map type and an optional capacity hint as arguments: </p> <pre> @@ -1331,9 +1327,9 @@ A value <code>x</code> is <i>assignable</i> to a variable of type <code>T</code> <code>x</code>'s type is identical to <code>T</code>. </li> <li> -<code>x</code>'s type <code>V</code> or <code>T</code> have identical -<a href="#Types">underlying types</a> and <code>V</code> or <code>T</code> -is not a named type. +<code>x</code>'s type <code>V</code> and <code>T</code> have identical +<a href="#Types">underlying types</a> and at least one of <code>V</code> +or <code>T</code> is not a named type. </li> <li> <code>T</code> is an interface type and @@ -1342,7 +1338,7 @@ is not a named type. <li> <code>x</code> is a bidirectional channel value, <code>T</code> is a channel type, <code>x</code>'s type <code>V</code> and <code>T</code> have identical element types, -and <code>V</code> or <code>T</code> is not a named type. +and at least one of <code>V</code> or <code>T</code> is not a named type. </li> <li> <code>x</code> is the predeclared identifier <code>nil</code> and <code>T</code> @@ -1496,8 +1492,8 @@ Zero value: nil Functions: - cap close closed cmplx copy imag len make - new panic print println real + append cap close closed cmplx copy imag len + make new panic print println real recover </pre> @@ -1665,7 +1661,7 @@ TypeSpec = identifier Type . type IntArray [16]int type ( - Point struct { x, y float } + Point struct { x, y float64 } Polar Point ) @@ -1835,7 +1831,7 @@ A function declaration binds an identifier to a function (§<a href="#Function_t <pre class="ebnf"> FunctionDecl = "func" identifier Signature [ Body ] . -Body = Block. +Body = Block . </pre> <p> @@ -1882,13 +1878,13 @@ Given type <code>Point</code>, the declarations </p> <pre> -func (p *Point) Length() float { - return Math.sqrt(p.x * p.x + p.y * p.y) +func (p *Point) Length() float64 { + return math.Sqrt(p.x * p.x + p.y * p.y) } -func (p *Point) Scale(factor float) { - p.x = p.x * factor - p.y = p.y * factor +func (p *Point) Scale(factor float64) { + p.x *= factor + p.y *= factor } </pre> @@ -1910,7 +1906,7 @@ argument. For instance, the method <code>Scale</code> has type </p> <pre> -(p *Point, factor float) +func(p *Point, factor float64) </pre> <p> @@ -1975,15 +1971,16 @@ a single expression or a key-value pair. </p> <pre class="ebnf"> -CompositeLit = LiteralType "{" [ ElementList [ "," ] ] "}" . +CompositeLit = LiteralType LiteralValue . LiteralType = StructType | ArrayType | "[" "..." "]" ElementType | - SliceType | MapType | TypeName | "(" LiteralType ")" . + SliceType | MapType | TypeName . +LiteralValue = "{" [ ElementList [ "," ] ] "}" . ElementList = Element { "," Element } . Element = [ Key ":" ] Value . Key = FieldName | ElementIndex . FieldName = identifier . ElementIndex = Expression . -Value = Expression . +Value = Expression | LiteralValue . </pre> <p> @@ -2028,8 +2025,8 @@ For struct literals the following rules apply: Given the declarations </p> <pre> -type Point struct { x, y, z float } -type Line struct { p, q Point } +type Point3D struct { x, y, z float64 } +type Line struct { p, q Point3D } </pre> <p> @@ -2037,8 +2034,8 @@ one may write </p> <pre> -origin := Point{} // zero value for Point -line := Line{origin, Point{y: -4, z: 12.3}} // zero value for line.q.x +origin := Point3D{} // zero value for Point3D +line := Line{origin, Point3D{y: -4, z: 12.3}} // zero value for line.q.x </pre> <p> @@ -2061,7 +2058,7 @@ Taking the address of a composite literal (§<a href="#Address_operators">Addres generates a unique pointer to an instance of the literal's value. </p> <pre> -var pointer *Point = &Point{y: 1000} +var pointer *Point3D = &Point3D{y: 1000} </pre> <p> @@ -2098,11 +2095,23 @@ and is a shortcut for a slice operation applied to an array literal: </pre> <p> +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>. +</p> + +<pre> +[...]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}} +</pre> + +<p> A parsing ambiguity arises when a composite literal using the -TypeName form of the LiteralType appears in the condition of an +TypeName form of the LiteralType appears between the +<a href="#Keywords">keyword</a> 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 -a block of statements. To resolve the ambiguity in this rare case, +the block of statements. To resolve the ambiguity in this rare case, the composite literal must appear within parentheses. </p> @@ -2185,9 +2194,10 @@ PrimaryExpr = Selector = "." identifier . Index = "[" Expression "]" . -Slice = "[" Expression ":" [ Expression ] "]" . +Slice = "[" [ Expression ] ":" [ Expression ] "]" . TypeAssertion = "." "(" Type ")" . -Call = "(" [ ExpressionList [ "," ] ] ")" . +Call = "(" [ ArgumentList [ "," ] ] ")" . +ArgumentList = ExpressionList [ "..." ] . </pre> @@ -2200,7 +2210,7 @@ Point{1, 2} m["foo"] s[i : j + 1] obj.color -Math.sin +math.Sin f.p[i].x() </pre> @@ -2217,8 +2227,7 @@ x.f <p> denotes the field or method <code>f</code> of the value denoted by <code>x</code> -(or of <code>*x</code> if -<code>x</code> is of pointer type). The identifier <code>f</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>. @@ -2261,16 +2270,13 @@ In all other cases, <code>x.f</code> is illegal. </li> </ol> <p> -Selectors automatically dereference pointers. -If <code>x</code> is of pointer type, <code>x.y</code> -is shorthand for <code>(*x).y</code>; if <code>y</code> -is also of pointer type, <code>x.y.z</code> is shorthand +Selectors automatically dereference 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 for <code>(*(*x).y).z</code>, and so on. -If <code>*x</code> is of pointer type, dereferencing -must be explicit; -only one level of automatic dereferencing is provided. -For an <code>x</code> of type <code>T</code> containing an -anonymous field declared as <code>*A</code>, +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> @@ -2428,14 +2434,14 @@ For a string, array, or slice <code>a</code>, the primary expression </p> <pre> -a[lo : hi] +a[low : high] </pre> <p> -constructs a substring or slice. The index expressions <code>lo</code> and -<code>hi</code> select which elements appear in the result. The result has +constructs a substring or slice. The index expressions <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 -<code>hi</code> - <code>lo</code>. +<code>high</code> - <code>low</code>. After slicing the array <code>a</code> </p> @@ -2455,19 +2461,28 @@ s[2] == 4 </pre> <p> -For convenience, the <code>hi</code> expression may be omitted; the notation -<code>a[lo :]</code> is shorthand for <code>a[lo : len(a)]</code>. -For arrays or strings, the indexes -<code>lo</code> and <code>hi</code> must satisfy -0 <= <code>lo</code> <= <code>hi</code> <= length; -for slices, the upper bound is the capacity rather than the length. +For convenience, any of the index expressions 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> + +<pre> +a[2:] // same a[2 : len(a)] +a[:3] // same as a[0 : 3] +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 <= <code>low</code> <= <code>high</code> <= length; for +slices, the upper bound is the capacity rather than the length. </p> <p> If the sliced operand is a string or slice, the result of the slice operation is a string or slice of the same type. -If the sliced operand is an array, the result of the slice operation is a slice -with the same element type as the array. +If the sliced operand is an array, it must be <a href="#Address_operators">addressable</a> +and the result of the slice operation is a slice with the same element type as the array. </p> @@ -2605,9 +2620,9 @@ then within the function the argument is equivalent to a parameter of type <code>[]T</code>. At each call of <code>f</code>, the argument passed to the final parameter is a new slice of type <code>[]T</code> whose successive elements are -the actual arguments. The length of the slice is therefore the -number of arguments bound to the final parameter and -may differ for each call site. +the actual arguments, which all must be <a href="#Assignability">assignable</a> +to the type <code>T</code>. The length of the slice is therefore the number of +arguments bound to the final parameter and may differ for each call site. </p> <p> @@ -2619,20 +2634,31 @@ Greeting("hello:", "Joe", "Anna", "Eileen") </pre> <p> -Within <code>Greeting</code>, <code>who</code> will have value -<code>[]string{"Joe", "Anna", "Eileen")</code> +within <code>Greeting</code>, <code>who</code> will have the value +<code>[]string{"Joe", "Anna", "Eileen"}</code> </p> +<p> +If the final argument is assignable to a slice type <code>[]T</code>, it may be +passed unchanged as the value for a <code>...T</code> parameter if the argument +is followed by <code>...</code>. In this case no new slice is created. +</p> <p> -As a special case, if a function passes its own <code>...</code> parameter -as the <code>...</code> argument in a call to another function with -a <code>...</code> parameter of <a href="#Type_identity">identical type</a>, -the parameter is passed directly. In short, a formal <code>...</code> -parameter is passed unchanged as an actual <code>...</code> parameter provided the -types match. +Given the slice <code>s</code> and call </p> +<pre> +s := []string{"James", "Jasmine"} +Greeting("goodbye:", s...) +</pre> + +<p> +within <code>Greeting</code>, <code>who</code> will have the same value as <code>s</code> +with the same underlying array. +</p> + + <h3 id="Operators">Operators</h3> <p> @@ -2903,7 +2929,7 @@ and string values. The result of a comparison is defined as follows: String values are compared byte-wise (lexically). </li> <li> - Boolean values are are equal if they are either both + Boolean values are equal if they are either both <code>true</code> or both <code>false</code>. </li> <li> @@ -3065,6 +3091,12 @@ to <code>false</code> and <code>x</code> is set to the zero value for its type (§<a href="#The_zero_value">The zero value</a>). </p> +<p> +Except in a communications clause of a <a href="#Select_statements">select statement</a>, +sending or receiving from a <code>nil</code> channel causes a +<a href="#Run_time_panics">run-time panic</a>. +</p> + <!--- <p> <span class="alert">TODO: Probably in a separate section, communication semantics @@ -3548,8 +3580,8 @@ f(x+y) <p> The "++" and "--" statements increment or decrement their operands by the untyped <a href="#Constants">constant</a> <code>1</code>. -As with an assignment, the operand must be a variable, pointer indirection, -field selector or index expression. +As with an assignment, the operand must be <a href="#Address_operators">addressable</a> +or a map index expression. </p> <pre class="ebnf"> @@ -3567,6 +3599,7 @@ x++ x += 1 x-- x -= 1 </pre> + <h3 id="Assignments">Assignments</h3> <pre class="ebnf"> @@ -3925,59 +3958,81 @@ for { S() } is the same as for true { S() } <p> 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 first assigns the current index or key to an iteration -variable - or the current (index, element) or (key, value) pair to a pair -of iteration variables - and then executes the block. +or values received on a channel. For each entry it assigns <i>iteration values</i> +to corresponding <i>iteration variables</i> and then executes the block. </p> <pre class="ebnf"> -RangeClause = ExpressionList ( "=" | ":=" ) "range" Expression . -</pre> - -<p> -The type of the right-hand expression in the "range" clause must be an -array, slice, string or map, or a pointer to an array; -or it may be a channel. -Except for channels, -the identifier list must contain one or two expressions -(as in assignments, these must be a -variable, pointer indirection, field selector, or index expression) -denoting the -iteration variables. On each iteration, -the first variable is set to the string, array or slice index or -map key, and the second variable, if present, is set to the corresponding -string or array element or map value. -The types of the array or slice index (always <code>int</code>) -and element, or of the map key and value respectively, -must be <a href="#Assignability">assignable</a> to -the type of the iteration variables. The expression on the right hand -side is evaluated once before beginning the loop. At each iteration -of the loop, the values produced by the range clause are assigned to -the left hand side as in an <a href="#Assignments">assignment -statement</a>. Function calls on the left hand side will be evaluated -exactly once per iteration. -</p> -<p> -For a value of a string type, the "range" clause iterates over the Unicode code points -in the string. On successive iterations, the index variable will be the -index of the first byte of successive UTF-8-encoded code points in the string, and -the second variable, of type <code>int</code>, will be the value of +RangeClause = Expression [ "," Expression ] ( "=" | ":=" ) "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. +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. +</p> + +<p> +The range expression is evaluated once before beginning the loop. +Function calls on the left are evaluated once per iteration. +For each iteration, iteration values are produced as follows: +</p> + +<pre class="grammar"> +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 int +map m map[K]V key k K m[k] V +channel c chan E element e E +</pre> + +<ol> +<li> +For an array or slice value, the index iteration values are produced in +increasing order, starting at element index 0. +</li> + +<li> +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 <code>int</code>, will be the value of the corresponding code point. If the iteration encounters an invalid -UTF-8 sequence, the second variable will be <code>0xFFFD</code>, +UTF-8 sequence, the second value will be <code>0xFFFD</code>, the Unicode replacement character, and the next iteration will advance a single byte in the string. -</p> +</li> + +<li> +The iteration order over maps is not specified. +If map entries that have not yet been reached are deleted 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. +</li> + +<li> +For channels, the iteration values produced are the successive values sent on +the channel until the channel is closed; it does not produce the zero value sent +before the channel is closed +(§<a href="#Close_and_closed"><code>close</code> and <code>closed</code></a>). +</li> +</ol + <p> -For channels, the identifier list must contain one identifier. -The iteration receives values sent on the channel until the channel is closed; -it does not process the zero value sent before the channel is closed. +The iteration values are assigned to the respective +iteration variables as in an <a href="#Assignments">assignment statement</a>. </p> + <p> -The iteration variables may be declared by the "range" clause (":="), in which -case their scope ends at the end of the "for" statement (§<a href="#Declarations_and">Declarations and</a> -scope rules). In this case their types are set to -<code>int</code> and the array element type, or the map key and value types, respectively. +The iteration variables may be declared by the "range" clause (<code>:=</code>). +In this case their types are set to the types of the respective iteration values +and their <a href="#Declarations_and_scope">scope</a> 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. </p> @@ -4002,11 +4057,6 @@ for key, val = range m { // val == map[key] </pre> -<p> -If map entries that have not yet been processed are deleted during iteration, -they will not be processed. If map entries are inserted during iteration, the -behavior is implementation-dependent, but each entry will be processed at most once. -</p> <h3 id="Go_statements">Go statements</h3> @@ -4050,18 +4100,22 @@ RecvExpr = [ Expression ( "=" | ":=" ) ] "<-" Expression . <p> For all the send and receive expressions in the "select" -statement, the channel expressions are evaluated, along with -any expressions that appear on the right hand side of send expressions, -in top-to-bottom order. -If any of the resulting operations can proceed, one is -chosen and the corresponding communication and statements are -evaluated. Otherwise, if there is a default case, that executes; -if not, the statement blocks until one of the communications can -complete. The channels and send expressions are not re-evaluated. -A channel pointer may be <code>nil</code>, +statement, the channel expressions are evaluated in top-to-bottom order, along with +any expressions that appear on the right hand side of send expressions. +A channel may be <code>nil</code>, 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. +If there are no cases with non-<code>nil</code> channels, +the statement blocks forever. +Even if the statement blocks, +the channel and send expressions are evaluated only once, +upon entering the select statement. </p> <p> Since all the channels and send expressions are evaluated, any side @@ -4069,7 +4123,7 @@ effects in that evaluation will occur for all the communications in the "select" statement. </p> <p> -If multiple cases can proceed, a uniform fair choice is made to decide +If multiple cases can proceed, a pseudo-random fair choice is made to decide which single communication will execute. <p> The receive case may declare a new variable using a @@ -4094,6 +4148,8 @@ for { // send random sequence of bits to c case c <- 1: } } + +select { } // block forever </pre> @@ -4150,7 +4206,7 @@ func complex_f2() (re float, im float) { } </pre> </li> - <li>The expression list may be empty if the functions's result + <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>). The result parameters act as ordinary local variables and the function may assign values to them as necessary. @@ -4331,21 +4387,24 @@ they cannot be used as function values. </p> <pre class="ebnf"> -BuiltinCall = identifier "(" [ BuiltinArgs ] ")" . +BuiltinCall = identifier "(" [ BuiltinArgs [ "," ] ] ")" . BuiltinArgs = Type [ "," ExpressionList ] | ExpressionList . </pre> <h3 id="Close_and_closed">Close and closed</h3> <p> -For a channel <code>c</code>, the predefined function <code>close(c)</code> -marks the channel as unable to accept more -values through a send operation. After any previously +For a channel <code>c</code>, the built-in function <code>close(c)</code> +marks the channel as unable to accept more values through a send operation; +values sent to a closed channel are ignored. +After calling <code>close</code>, and after any previously sent values have been received, receive operations will return -the zero value for the channel's type. After at least one such zero value has been +the zero value for the channel's type without blocking. +After at least one such zero value has been received, <code>closed(c)</code> returns true. </p> + <h3 id="Length_and_capacity">Length and capacity</h3> <p> @@ -4358,12 +4417,12 @@ The implementation guarantees that the result always fits into an <code>int</cod Call Argument type Result len(s) string type string length in bytes - [n]T, *[n]T array length (== constant n) + [n]T, *[n]T array length (== n) []T slice length map[K]T map length (number of defined keys) chan T number of elements queued in channel buffer -cap(s) [n]T, *[n]T array length (== constant n) +cap(s) [n]T, *[n]T array length (== n) []T slice capacity chan T channel buffer capacity </pre> @@ -4378,6 +4437,24 @@ At any time the following relationship holds: 0 <= len(s) <= cap(s) </pre> +<p> +The length and capacity of a <code>nil</code> slice, map, or channel are 0. +</p> + +<p> +The expression +<code>len(s)</code> is a +<a href="#Constants">constant</a> if <code>s</code> is a string constant. +The expressions +<code>len(s)</code> and +<code>cap(s)</code> are +constants if <code>s</code> is an (optionally parenthesized) +identifier or +<a href="#Qualified_identifiers">qualified identifier</a> +denoting an array or pointer to array. +Otherwise invocations of <code>len</code> and <code>cap</code> are not +constant. +</p> <h3 id="Allocation">Allocation</h3> @@ -4450,20 +4527,53 @@ m := make(map[string] int, 100) // map with initial space for 100 elements </pre> -<h3 id="Copying_slices">Copying slices</h3> +<h3 id="Appending_and_copying_slices">Appending to and copying slices</h3> + +<p> +Two built-in functions assist in common slice operations. +</p> + +<p> +The function <code>append</code> appends zero or more values <code>x</code> +to a slice <code>s</code> and returns the resulting slice, with the same type +as s. Each value must be <a href="#Assignability">assignable</a> to the slice's +element type. +</p> + +<pre class="grammar"> +append(s S, x ...T) S // S is assignable to []T +</pre> <p> -The built-in function <code>copy</code> copies slice elements from +If the capacity of <code>s</code> is not large enough to fit the additional +values, <code>append</code> allocates a new, sufficiently large slice that fits +both the existing slice elements and the additional values. Thus, the returned +slice may refer to a different underlying array. +</p> + +<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} +</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. 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 arguments copied is the minimum of +<a href="#Assignability">assignable</a> to a slice of type <code>[]T</code>. +The number of arguments copied is the minimum of <code>len(src)</code> and <code>len(dst)</code>. +As a special case, <code>copy</code> also accepts a destination argument assignable +to type <code>[]byte</code> with a source argument of a string type. +This form copies the bytes from the string into the byte slice. </p> <pre class="grammar"> copy(dst, src []T) int +copy(dst []byte, src string) int </pre> <p> @@ -4473,8 +4583,10 @@ Examples: <pre> var a = [...]int{0, 1, 2, 3, 4, 5, 6, 7} var s = make([]int, 6) -n1 := copy(s, a[0:]) // n1 == 6, s == []int{0, 1, 2, 3, 4, 5} -n2 := copy(s, s[2:]) // n2 == 4, s == []int{2, 3, 4, 5, 4, 5} +var b = make([]byte, 5) +n1 := copy(s, a[0:]) // n1 == 6, s == []int{0, 1, 2, 3, 4, 5} +n2 := copy(s, s[2:]) // n2 == 4, s == []int{2, 3, 4, 5, 4, 5} +n3 := copy(b, "Hello, World!") // n3 == 5, b == []byte("Hello") </pre> <h3 id="Complex_numbers">Assembling and disassembling complex numbers</h3> @@ -4533,10 +4645,10 @@ func recover() interface{} </pre> <p> -<font color=red>TODO: Most of this text could move to the respective +<span class="alert">TODO: Most of this text could move to the respective comments in <code>runtime.go</code> once the functions are implemented. They are here, at least for now, for reference and discussion. -</font> +</span> </p> <p> @@ -4630,8 +4742,9 @@ func IsPrintable(s string) (ok bool) { } // Panicking has stopped; execution will resume normally in caller. // The return value will be true normally, false if a panic occurred. - } + }() panicIfNotPrintable(s) // will panic if validations fails. + return } </pre> @@ -5086,27 +5199,24 @@ For the numeric types (§<a href="#Numeric_types">Numeric types</a>), the follow </p> <pre class="grammar"> -type size in bytes +type size in bytes -byte, uint8, int8 1 -uint16, int16 2 -uint32, int32, float32 4 -uint64, int64, float64 8 +byte, uint8, int8 1 +uint16, int16 2 +uint32, int32, float32 4 +uint64, int64, float64, complex64 8 +complex128 16 </pre> <p> The following minimal alignment properties are guaranteed: </p> <ol> -<li>For a variable <code>x</code> of any type: <code>1 <= unsafe.Alignof(x) <= unsafe.Maxalign</code>. -</li> - -<li>For a variable <code>x</code> of numeric type: <code>unsafe.Alignof(x)</code> is the smaller - of <code>unsafe.Sizeof(x)</code> and <code>unsafe.Maxalign</code>, but at least 1. +<li>For a variable <code>x</code> of any type: <code>unsafe.Alignof(x)</code> is at least 1. </li> <li>For a variable <code>x</code> of struct type: <code>unsafe.Alignof(x)</code> is the largest of - all the values <code>unsafe.Alignof(x.f)</code> for each field <code>f</code> of x, but at least 1. + all the values <code>unsafe.Alignof(x.f)</code> for each field <code>f</code> of <code>x</code>, but at least 1. </li> <li>For a variable <code>x</code> of array type: <code>unsafe.Alignof(x)</code> is the same as @@ -5117,10 +5227,7 @@ The following minimal alignment properties are guaranteed: <h2 id="Implementation_differences"><span class="alert">Implementation differences - TODO</span></h2> <ul> <li><span class="alert">Implementation does not honor the restriction on goto statements and targets (no intervening declarations).</span></li> - <li><span class="alert">Method expressions are partially implemented.</span></li> + <li><span class="alert">Gccgo: The <code>append</code> built-in function is not yet implemented.</span></li> + <li><span class="alert">Gccgo: Method expressions are partially implemented.</span></li> <li><span class="alert">Gccgo: allows only one init() function per source file.</span></li> - <li><span class="alert">Gccgo: Deferred functions cannot access the surrounding function's result parameters.</span></li> - <li><span class="alert">Gccgo: Function results are not addressable.</span></li> - <li><span class="alert">Gccgo: Recover is not implemented.</span></li> - <li><span class="alert">Gccgo: The implemented version of panic differs from its specification.</span></li> </ul> |