summaryrefslogtreecommitdiff
path: root/doc
diff options
context:
space:
mode:
Diffstat (limited to 'doc')
-rw-r--r--doc/contribute.html7
-rw-r--r--doc/effective_go.html748
-rw-r--r--doc/go1.1.html722
-rw-r--r--doc/go_faq.html85
-rw-r--r--doc/go_spec.html444
-rw-r--r--doc/progs/eff_unused1.go18
-rw-r--r--doc/progs/eff_unused2.go22
-rwxr-xr-xdoc/progs/run1
-rw-r--r--doc/progs/unused1.go12
-rw-r--r--doc/progs/unused2.go16
10 files changed, 1662 insertions, 413 deletions
diff --git a/doc/contribute.html b/doc/contribute.html
index 72c936472..c659de617 100644
--- a/doc/contribute.html
+++ b/doc/contribute.html
@@ -117,6 +117,13 @@ enabled for your checkout in <code>$GOROOT</code>, the remainder of this
document assumes you are inside <code>$GOROOT</code> when issuing commands.
</p>
+<p>
+Windows users may need to perform extra steps to get the code review
+extension working. See the
+<a href="https://code.google.com/p/go-wiki/wiki/CodeReview">CodeReview page</a>
+on the <a href="http://code.google.com/p/go-wiki/wiki">Go Wiki</a> for details.
+</p>
+
<h3>Log in to the code review site.</h3>
<p>
diff --git a/doc/effective_go.html b/doc/effective_go.html
index e02694add..decca34b5 100644
--- a/doc/effective_go.html
+++ b/doc/effective_go.html
@@ -696,10 +696,18 @@ for _, value := range array {
</pre>
<p>
+The blank identifier has many uses, as described in <a href="#blank">a later section</a>.
+
+<p>
For strings, the <code>range</code> does more work for you, breaking out individual
Unicode code points by parsing the UTF-8.
Erroneous encodings consume one byte and produce the
-replacement rune U+FFFD. The loop
+replacement rune U+FFFD.
+(The name (with associated builtin type) <code>rune</code> is Go terminology for a
+single Unicode code point.
+See <a href="http://golang.org/ref/spec#Rune_literals">the language specification</a>
+for details.)
+The loop
</p>
<pre>
for pos, char := range "日本\x80語" { // \x80 is an illegal UTF-8 encoding
@@ -797,6 +805,8 @@ func Compare(a, b []byte) int {
}
</pre>
+<h2 id="type_switch">Type switch</h2>
+
<p>
A switch can also be used to discover the dynamic type of an interface
variable. Such a <em>type switch</em> uses the syntax of a type
@@ -831,8 +841,8 @@ case *int:
One of Go's unusual features is that functions and methods
can return multiple values. This form can be used to
improve on a couple of clumsy idioms in C programs: in-band
-error returns (such as <code>-1</code> for <code>EOF</code>)
-and modifying an argument.
+error returns such as <code>-1</code> for <code>EOF</code>
+and modifying an argument passed by address.
</p>
<p>
@@ -841,7 +851,8 @@ error code secreted away in a volatile location.
In Go, <code>Write</code>
can return a count <i>and</i> an error: &ldquo;Yes, you wrote some
bytes but not all of them because you filled the device&rdquo;.
-The signature of <code>File.Write</code> in package <code>os</code> is:
+The signature of the <code>Write</code> method on files from
+package <code>os</code> is:
</p>
<pre>
@@ -1208,7 +1219,7 @@ It creates slices, maps, and channels only, and it returns an <em>initialized</e
(not <em>zeroed</em>)
value of type <code>T</code> (not <code>*T</code>).
The reason for the distinction
-is that these three types are, under the covers, references to data structures that
+is that these three types represent, under the covers, references to data structures that
must be initialized before use.
A slice, for example, is a three-item descriptor
containing a pointer to the data (inside an array), the length, and the
@@ -1253,7 +1264,8 @@ v := make([]int, 100)
<p>
Remember that <code>make</code> applies only to maps, slices and channels
and does not return a pointer.
-To obtain an explicit pointer allocate with <code>new</code>.
+To obtain an explicit pointer allocate with <code>new</code> or take the address
+of a variable explicitly.
</p>
<h3 id="arrays">Arrays</h3>
@@ -1300,7 +1312,8 @@ x := Sum(&amp;array) // Note the explicit address-of operator
</pre>
<p>
-But even this style isn't idiomatic Go. Slices are.
+But even this style isn't idiomatic Go.
+Use slices instead.
</p>
<h3 id="slices">Slices</h3>
@@ -1312,9 +1325,9 @@ dimension such as transformation matrices, most array programming in
Go is done with slices rather than simple arrays.
</p>
<p>
-Slices are <i>reference types</i>, which means that if you assign one
-slice to another, both refer to the same underlying array. For
-instance, if a function takes a slice argument, changes it makes to
+Slices hold references to an underlying array, and if you assign one
+slice to another, both refer to the same array.
+If a function takes a slice argument, changes it makes to
the elements of the slice will be visible to the caller, analogous to
passing a pointer to the underlying array. A <code>Read</code>
function can therefore accept a slice argument rather than a pointer
@@ -1391,19 +1404,87 @@ design, though, we need a little more information, so we'll return
to it later.
</p>
+<h3 id="two_dimensional_slices">Two-dimensional slices</h3>
+
+<p>
+Go's arrays and slices are one-dimensional.
+To create the equivalent of a 2D array or slice, it is necessary to define an array-of-arrays
+or slice-of-slices, like this:
+</p>
+
+<pre>
+type Transform [3][3]float64 // A 3x3 array, really an array of arrays.
+type LinesOfText [][]byte // A slice of byte slices.
+</pre>
+
+<p>
+Because slices are variable-length, it is possible to have each inner
+slice be a different length.
+That can be a common situation, as in our <code>LinesOfText</code>
+example: each line has an independent length.
+</p>
+
+<pre>
+text := LinesOfText{
+ []byte("Now is the time"),
+ []byte("for all good gophers"),
+ []byte("to bring some fun to the party."),
+}
+</pre>
+
+<p>
+Sometimes it's necessary to allocate a 2D slice, a situation that can arise when
+processing scan lines of pixels, for instance.
+There are two ways to achieve this.
+One is to allocate each slice independently; the other
+is to allocate a single array and point the individual slices into it.
+Which to use depends on your application.
+If the slices might grow or shrink, they should be allocated independently
+to avoid overwriting the next line; if not, it can be more efficient to construct
+the object with a single allocation.
+For reference, here are sketches of the two methods.
+First, a line a time:
+</p>
+
+<pre>
+// Allocate the top-level slice.
+picture := make([][]uint8, YSize) // One row per unit of y.
+// Loop over the rows, allocating the slice for each row.
+for i := range picture {
+ picture[i] = make([]uint8, XSize)
+}
+</pre>
+
+<p>
+And now as one allocation, sliced into lines:
+</p>
+
+<pre>
+// Allocate the top-level slice, the same as before.
+picture := make([][]uint8, YSize) // One row per unit of y.
+// Allocate one large slice to hold all the pixels.
+pixels := make([]uint8, XSize*YSize) // Has type []uint8 even though picture is [][]uint8.
+// Loop over the rows, slicing each row from the front of the remaining pixels slice.
+for i := range picture {
+ picture[i], pixels = pixels[:XSize], pixels[XSize:]
+}
+</pre>
<h3 id="maps">Maps</h3>
<p>
-Maps are a convenient and powerful built-in data structure to associate
-values of different types.
+Maps are a convenient and powerful built-in data structure that associate
+values of one type (the <em>key</em>) with values of another type
+(the <em>element</em> or <em>value</em>)
The key can be of any type for which the equality operator is defined,
such as integers,
floating point and complex numbers,
strings, pointers, interfaces (as long as the dynamic type
-supports equality), structs and arrays. Slices cannot be used as map keys,
+supports equality), structs and arrays.
+Slices cannot be used as map keys,
because equality is not defined on them.
-Like slices, maps are a reference type. If you pass a map to a function
+Like slices, maps hold references to an underlying data structure.
+If you pass a map to a function
that changes the contents of the map, the changes will be visible
in the caller.
</p>
@@ -1453,7 +1534,7 @@ if attended[person] { // will be false if person is not in the map
<p>
Sometimes you need to distinguish a missing entry from
a zero value. Is there an entry for <code>"UTC"</code>
-or is that zero value because it's not in the map at all?
+or is that the empty string because it's not in the map at all?
You can discriminate with a form of multiple assignment.
</p>
<pre>
@@ -1480,10 +1561,8 @@ func offset(tz string) int {
</pre>
<p>
To test for presence in the map without worrying about the actual value,
-you can use the blank identifier (<code>_</code>).
-The blank identifier can be assigned or declared with any value of any type, with the
-value discarded harmlessly. For testing just presence in a map, use the blank
-identifier in place of the usual variable for the value.
+you can use the <a href="#blank">blank identifier</a> (<code>_</code>)
+in place of the usual variable for the value.
</p>
<pre>
_, present := timeZone[tz]
@@ -1524,8 +1603,7 @@ fmt.Println("Hello", 23)
fmt.Println(fmt.Sprint("Hello ", 23))
</pre>
<p>
-As mentioned in
-the <a href="http://tour.golang.org">Tour</a>, <code>fmt.Fprint</code>
+The formatted print functions <code>fmt.Fprint</code>
and friends take as a first argument any object
that implements the <code>io.Writer</code> interface; the variables <code>os.Stdout</code>
and <code>os.Stderr</code> are familiar instances.
@@ -1591,8 +1669,10 @@ map[string] int{"CST":-21600, "PST":-28800, "EST":-18000, "UTC":0, "MST":-25200}
<p>
(Note the ampersands.)
That quoted string format is also available through <code>%q</code> when
-applied to a value of type <code>string</code> or <code>[]byte</code>;
-the alternate format <code>%#q</code> will use backquotes instead if possible.
+applied to a value of type <code>string</code> or <code>[]byte</code>.
+The alternate format <code>%#q</code> will use backquotes instead if possible.
+(The <code>%q</code> format also applies to integers and runes, producing a
+single-quoted rune constant.)
Also, <code>%x</code> works on strings, byte arrays and byte slices as well as
on integers, generating a long hexadecimal string, and with
a space in the format (<code>%&nbsp;x</code>) it puts spaces between the bytes.
@@ -1632,10 +1712,45 @@ the receiver for <code>String</code> must be of value type; this example used a
that's more efficient and idiomatic for struct types.
See the section below on <a href="#pointers_vs_values">pointers vs. value receivers</a> for more information.)
</p>
+
<p>
Our <code>String</code> method is able to call <code>Sprintf</code> because the
-print routines are fully reentrant and can be used recursively.
-We can even go one step further and pass a print routine's arguments directly to another such routine.
+print routines are fully reentrant and can be wrapped this way.
+There is one important detail to understand about this approach,
+however: don't construct a <code>String</code> method by calling
+<code>Sprintf</code> in a way that will recur into your <code>String</code>
+method indefinitely. This can happen if the <code>Sprintf</code>
+call attempts to print the receiver directly as a string, which in
+turn will invoke the method again. It's a common and easy mistake
+to make, as this example shows.
+</p>
+
+<pre>
+type MyString string
+
+func (m MyString) String() string {
+ return fmt.Sprintf("MyString=%s", m) // Error: will recur forever.
+}
+</pre>
+
+<p>
+It's also easy to fix: convert the argument to the basic string type, which does not have the
+method.
+</p>
+
+<pre>
+type MyString string
+func (m MyString) String() string {
+ return fmt.Sprintf("MyString=%s", string(m)) // OK: note conversion.
+}
+</pre>
+
+<p>
+In the <a href="#initialization">initialization section</a> we'll see another technique that avoids this recursion.
+</p>
+
+<p>
+Another printing technique is to pass a print routine's arguments directly to another such routine.
The signature of <code>Printf</code> uses the type <code>...interface{}</code>
for its final argument to specify that an arbitrary number of parameters (of arbitrary type)
can appear after the format.
@@ -1690,7 +1805,7 @@ is different from our custom <code>Append</code> function above.
Schematically, it's like this:
</p>
<pre>
-func append(slice []<i>T</i>, elements...T) []<i>T</i>
+func append(slice []<i>T</i>, elements...<i>T</i>) []<i>T</i>
</pre>
<p>
where <i>T</i> is a placeholder for any given type. You can't
@@ -1738,7 +1853,7 @@ would be wrong; <code>y</code> is not of type <code>int</code>.
Although it doesn't look superficially very different from
initialization in C or C++, initialization in Go is more powerful.
Complex structures can be built during initialization and the ordering
-issues between initialized objects in different packages are handled
+issues among initialized objects, even among different packages, are handled
correctly.
</p>
@@ -1748,7 +1863,7 @@ correctly.
Constants in Go are just that&mdash;constant.
They are created at compile time, even when defined as
locals in functions,
-and can only be numbers, strings or booleans.
+and can only be numbers, characters (runes), strings or booleans.
Because of the compile-time restriction, the expressions
that define them must be constant expressions,
evaluatable by the compiler. For instance,
@@ -1766,9 +1881,11 @@ sets of values.
</p>
{{code "/doc/progs/eff_bytesize.go" `/^type ByteSize/` `/^\)/`}}
<p>
-The ability to attach a method such as <code>String</code> to a
-type makes it possible for such values to format themselves
-automatically for printing, even as part of a general type.
+The ability to attach a method such as <code>String</code> to any
+user-defined type makes it possible for arbitrary values to format themselves
+automatically for printing.
+Although you'll see it most often applied to structs, this technique is also useful for
+scalar types such as floating-point types like <code>ByteSize</code>.
</p>
{{code "/doc/progs/eff_bytesize.go" `/^func.*ByteSize.*String/` `/^}/`}}
<p>
@@ -1777,13 +1894,13 @@ while <code>ByteSize(1e13)</code> prints as <code>9.09TB</code>.
</p>
<p>
-Note that it's fine to call <code>Sprintf</code> and friends in the
-implementation of <code>String</code> methods, but beware of
-recurring into the <code>String</code> method through the nested
-<code>Sprintf</code> call using a string format
-(<code>%s</code>, <code>%q</code>, <code>%v</code>, <code>%x</code> or <code>%X</code>).
-The <code>ByteSize</code> implementation of <code>String</code> is safe
-because it calls <code>Sprintf</code> with <code>%f</code>.
+The use here of <code>Sprintf</code>
+to implement <code>ByteSize</code>'s <code>String</code> method is safe
+(avoids recurring indefinitely) not because of a conversion but
+because it calls <code>Sprintf</code> with <code>%f</code>,
+which is not a string format: <code>Sprintf</code> will only call
+the <code>String</code> method when it wants a string, and <code>%f</code>
+wants a floating-point value.
</p>
<h3 id="variables">Variables</h3>
@@ -1837,7 +1954,8 @@ func init() {
<h3 id="pointers_vs_values">Pointers vs. Values</h3>
<p>
-Methods can be defined for any named type that is not a pointer or an interface;
+As we saw with <code>ByteSize</code>,
+methods can be defined for any named type (except a pointer or an interface);
the receiver does not have to be a struct.
</p>
<p>
@@ -1898,7 +2016,7 @@ modifications to be discarded.
</p>
<p>
By the way, the idea of using <code>Write</code> on a slice of bytes
-is implemented by <code>bytes.Buffer</code>.
+is central to the implementation of <code>bytes.Buffer</code>.
</p>
<h2 id="interfaces_and_types">Interfaces and other types</h2>
@@ -1941,10 +2059,8 @@ func (s Sequence) String() string {
}
</pre>
<p>
-The conversion causes <code>s</code> to be treated as an ordinary slice
-and therefore receive the default formatting.
-Without the conversion, <code>Sprint</code> would find the
-<code>String</code> method of <code>Sequence</code> and recur indefinitely.
+This method is another example of the conversion technique for calling
+<code>Sprintf</code> safely from a <code>String</code> method.
Because the two types (<code>Sequence</code> and <code>[]int</code>)
are the same if we ignore the type name, it's legal to convert between them.
The conversion doesn't create a new value, it just temporarily acts
@@ -1976,6 +2092,91 @@ and <code>[]int</code>), each of which does some part of the job.
That's more unusual in practice but can be effective.
</p>
+<h3 id="interface_conversions">Interface conversions and type assertions</h3>
+
+<p>
+<a href="#type_switch">Type switches</a> are a form of conversion: they take an interface and, for
+each case in the switch, in a sense convert it to the type of that case.
+Here's a simplified version of how the code under <code>fmt.Printf</code> turns a value into
+a string using a type switch.
+If it's already a string, we want the actual string value held by the interface, while if it has a
+<code>String</code> method we want the result of calling the method.
+</p>
+
+<pre>
+type Stringer interface {
+ String() string
+}
+
+var value interface{} // Value provided by caller.
+switch str := value.(type) {
+case string:
+ return str
+case Stringer:
+ return str.String()
+}
+</pre>
+
+<p>
+The first case finds a concrete value; the second converts the interface into another interface.
+It's perfectly fine to mix types this way.
+</p>
+
+<p>
+What if there's only one type we care about? If we know the value holds a <code>string</code>
+and we just want to extract it?
+A one-case type switch would do, but so would a <em>type assertion</em>.
+A type assertion takes an interface value and extracts from it a value of the specified explicit type.
+The syntax borrows from the clause opening a type switch, but with an explicit
+type rather than the <code>type</code> keyword:
+
+<pre>
+value.(typeName)
+</pre>
+
+<p>
+and the result is a new value with the static type <code>typeName</code>.
+That type must either be the concrete type held by the interface, or a second interface
+type that the value can be converted to.
+To extract the string we know is in the value, we could write:
+</p>
+
+<pre>
+str := value.(string)
+</pre>
+
+<p>
+But if it turns out that the value does not contain a string, the program will crash with a run-time error.
+To guard against that, use the "comma, ok" idiom to test, safely, whether the value is a string:
+</p>
+
+<pre>
+str, ok := value.(string)
+if ok {
+ fmt.Printf("string value is: %q\n", str)
+} else {
+ fmt.Printf("value is not a string\n")
+}
+</pre>
+
+<p>
+If the type assertion fails, <code>str</code> will still exist and be of type string, but it will have
+the zero value, an empty string.
+</p>
+
+<p>
+As an illustration of the capability, here's an <code>if</code>-<code>else</code>
+statement that's equivalent to the type switch that opened this section.
+</p>
+
+<pre>
+if str, ok := value.(string); ok {
+ return str
+} else if str, ok := value.(Stringer); ok {
+ return str.String()
+}
+</pre>
+
<h3 id="generality">Generality</h3>
<p>
If a type exists only to implement an interface
@@ -2133,9 +2334,7 @@ It's easy to write a function to print the arguments.
</p>
<pre>
func ArgServer() {
- for _, s := range os.Args {
- fmt.Println(s)
- }
+ fmt.Println(os.Args)
}
</pre>
<p>
@@ -2171,9 +2370,7 @@ to have the right signature.
<pre>
// Argument server.
func ArgServer(w http.ResponseWriter, req *http.Request) {
- for _, s := range os.Args {
- fmt.Fprintln(w, s)
- }
+ fmt.Fprintln(w, os.Args)
}
</pre>
<p>
@@ -2202,6 +2399,196 @@ a channel, and a function, all because interfaces are just sets of
methods, which can be defined for (almost) any type.
</p>
+<h2 id="blank">The blank identifier</h2>
+
+<p>
+We've mentioned the blank identifier a couple of times now, in the context of
+<a href="#for"><code>for</code> <code>range</code> loops</a>
+and <a href="#maps">maps</a>.
+The blank identifier can be assigned or declared with any value of any type, with the
+value discarded harmlessly.
+It's a bit like writing to the Unix <code>/dev/null</code> file:
+it represents a write-only value
+to be used as a place-holder
+where a variable is needed but the actual value is irrelevant.
+It has uses beyond those we've seen already.
+</p>
+
+<h3 id="blank_assign">The blank identifier in multiple assignment</h3>
+
+<p>
+The use of a blank identifier in a <code>for</code> <code>range</code> loop is a
+special case of a general situation: multiple assignment.
+<p>
+If an assignment requires multiple values on the left side,
+but one of the values will not be used by the program,
+a blank identifier on the left-hand-side of
+the assignment avoids the need
+to create a dummy variable and makes it clear that the
+value is to be discarded.
+For instance, when calling a function that returns
+a value and an error, but only the error is important,
+use the blank identifier to discard the irrelevant value.
+</p>
+
+<pre>
+if _, err := os.Stat(path); os.IsNotExist(err) {
+ fmt.Printf("%s does not exist\n", path)
+}
+</pre>
+
+<p>
+Occasionally you'll see code that discards the error value in order
+to ignore the error; this is terrible practice. Always check error returns;
+they're provided for a reason.
+</p>
+
+<pre>
+// Bad! This code will crash if path does not exist.
+fi, _ := os.Stat(path)
+if fi.IsDir() {
+ fmt.Printf("%s is a directory\n", path)
+}
+</pre>
+
+<h3 id="blank_unused">Unused imports and variables</h3>
+
+<p>
+It is an error to import a package or to declare a variable without using it.
+Unused imports bloat the program and slow compilation,
+while a variable that is initialized but not used is at least
+a wasted computation and perhaps indicative of a
+larger bug.
+When a program is under active development, however,
+unused imports and variables often arise and it can
+be annoying to delete them just to have the compilation proceed,
+only to have them be needed again later.
+The blank identifier provides a workaround.
+</p>
+<p>
+This half-written program is has two unused imports
+(<code>fmt</code> and <code>io</code>)
+and an unused variable (<code>fd</code>),
+so it will not compile, but it would be nice to see if the
+code so far is correct.
+</p>
+{{code "/doc/progs/eff_unused1.go" `/package/` `$`}}
+<p>
+To silence complaints about the unused imports, use a
+blank identifier to refer to a symbol from the imported package.
+Similarly, assigning the unused variable <code>fd</code>
+to the blank identifier will silence the unused variable error.
+This version of the program does compile.
+</p>
+{{code "/doc/progs/eff_unused2.go" `/package/` `$`}}
+
+<p>
+By convention, the global declarations to silence import errors
+should come right after the imports and be commented,
+both to make them easy to find and as a reminder to clean things up later.
+</p>
+
+<h3 id="blank_import">Import for side effect</h3>
+
+<p>
+An unused import like <code>fmt</code> or <code>io</code> in the
+previous example should eventually be used or removed:
+blank assignments identify code as a work in progress.
+But sometimes it is useful to import a package only for its
+side effects, without any explicit use.
+For example, during its <code>init</code> function,
+the <code><a href="/pkg/net/http/pprof/">net/http/pprof</a></code>
+package registers HTTP handlers that provide
+debugging information. It has an exported API, but
+most clients need only the handler registration and
+access the data through a web page.
+To import the package only for its side effects, rename the package
+to the blank identifier:
+</p>
+<pre>
+import _ "net/http/pprof"
+</pre>
+<p>
+This form of import makes clear that the package is being
+imported for its side effects, because there is no other possible
+use of the package: in this file, it doesn't have a name.
+(If it did, and we didn't use that name, the compiler would reject the program.)
+</p>
+
+<h3 id="blank_implements">Interface checks</h3>
+
+<p>
+As we saw in the discussion of <a href="#interfaces_and_types">interfaces</a> above,
+a type need not declare explicitly that it implements an interface.
+Instead, a type implements the interface just by implementing the interface's methods.
+In practice, most interface conversions are static and therefore checked at compile time.
+For example, passing an <code>*os.File</code> to a function
+expecting an <code>io.Reader</code> will not compile unless
+<code>*os.File</code> implements the <code>io.Reader</code> interface.
+</p>
+
+<p>
+Some interface checks do happen at run-time, though.
+One instance is in the <code><a href="/pkg/encoding/json/">encoding/json</a></code>
+package, which defines a <code><a href="/pkg/encoding/json/#Marshaler">Marshaler</a></code>
+interface. When the JSON encoder receives a value that implements that interface,
+the encoder invokes the value's marshaling method to convert it to JSON
+instead of doing the standard conversion.
+The encoder checks this property at run time with a <a href="interface_conversions">type assertion</a> like:
+</p>
+
+<pre>
+m, ok := val.(json.Marshaler)
+</pre>
+
+<p>
+If it's necessary only to ask whether a type implements an interface, without
+actually using the interface itself, perhaps as part of an error check, use the blank
+identifier to ignore the type-asserted value:
+</p>
+
+<pre>
+if _, ok := val.(json.Marshaler); ok {
+ fmt.Printf("value %v of type %T implements json.Marshaler\n", val, val)
+}
+</pre>
+
+<p>
+One place this situation arises is when it is necessary to guarantee within the package implementing the type that
+it it actually satisfies the interface.
+If a type—for example,
+<code><a href="/pkg/encoding/json/#RawMessage">json.RawMessage</a></code>—needs
+a custom its JSON representation, it should implement
+<code>json.Marshaler</code>, but there are no static conversions that would
+cause the compiler to verify this automatically.
+If the type inadvertently fails to satisfy the interface, the JSON encoder will still work,
+but will not use the custom implementation.
+To guarantee that the implementation is correct,
+a global declaration using the blank identifier can be used in the package:
+</p>
+<pre>
+var _ json.Marshaler = (*RawMessage)(nil)
+</pre>
+<p>
+In this declaration, the assignment involving a conversion of a
+<code>*RawMessage</code> to a <code>Marshaler</code>
+requires that <code>*RawMessage</code> implements <code>Marshaler</code>,
+and that property will be checked at compile time.
+Should the <code>json.Marshaler</code> interface change, this package
+will no longer compile and we will be on notice that it needs to be updated.
+</p>
+
+<p>
+The appearance of the blank identifier in this construct indicates that
+the declaration exists only for the type checking,
+not to create a variable.
+Don't do this for every type that satisfies an interface, though.
+By convention, such declarations are only used
+when there are no static conversions already present in the code,
+which is a rare event.
+</p>
+
+
<h2 id="embedding">Embedding</h2>
<p>
@@ -2328,8 +2715,8 @@ log to the <code>Job</code>:
job.Log("starting now...")
</pre>
<p>
-The <code>Logger</code> is a regular field of the struct and we can initialize
-it in the usual way with a constructor,
+The <code>Logger</code> is a regular field of the <code>Job</code> struct,
+so we can initialize it in the usual way inside the constructor for <code>Job</code>, like this,
</p>
<pre>
func NewJob(command string, logger *log.Logger) *Job {
@@ -2344,10 +2731,12 @@ job := &amp;Job{command, log.New(os.Stderr, "Job: ", log.Ldate)}
</pre>
<p>
If we need to refer to an embedded field directly, the type name of the field,
-ignoring the package qualifier, serves as a field name. If we needed to access the
+ignoring the package qualifier, serves as a field name, as it did
+in the <code>Read</code> method of our <code>ReaderWriter</code> struct.
+Here, if we needed to access the
<code>*log.Logger</code> of a <code>Job</code> variable <code>job</code>,
-we would write <code>job.Logger</code>.
-This would be useful if we wanted to refine the methods of <code>Logger</code>.
+we would write <code>job.Logger</code>,
+which would be useful if we wanted to refine the methods of <code>Logger</code>.
</p>
<pre>
func (job *Job) Logf(format string, args ...interface{}) {
@@ -2463,7 +2852,8 @@ completion. For that, we need channels.
<h3 id="channels">Channels</h3>
<p>
-Like maps, channels are a reference type and are allocated with <code>make</code>.
+Like maps, channels are allocated with <code>make</code>, and
+the resulting value acts as a reference to an underlying data structure.
If an optional integer parameter is provided, it sets the buffer size for the channel.
The default is zero, for an unbuffered or synchronous channel.
</p>
@@ -2473,7 +2863,7 @@ cj := make(chan int, 0) // unbuffered channel of integers
cs := make(chan *os.File, 100) // buffered channel of pointers to Files
</pre>
<p>
-Channels combine communication&mdash;the exchange of a value&mdash;with
+Unbuffered channels combine communication&mdash;the exchange of a value&mdash;with
synchronization&mdash;guaranteeing that two calculations (goroutines) are in
a known state.
</p>
@@ -2503,18 +2893,26 @@ means waiting until some receiver has retrieved a value.
<p>
A buffered channel can be used like a semaphore, for instance to
limit throughput. In this example, incoming requests are passed
-to <code>handle</code>, which sends a value into the channel, processes
-the request, and then receives a value from the channel.
+to <code>handle</code>, which receives a value from the channel, processes
+the request, and then sends a value back to the channel
+to ready the "semaphore" for the next consumer.
The capacity of the channel buffer limits the number of
-simultaneous calls to <code>process</code>.
+simultaneous calls to <code>process</code>,
+so during initialization we prime the channel by filling it to capacity.
</p>
<pre>
var sem = make(chan int, MaxOutstanding)
func handle(r *Request) {
- sem &lt;- 1 // Wait for active queue to drain.
- process(r) // May take a long time.
- &lt;-sem // Done; enable next request to run.
+ &lt;-sem // Wait for active queue to drain.
+ process(r) // May take a long time.
+ sem &lt;- 1 // Done; enable next request to run.
+}
+
+func init() {
+ for i := 0; i < MaxOutstanding; i++ {
+ sem &lt;- 1
+ }
}
func Serve(queue chan *Request) {
@@ -2524,8 +2922,37 @@ func Serve(queue chan *Request) {
}
}
</pre>
+
+<p>
+Because data synchronization occurs on a receive from a channel
+(that is, the send "happens before" the receive; see
+<a href="/ref/mem">The Go Memory Model</a>),
+acquisition of the semaphore must be on a channel receive, not a send.
+</p>
+
+<p>
+This design has a problem, though: <code>Serve</code>
+creates a new goroutine for
+every incoming request, even though only <code>MaxOutstanding</code>
+of them can run at any moment.
+As a result, the program can consume unlimited resources if the requests come in too fast.
+We can address that deficiency by changing <code>Serve</code> to
+gate the creation of the goroutines.
+</p>
+
+<pre>
+func Serve(queue chan *Request) {
+ for req := range queue {
+ &lt;-sem
+ go func() {
+ process(req)
+ sem &lt;- 1
+ }
+ }
+}</pre>
+
<p>
-Here's the same idea implemented by starting a fixed
+Another solution that manages resources well is to start a fixed
number of <code>handle</code> goroutines all reading from the request
channel.
The number of goroutines limits the number of simultaneous
@@ -2534,6 +2961,7 @@ This <code>Serve</code> function also accepts a channel on which
it will be told to exit; after launching the goroutines it blocks
receiving from that channel.
</p>
+
<pre>
func handle(queue chan *Request) {
for r := range queue {
@@ -2669,6 +3097,17 @@ of logical CPUs on the local machine.
Again, this requirement is expected to be retired as the scheduling and run-time improve.
</p>
+<p>
+Be sure not to confuse the ideas of concurrency—structuring a program
+as independently executing components—and parallelism—executing
+calculations in parallel for efficiency on multiple CPUs.
+Although the concurrency features of Go can make some problems easy
+to structure as parallel computations, Go is a concurrent language,
+not a parallel one, and not all parallelization problems fit Go's model.
+For a discussion of the distinction, see the talk cited in
+<a href="http://blog.golang.org/2013/01/concurrency-is-not-parallelism.html">this
+blog post</a>.
+
<h3 id="leaky_buffer">A leaky buffer</h3>
<p>
@@ -2785,7 +3224,7 @@ it is much more informative than the plain
<p>
When feasible, error strings should identify their origin, such as by having
-a prefix naming the package that generated the error. For example, in package
+a prefix naming the operation or package that generated the error. For example, in package
<code>image</code>, the string representation for a decoding error due to an
unknown format is "image: unknown format".
</p>
@@ -2813,11 +3252,8 @@ for try := 0; try &lt; 2; try++ {
</pre>
<p>
-The second <code>if</code> statement here is idiomatic Go.
-The type assertion <code>err.(*os.PathError)</code> is
-checked with the "comma ok" idiom (mentioned <a href="#maps">earlier</a>
-in the context of examining maps).
-If the type assertion fails, <code>ok</code> will be false, and <code>e</code>
+The second <code>if</code> statement here is another <a href="#interface_conversion">type assertion</a>.
+If it fails, <code>ok</code> will be false, and <code>e</code>
will be <code>nil</code>.
If it succeeds, <code>ok</code> will be true, which means the
error was of type <code>*os.PathError</code>, and then so is <code>e</code>,
@@ -2840,9 +3276,7 @@ that in effect creates a run-time error that will stop the program
(but see the next section). The function takes a single argument
of arbitrary type&mdash;often a string&mdash;to be printed as the
program dies. It's also a way to indicate that something impossible has
-happened, such as exiting an infinite loop. In fact, the compiler
-recognizes a <code>panic</code> at the end of a function and
-suppresses the usual check for a <code>return</code> statement.
+happened, such as exiting an infinite loop.
</p>
@@ -2944,7 +3378,7 @@ With our recovery pattern in place, the <code>do</code>
function (and anything it calls) can get out of any bad situation
cleanly by calling <code>panic</code>. We can use that idea to
simplify error handling in complex software. Let's look at an
-idealized excerpt from the <code>regexp</code> package, which reports
+idealized version of a <code>regexp</code> package, which reports
parsing errors by calling <code>panic</code> with a local
error type. Here's the definition of <code>Error</code>,
an <code>error</code> method, and the <code>Compile</code> function.
@@ -2985,18 +3419,27 @@ to <code>err</code>, that the problem was a parse error by asserting
that it has the local type <code>Error</code>.
If it does not, the type assertion will fail, causing a run-time error
that continues the stack unwinding as though nothing had interrupted
-it. This check means that if something unexpected happens, such
+it.
+This check means that if something unexpected happens, such
as an index out of bounds, the code will fail even though we
are using <code>panic</code> and <code>recover</code> to handle
-user-triggered errors.
+parse errors.
</p>
<p>
-With error handling in place, the <code>error</code> method
+With error handling in place, the <code>error</code> method (because it's a
+method bound to a type, it's fine, even natural, for it to have the same name
+as the builtin <code>error</code> type)
makes it easy to report parse errors without worrying about unwinding
-the parse stack by hand.
+the parse stack by hand:
</p>
+<pre>
+if pos==0 {
+ re.error("'*' illegal at start of expression")
+}
+</pre>
+
<p>
Useful though this pattern is, it should be used only within a package.
<code>Parse</code> turns its internal <code>panic</code> calls into
@@ -3015,155 +3458,6 @@ filter unexpected problems and re-panic with the original error.
That's left as an exercise for the reader.
</p>
-<h2 id="blank">Blank identifier</h2>
-
-<p>
-Go defines a special identifier <code>_</code>, called the <i>blank identifier</i>.
-The blank identifier can be used in a declaration to avoid
-declaring a name, and it can be used in an assignment to discard a value.
-This definition makes it useful in a variety of contexts.
-</p>
-
-<h3 id="blank_assign">Multiple assignment</h3>
-
-<p>
-If an assignment requires multiple values on the left side,
-but one of the values will not be used by the program,
-using the blank identifier in the assignment avoids the need
-to create a dummy variable.
-We saw one example of this in the discussion of
-<a href="#for">for loops</a> above.
-</p>
-<pre>
-sum := 0
-for _, value := range array {
- sum += value
-}
-</pre>
-
-<p>
-Another common use is when calling a function that returns
-a value and an error, but only the error is important.
-</p>
-<pre>
-if _, err := os.Stat(path); os.IsNotExist(err) {
- fmt.Printf("%s does not exist\n", path)
-}
-</pre>
-
-<p>
-A final use that is more common than it should be is to
-discard the error from a function that is not expected to fail.
-This is usually a mistake: when the function does fail, the code
-will continue on and probably panic dereferencing a nil pointer.
-</p>
-<pre>
-// Always check errors: this program crashes if path does not exist.
-fi, _ := os.Stat(path)
-fmt.Printf("%s is %d bytes\n", path, fi.Size())
-</pre>
-
-<h3 id="blank_unused">Unused imports and variables</h3>
-
-<p>
-Go defines that it is an error to import a package without using it,
-or to declare a variable without using its value.
-Unused imports bloat a program and lengthen compiles unnecessarily;
-a variable that is initialized but not used is at least
-a wasted computation and perhaps indicative of a
-larger bug.
-Of course, both of these situations also arise in programs
-that are under active development, as you test and refine
-your code.
-</p>
-<p>
-For example, in this program, there are two unused imports
-(<code>fmt</code> and <code>io</code>)
-and an unused variable (<code>greeting</code>).
-</p>
-{{code "/doc/progs/unused1.go" `/package/` `$`}}
-<p>
-Top-level blank declarations referring to the packages
-will silence the unused import errors.
-By convention, these declarations should come immediately after
-the imports, as a reminder to clean things up later.
-Similarly, assigning <code>greeting</code> to a blank identifier
-will silence the unused variable error.
-</p>
-{{code "/doc/progs/unused2.go" `/package/` `$`}}
-
-<h3 id="blank_import">Import for side effect</h3>
-
-<p>
-An unused import like <code>fmt</code> or <code>io</code> in the last section
-should eventually be used or removed:
-blank assignments identify code as a work in progress.
-But sometimes it is useful to import a package only for its
-side effects, without any explicit use.
-For example, during its <code>init</code> function,
-the <code><a href="/pkg/net/http/pprof/">net/http/pprof</a></code>
-package registers HTTP handlers that provide useful
-debugging information. It has an exported API too, but
-most clients need only the handler registration.
-In this situation, it is conventional to rename the package
-to the blank identifier:
-</p>
-<pre>
-import _ "net/http/pprof"
-</pre>
-<p>
-This form of import makes clear that the package is being
-imported for its side effects, because there is no other possible
-use of the package: in this file, it doesn't have a name.
-</p>
-
-<h3 id="blank_implements">Interface checks</h3>
-
-<p>
-As we saw in the discussion of <a href="#interfaces_and_types">interfaces</a> above,
-Go does not require a type to declare explicitly that it implements an interface.
-It implements the interface by simply implementing the required methods.
-This makes Go programs more lightweight and flexible, and it can avoid
-unnecessary dependencies between packages.
-Most interface conversions are static, visible to the compiler,
-and therefore checked at compile time.
-For example, passing an <code>*os.File</code> to a function
-expecting an <code>io.Reader</code> will not compile unless
-<code>*os.File</code> implements the <code>io.Reader</code> interface.
-</p>
-<p>
-However, some types that are used only to satisfy dynamic interface checks.
-For example, the <code><a href="/pkg/encoding/json/">encoding/json</a></code>
-package defines a <code><a href="/pkg/encoding/json/#Marshaler">Marshaler</a></code>
-interface. If the JSON encoder encounters a type implementing that interface,
-the encoder will let the type convert itself to JSON instead of using the standard
-conversion.
-This check is done only at runtime, with code like:
-</p>
-<pre>
-m, ok := val.(json.Marshaler)
-</pre>
-<p>
-If a type—for example,
-<code><a href="/pkg/encoding/json/#RawMessage">json.RawMessage</a></code>—intends
-to customize its JSON representation, it should implement
-<code>json.Marshaler</code>, but there are no static conversions that would
-cause the compiler to verify this automatically.
-A declaration can be used to add such a check:
-</p>
-<pre>
-var _ json.Marshaler = (*RawMessage)(nil)
-</pre>
-<p>
-As part of type-checking this static assignment of a
-<code>*RawMessage</code> to a <code>Marshaler</code>,
-the Go compiler will require that <code>*RawMessage</code> implements <code>Marshaler</code>.
-Using the blank identifier here indicates that
-the declaration exists only for the type checking,
-not to create a variable.
-Conventionally, such declarations are used only when there are
-no static conversions already present in the code.
-</p>
<h2 id="web_server">A web server</h2>
diff --git a/doc/go1.1.html b/doc/go1.1.html
index ae0a09939..f1d490f41 100644
--- a/doc/go1.1.html
+++ b/doc/go1.1.html
@@ -12,12 +12,19 @@ TODO
<h2 id="language">Changes to the language</h2>
-TODO
+<p>
+<a href="/doc/go1compat.html">The Go compatibility document</a> promises
+that programs written to the Go 1 language specification will continue to operate,
+and those promises are maintained.
+In the interest of firming up the specification, though, there are
+details about some error cases that have been clarified.
+There are also some new language features.
+</p>
<h3 id="divzero">Integer division by zero</h3>
<p>
-In Go 1, integer division by a constant zero produced a runtime panic:
+In Go 1, integer division by a constant zero produced a run-time panic:
</p>
<pre>
@@ -30,15 +37,93 @@ func f(x int) int {
In Go 1.1, an integer division by constant zero is not a legal program, so it is a compile-time error.
</p>
+<h3 id="unicode_literals">Surrogates in Unicode literals</h3>
-<h2 id="impl">Changes to the implementations and tools</h2>
+<p>
+The definition of string and rune literals has been refined to exclude surrogate halves from the
+set of valid Unicode code points.
+See the <a href="#unicode">Unicode</a> section for more information.
+</p>
-TODO: more
+<h3 id="method_values">Method values</h3>
-<h3 id="gc-flag">Command-line flag parsing</h3>
+<p>
+Go 1.1 now implements
+<a href="/ref/spec#Method_values">method values</a>,
+which are functions that have been bound to a specific receiver value.
+For instance, given a
+<a href="/pkg/bufio/#Writer"><code>Writer</code></a>
+value <code>w</code>,
+the expression
+<code>w.Write</code>,
+a method value, is a function that will always write to <code>w</code>; it is equivalent to
+a function literal closing over <code>w</code>:
+</p>
+
+<pre>
+func (p []byte) (n int, err error) {
+ return w.Write(n, err)
+}
+</pre>
<p>
-In the gc toolchain, the compilers and linkers now use the
+Method values are distinct from method expressions, which generate functions
+from methods of a given type; the method expression <code>(*bufio.Writer).Write</code>
+is equivalent to a function with an extra first argument, a receiver of type
+<code>(*bufio.Writer)</code>:
+</p>
+
+<pre>
+func (w *bufio.Writer, p []byte) (n int, err error) {
+ return w.Write(n, err)
+}
+</pre>
+
+<p>
+<em>Updating</em>: No existing code is affected; the change is strictly backward-compatible.
+</p>
+
+<h3 id="return">Return requirements</h3>
+
+<p>
+Before Go 1.1, a function that returned a value needed an explicit "return"
+or call to <code>panic</code> at
+the end of the function; this was a simple way to make the programmer
+be explicit about the meaning of the function. But there are many cases
+where a final "return" is clearly unnecessary, such as a function with
+only an infinite "for" loop.
+</p>
+
+<p>
+In Go 1.1, the rule about final "return" statements is more permissive.
+It introduces the concept of a
+<a href="/ref/spec/#Terminating_statements"><em>terminating statement</em></a>,
+a statement that is guaranteed to be the last one a function executes.
+Examples include
+"for" loops with no condition and "if-else"
+statements in which each half ends in a "return".
+If the final statement of a function can be shown <em>syntactically</em> to
+be a terminating statement, no final "return" statement is needed.
+</p>
+
+<p>
+Note that the rule is purely syntactic: it pays no attention to the values in the
+code and therefore requires no complex analysis.
+</p>
+
+<p>
+<em>Updating</em>: The change is backward-compatible, but existing code
+with superfluous "return" statements and calls to <code>panic</code> may
+be simplified manually.
+Such code can be identified by <code>go vet</code>.
+</p>
+
+<h2 id="impl">Changes to the implementations and tools</h2>
+
+<h3 id="gc_flag">Command-line flag parsing</h3>
+
+<p>
+In the gc tool chain, the compilers and linkers now use the
same command-line flag parsing rules as the Go flag package, a departure
from the traditional Unix flag parsing. This may affect scripts that invoke
the tool directly.
@@ -50,7 +135,11 @@ For example,
<h3 id="int">Size of int on 64-bit platforms</h3>
<p>
-The language allows the implementation to choose whether the <code>int</code> type and <code>uint</code> types are 32 or 64 bits. Previous Go implementations made <code>int</code> and <code>uint</code> 32 bits on all systems. Both the gc and gccgo implementations (TODO: check that gccgo does) <a href="http://golang.org/issue/2188">now make <code>int</code> and <code>uint</code> 64 bits on 64-bit platforms such as AMD64/x86-64</a>.
+The language allows the implementation to choose whether the <code>int</code> type and
+<code>uint</code> types are 32 or 64 bits. Previous Go implementations made <code>int</code>
+and <code>uint</code> 32 bits on all systems. Both the gc and gccgo implementations
+now make
+<code>int</code> and <code>uint</code> 64 bits on 64-bit platforms such as AMD64/x86-64.
Among other things, this enables the allocation of slices with
more than 2 billion elements on 64-bit platforms.
</p>
@@ -59,7 +148,7 @@ more than 2 billion elements on 64-bit platforms.
<em>Updating</em>:
Most programs will be unaffected by this change.
Because Go does not allow implicit conversions between distinct
-<a href="/ref/spec#Numeric_types">numeric types</a>,
+<a href="/ref/spec/#Numeric_types">numeric types</a>,
no programs will stop compiling due to this change.
However, programs that contain implicit assumptions
that <code>int</code> is only 32 bits may change behavior.
@@ -72,7 +161,7 @@ i := int(x) // i is -1 on 32-bit systems, 0xffffffff on 64-bit
fmt.Println(i)
</pre>
-<p>Portable code intending 32-bit sign extension (yielding -1 on all systems)
+<p>Portable code intending 32-bit sign extension (yielding <code>-1</code> on all systems)
would instead say:
</p>
@@ -80,31 +169,100 @@ would instead say:
i := int(int32(x))
</pre>
-<h3 id="asm">Assembler</h3>
+<h3 id="unicode">Unicode</h3>
+
+<p>
+To make it possible to represent code points greater than 65535 in UTF-16,
+Unicode defines <em>surrogate halves</em>,
+a range of code points to be used only in the assembly of large values, and only in UTF-16.
+The code points in that surrogate range are illegal for any other purpose.
+In Go 1.1, this constraint is honored by the compiler, libraries, and run-time:
+a surrogate half is illegal as a rune value, when encoded as UTF-8, or when
+encoded in isolation as UTF-16.
+When encountered, for example in converting from a rune to UTF-8, it is
+treated as an encoding error and will yield the replacement rune,
+<a href="/pkg/unicode/utf8/#RuneError"><code>utf8.RuneError</code></a>,
+U+FFFD.
+</p>
+
+<p>
+This program,
+</p>
+
+<pre>
+import "fmt"
+
+func main() {
+ fmt.Printf("%+q\n", string(0xD800))
+}
+</pre>
+
+<p>
+printed <code>"\ud800"</code> in Go 1.0, but prints <code>"\ufffd"</code> in Go 1.1.
+</p>
+
+<p>
+Surrogate-half Unicode values are now illegal in rune and string constants, so constants such as
+<code>'\ud800'</code> and <code>"\ud800"</code> are now rejected by the compilers.
+When written explicitly as UTF-8 encoded bytes,
+such strings can still be created, as in <code>"\xed\xa0\x80"</code>.
+However, when such a string is decoded as a sequence of runes, as in a range loop, it will yield only <code>utf8.RuneError</code>
+values.
+</p>
+
+<p>
+The Unicode byte order marks U+FFFE and U+FEFF, encoded in UTF-8, are now permitted as the first
+character of a Go source file.
+Even though their appearance in the byte-order-free UTF-8 encoding is clearly unnecessary,
+some editors add them as a kind of "magic number" identifying a UTF-8 encoded file.
+</p>
+
+<p>
+<em>Updating</em>:
+Most programs will be unaffected by the surrogate change.
+Programs that depend on the old behavior should be modified to avoid the issue.
+The byte-order-mark change is strictly backward-compatible.
+</p>
+
+<h3 id="gc_asm">The gc assemblers</h3>
<p>
-Due to the <a href="#int">int</a> and TODO: OTHER changes,
-the placement of function arguments on the stack has changed.
+Due to the change of the <a href="#int"><code>int</code></a> to 64 bits and some other changes,
+the arrangement of function arguments on the stack has changed in the gc tool chain.
Functions written in assembly will need to be revised at least
to adjust frame pointer offsets.
</p>
-<h3 id="gotool">Changes to the go tool</h3>
+<p>
+<em>Updating</em>:
+The <code>go vet</code> command now checks that functions implemented in assembly
+match the Go function prototypes they implement.
+</p>
+
+<h3 id="gocmd">Changes to the go command</h3>
-<p>The <code>go</code> tool has acquired several improvements which are intended to improve the experience for new Go users.</p>
+<p>
+The <a href="/cmd/go/"><code>go</code></a> command has acquired several
+changes intended to improve the experience for new Go users.
+</p>
-<p>Firstly, when compiling, testing, or running Go code, the <code>go</code> tool will now give more detailed errors messages, including a list of paths searched, when a package cannot be located.
+<p>
+First, when compiling, testing, or running Go code, the <code>go</code> command will now give more detailed error messages,
+including a list of paths searched, when a package cannot be located.
</p>
<pre>
$ go build foo/quxx
can't load package: package foo/quxx: cannot find package "foo/quxx" in any of:
- /home/User/go/src/pkg/foo/quxx (from $GOROOT)
- /home/User/src/foo/quxx (from $GOPATH)
+ /home/you/go/src/pkg/foo/quxx (from $GOROOT)
+ /home/you/src/foo/quxx (from $GOPATH)
</pre>
<p>
-Secondly, the <code>go get</code> command no longer allows <code>$GOROOT</code> as the default destination when downloading package source. To use <code>go get</code> command, a valid <code>$GOPATH</code> is now required.
+Second, the <code>go get</code> command no longer allows <code>$GOROOT</code>
+as the default destination when downloading package source.
+To use the <code>go get</code>
+command, a valid <code>$GOPATH</code> is now required.
</p>
<pre>
@@ -112,7 +270,9 @@ $ GOPATH= go get code.google.com/p/foo/quxx
package code.google.com/p/foo/quxx: cannot download, $GOPATH not set. For more details see: go help gopath
</pre>
-<p>Finally, as a result of the previous change, the <code>go get</code> command will also fail when <code>$GOPATH</code> and <code>$GOROOT</code> are set to the same value.
+<p>
+Finally, as a result of the previous change, the <code>go get</code> command will also fail
+when <code>$GOPATH</code> and <code>$GOROOT</code> are set to the same value.
</p>
<pre>
@@ -121,68 +281,226 @@ warning: GOPATH set to GOROOT (/home/User/go) has no effect
package code.google.com/p/foo/quxx: cannot download, $GOPATH must not be set to $GOROOT. For more details see: go help gopath
</pre>
-<h3 id="gofix">Changes to go fix</h3>
+<h3 id="gotest">Changes to the go test command</h3>
<p>
-The <code>go fix</code> command no longer applies fixes to update code from
-before Go 1 to use Go 1 APIs. To update pre-Go 1 code to Go 1.1, use a Go 1.0 toolchain
+The <code>go test</code> command no longer deletes the binary when run with profiling enabled,
+to make it easier to analyze the profile.
+The implementation sets the <code>-c</code> flag automatically, so after running,
+</p>
+
+<pre>
+$ go test -cpuprofile cpuprof.out mypackage
+</pre>
+
+<p>
+the file <code>mypackage.test</code> will be left in the directory where <code>go test</code> was run.
+</p>
+
+<p>
+The <code>go test</code> command can now generate profiling information
+that reports where goroutines are blocked, that is,
+where they tend to stall waiting for an event such as a channel communication.
+The information is presented as a
+<em>blocking profile</em>
+enabled with the
+<code>-blockprofile</code>
+option of
+<code>go test</code>.
+Run <code>go help test</code> for more information.
+</p>
+
+<h3 id="gofix">Changes to the go fix command</h3>
+
+<p>
+The <a href="/cmd/fix/"><code>fix</code></a> command, usually run as
+<code>go fix</code>, no longer applies fixes to update code from
+before Go 1 to use Go 1 APIs.
+To update pre-Go 1 code to Go 1.1, use a Go 1.0 tool chain
to convert the code to Go 1.0 first.
</p>
+<h2 id="performance">Performance</h2>
+
+<p>
+TODO introduction
+</p>
+
+<ul>
+<li>TODO better code generation (inlining, ...?)</li>
+<li>TODO parallel gc</li>
+<li>TODO more precise gc</li>
+<li>TODO networking is more efficient (known to runtime)</li>
+</ul>
+
<h2 id="library">Changes to the standard library</h2>
-<h3 id="debug_elf">debug/elf</h3>
+<h3 id="bufio_scanner">bufio.Scanner</h3>
+
<p>
-Previous versions of the debug/elf package intentionally skipped over the first
-symbol in the ELF symbol table, since it is always an empty symbol. This symbol
-is no longer skipped since indexes into the symbol table returned by debug/elf,
-will be different to indexes into the original ELF symbol table. Any code that
-calls the debug/elf functions Symbols or ImportedSymbols may need to be
-adjusted to account for the additional symbol and the change in symbol offsets.
+The various routines to scan textual input in the
+<a href="/pkg/bufio/"><code>bufio</code></a>
+package,
+<a href="/pkg/bufio/#Reader.ReadBytes"><code>ReadBytes</code></a>,
+<a href="/pkg/bufio/#Reader.ReadString"><code>ReadString</code></a>
+and particularly
+<a href="/pkg/bufio/#Reader.ReadLine"><code>ReadLine</code></a>,
+are needlessly complex to use for simple purposes.
+In Go 1.1, a new type,
+<a href="/pkg/bufio/#Scanner"><code>Scanner</code></a>,
+has been added to make it easier to do simple tasks such as
+read the input as a sequence of lines or space-delimited words.
+It simplifies the problem by terminating the scan on problematic
+input such as pathologically long lines, and having a simple
+default: line-oriented input, with each line stripped of its terminator.
+Here is code to reproduce the input a line at a time:
</p>
-<h3 id="html_template">html/template</h3>
+<pre>
+scanner := bufio.NewScanner(os.Stdin)
+for scanner.Scan() {
+ fmt.Println(scanner.Text()) // Println will add back the final '\n'
+}
+if err := scanner.Err(); err != nil {
+ fmt.Fprintln(os.Stderr, "reading standard input:", err)
+}
+</pre>
<p>
-Templates using the undocumented and only partially implemented
-"noescape" feature will break: that feature was removed.
+Scanning behavior can be adjusted through a function to control subdividing the input
+(see the documentation for <a href="/pkg/bufio/#SplitFunc"><code>SplitFunc</code></a>),
+but for tough problems or the need to continue past errors, the older interface
+may still be required.
</p>
<h3 id="net">net</h3>
<p>
-The protocol-specific resolvers were formerly
-lax about the network name passed in. For example, although the documentation was clear
-that the only valid networks for <code>ResolveTCPAddr</code> are <code>"tcp"</code>,
-<code>"tcp4"</code>, and <code>"tcp6"</code>, the Go 1.0 implementation silently accepted
-any string. The Go 1.1 implementation returns an error if the network is not one of those strings.
-The same is true of the other protocol-specific resolvers <code>ResolveIPAddr</code>, <code>ResolveUDPAddr</code>, and
-<code>ResolveUnixAddr</code>.
+The protocol-specific resolvers in the <a href="/pkg/net/"><code>net</code></a> package were formerly
+lax about the network name passed in.
+Although the documentation was clear
+that the only valid networks for
+<a href="/pkg/net/#ResolveTCPAddr"><code>ResolveTCPAddr</code></a>
+are <code>"tcp"</code>,
+<code>"tcp4"</code>, and <code>"tcp6"</code>, the Go 1.0 implementation silently accepted any string.
+The Go 1.1 implementation returns an error if the network is not one of those strings.
+The same is true of the other protocol-specific resolvers <a href="/pkg/net/#ResolveIPAddr"><code>ResolveIPAddr</code></a>,
+<a href="/pkg/net/#ResolveUDPAddr"><code>ResolveUDPAddr</code></a>, and
+<a href="/pkg/net/#ResolveUnixAddr"><code>ResolveUnixAddr</code></a>.
</p>
<p>
-The previous <code>ListenUnixgram</code> returned <code>UDPConn</code> as
-arepresentation of the connection endpoint. The Go 1.1 implementation
-returns <code>UnixConn</code> to allow reading and writing
-with <code>ReadFrom</code> and <code>WriteTo</code> methods on
-the <code>UnixConn</code>.
+The previous implementation of
+<a href="/pkg/net/#ListenUnixgram"><code>ListenUnixgram</code></a>
+returned a
+<a href="/pkg/net/#UDPConn"><code>UDPConn</code></a> as
+a representation of the connection endpoint.
+The Go 1.1 implementation instead returns a
+<a href="/pkg/net/#UnixConn"><code>UnixConn</code></a>
+to allow reading and writing
+with its
+<a href="/pkg/net/#UnixConn.ReadFrom"><code>ReadFrom</code></a>
+and
+<a href="/pkg/net/#UnixConn.WriteTo"><code>WriteTo</code></a>
+methods.
+</p>
+
+<h3 id="reflect">reflect</h3>
+
+<p>
+The <a href="/pkg/reflect/"><code>reflect</code></a> package has several significant additions.
</p>
+<p>
+It is now possible to run a "select" statement using
+the <code>reflect</code> package; see the description of
+<a href="/pkg/reflect/#Select"><code>Select</code></a>
+and
+<a href="/pkg/reflect/#SelectCase"><code>SelectCase</code></a>
+for details.
+</p>
+
+<p>
+The new method
+<a href="/pkg/reflect/#Value.Convert"><code>Value.Convert</code></a>
+(or
+<a href="/pkg/reflect/#Type"><code>Type.ConvertibleTo</code></a>)
+provides functionality to execute a Go conversion or type assertion operation
+on a
+<a href="/pkg/reflect/#Value"><code>Value</code></a>
+(or test for its possibility).
+</p>
+
+<p>
+The new function
+<a href="/pkg/reflect/#MakeFunc"><code>MakeFunc</code></a>
+creates a wrapper function to make it easier to call a function with existing
+<a href="/pkg/reflect/#Value"><code>Values</code></a>,
+doing the standard Go conversions among the arguments, for instance
+to pass an actual <code>int</code> to a formal <code>interface{}</code>.
+</p>
+
+<p>
+Finally, the new functions
+<a href="/pkg/reflect/#ChanOf"><code>ChanOf</code></a>,
+<a href="/pkg/reflect/#MapOf"><code>MapOf</code></a>
+and
+<a href="/pkg/reflect/#SliceOf"><code>SliceOf</code></a>
+construct new
+<a href="/pkg/reflect/#Type"><code>Types</code></a>
+from existing types, for example to construct a the type <code>[]T</code> given
+only <code>T</code>.
+</p>
+
+
<h3 id="time">time</h3>
<p>
-On FreeBSD, Linux, NetBSD, OS X and OpenBSD, previous versions of the time package
-returned times with microsecond precision. The Go 1.1 implementation of time on these
-systems now returns times with nanosecond precision. Code may exist that expects to be
-able to store such a time in an external format with only microsecond precision,
-read it back, and recover exactly the same time instant.
-In Go 1.1 the same time will not be recovered, since the external storage
-will have discarded nanoseconds.
-To address this case, there are two new methods of time.Time, Round and Truncate,
+On FreeBSD, Linux, NetBSD, OS X and OpenBSD, previous versions of the
+<a href="/pkg/time/"><code>time</code></a> package
+returned times with microsecond precision.
+The Go 1.1 implementation on these
+systems now returns times with nanosecond precision.
+Programs that write to an external format with microsecond precision
+and read it back, expecting to recover the original value, will be affected
+by the loss of precision.
+There are two new methods of <a href="/pkg/time/#Time"><code>Time</code></a>,
+<a href="/pkg/time/#Time.Round"><code>Round</code></a>
+and
+<a href="/pkg/time/#Time.Truncate"><code>Truncate</code></a>,
that can be used to remove precision from a time before passing it to
external storage.
</p>
-<h3 id="exp_old">Exp and old subtrees moved to go.exp subrepo</h3>
+<p>
+The new method
+<a href="/pkg/time/#Time.YearDay"><code>YearDay</code></a>
+returns the one-indexed integral day number of the year specified by the time value.
+</p>
+
+<p>
+The
+<a href="/pkg/time/#Timer"><code>Timer</code></a>
+type has a new method
+<a href="/pkg/time/#Timer.Reset"><code>Reset</code></a>
+that modifies the timer to expire after a specified duration.
+</p>
+
+<p>
+Finally, the new function
+<a href="/pkg/time/#ParseInLocation"><code>ParseInLocation</code></a>
+is like the existing
+<a href="/pkg/time/#Parse"><code>Parse</code></a>
+but parses the time in the context of a location (time zone), ignoring
+time zone information in the parsed string.
+This function addresses a common source of confusion in the time API.
+</p>
+
+<p>
+<em>Updating</em>:
+Code that needs to read and write times using an external format with
+lower precision should be modified to use the new methods.
+
+<h3 id="exp_old">Exp and old subtrees moved to go.exp and go.text subrepositories</h3>
<p>
To make it easier for binary distributions to access them if desired, the <code>exp</code>
@@ -204,4 +522,300 @@ and then in Go source,
import "code.google.com/p/go.exp/ssa"
</pre>
-<h3 id="TODO">TODO</h3>
+<p>
+The old package <code>exp/norm</code> has also been moved, but to a new repository
+<code>go.text</code>, where the Unicode APIs and other text-related packages will
+be developed.
+</p>
+
+<h3 id="minor_library_changes">Minor changes to the library</h3>
+
+<p>
+The following list summarizes a number of minor changes to the library, mostly additions.
+See the relevant package documentation for more information about each change.
+</p>
+
+<ul>
+<li>
+The <a href="/pkg/bytes/"><code>bytes</code></a> package has two new functions,
+<a href="/pkg/bytes/#TrimPrefix"><code>TrimPrefix</code></a>
+and
+<a href="/pkg/bytes/#TrimSuffix"><code>TrimSuffix</code></a>,
+with self-evident properties.
+Also, the <a href="/pkg/bytes/#Buffer"><code>Buffer</code></a> type
+has a new method
+<a href="/pkg/bytes/#Buffer.Grow"><code>Grow</code></a> that
+provides some control over memory allocation inside the buffer.
+Finally, the
+<a href="/pkg/bytes/#Reader"><code>Reader</code></a> type now has a
+<a href="/pkg/strings/#Reader.WriteTo"><code>WriteTo</code></a> method
+so it implements the
+<a href="/pkg/io/#WriterTo"><code>io.WriterTo</code></a> interface.
+</li>
+
+<li>
+The <a href="/pkg/crypto/hmac/"><code>crypto/hmac</code></a> package has a new function,
+<a href="/pkg/crypto/hmac/#Equal"><code>Equal</code></a>, to compare two MACs.
+</li>
+
+<li>
+The <a href="/pkg/crypto/x509/"><code>crypto/x509</code></a> package
+now supports PEM blocks (see
+<a href="/pkg/crypto/x509/#DecryptPEMBlock"><code>DecryptPEMBlock</code></a> for instance),
+and a new function
+<a href="/pkg/crypto/x509/#ParseECPrivateKey"><code>ParseECPrivateKey</code></a> to parse elliptic curve private keys.
+</li>
+
+<li>
+The <a href="/pkg/database/sql/"><code>database/sql/</code></a> package
+has a new
+<a href="/pkg/database/sql/#DB.Ping"><code>Ping</code></a>
+method for its
+<a href="/pkg/database/sql/#DB"><code>DB</code></a>
+type that tests the health of the connection.
+</li>
+
+<li>
+The <a href="/pkg/database/sql/driver/"><code>database/sql/driver</code></a> package
+has a new
+<a href="/pkg/database/sql/driver/#Queryer"><code>Queryer</code></a>
+interface that a
+<a href="/pkg/database/sql/driver/#Conn"><code>Conn</code></a>
+may implement to improve performance.
+</li>
+
+<li>
+The <a href="/pkg/encoding/json/"><code>encoding/json</code></a> package's
+<a href="/pkg/encoding/json/#Decoder"><code>Decoder</code></a>
+has a new method
+<a href="/pkg/encoding/json/#Decoder.Reader"><code>Reader</code></a>
+to provide access to the remaining data in its buffer,
+as well as a new method
+<a href="/pkg/encoding/json/#Decoder.UseNumber"><code>UseNumber</code></a>
+to unmarshal a value into the new type
+<a href="/pkg/encoding/json/#Number"><code>Number</code></a>,
+a string, rather than a float64.
+</li>
+
+<li>
+The <a href="/pkg/encoding/xml/"><code>endoding/xml</code></a> package
+has a new function,
+<a href="/pkg/encoding/xml/#EscapeText"><code>EscapeText</code></a>,
+which writes escaped XML output,
+and a method on
+<a href="/pkg/encoding/xml/#Encoder"><code>Encoder</code></a>,
+<a href="/pkg/encoding/xml/#Encoder.Indent"><code>Indent</code></a>,
+to specify indented output.
+</li>
+
+<li>
+In the <a href="/pkg/go/ast/"><code>go/ast</code></a> package, a
+new type <a href="/pkg/go/ast/#CommentMap"><code>CommentMap</code></a>
+and associated methods makes it easier to extract and process comments in Go programs.
+</li>
+
+<li>
+In the <a href="/pkg/go/doc/"><code>go/doc</code></a> package,
+the parser now keeps better track of stylized annotations such as <code>TODO(joe)</code>
+throughout the code,
+information that the <a href="/cmd/godoc/"><code>godoc</code></a>
+command can filter or present according to the value of the <code>-notes</code> flag.
+</li>
+
+<li>
+A new package, <a href="/pkg/go/format/"><code>go/format</code></a>, provides
+a convenient way for a program to access the formatting capabilities of <code>gofmt</code>.
+It has two functions,
+<a href="/pkg/go/format/#Node"><code>Node</code></a> to format a Go parser
+<a href="/pkg/go/ast/#Node"><code>Node</code></a>,
+and
+<a href="/pkg/go/format/#Source"><code>Source</code></a>
+to format arbitrary Go source code.
+</li>
+
+<li>
+The undocumented and only partially implemented "noescape" feature of the
+<a href="/pkg/html/template/">html/template</a>
+package has been removed; programs that depend on it will break.
+</li>
+
+<li>
+The <a href="/pkg/io/">io</a> package now exports the
+<a href="/pkg/io/#ByteWriter"><code>io.ByteWriter</code></a> interface to capture the common
+functionality of writing a byte at a time.
+</li>
+
+<li>
+The <a href="/pkg/log/syslog/"><code>log/syslog</code></a> package now provides better support
+for OS-specific logging features.
+</li>
+
+<li>
+The <a href="/pkg/math/big/"><code>math/big</code></a> package's
+<a href="/pkg/math/big/#Int"><code>Int</code></a> type now has
+now has methods
+<a href="/pkg/math/big/#Int.MarshalJSON"><code>MarshalJSON</code></a>
+and
+<a href="/pkg/math/big/#Int.UnmarshalJSON"><code>UnmarshalJSON</code></a>
+to convert to and from a JSON representation.
+Also,
+<a href="/pkg/math/big/#Int"><code>Int</code></a>
+can now convert directly to and from a <code>uint64</code> using
+<a href="/pkg/math/big/#Int.Uint64"><code>Uint64</code></a>
+and
+<a href="/pkg/math/big/#Int.SetUint64"><code>SetUint64</code></a>,
+while
+<a href="/pkg/math/big/#Rat"><code>Rat</code></a>
+can do the same with <code>float64</code> using
+<a href="/pkg/math/big/#Rat.Float64"><code>Float64</code></a>
+and
+<a href="/pkg/math/big/#Rat.SetFloat64"><code>SetFloat64</code></a>.
+</li>
+
+<li>
+The <a href="/pkg/mime/multipart/"><code>mime/multipart</code></a> package
+has a new method for its
+<a href="/pkg/mime/multipart/#Writer"><code>Writer</code></a>,
+<a href="/pkg/mime/multipart/#Writer.SetBoundary"><code>SetBoundary</code></a>,
+to define the boundary separator used to package the output.
+</li>
+
+<li>
+The
+<a href="/pkg/net/"><code>net</code></a> package's
+<a href="/pkg/net/#ListenUnixgram"><code>net/ListenUnixgram</code></a>
+function has changed return types: it now returns a
+<a href="/pkg/net/#UnixConn"><code>net/UnixConn</code></a>
+rather than a
+<a href="/pkg/net/#UDPConn"><code>net/UDPConn</code></a>, which was
+clearly a mistake in Go 1.0.
+Since this API change fixes a bug, it is permitted by the Go 1 compatibility rules.
+</li>
+
+<li>
+The new <a href="/pkg/net/http/cookiejar/">net/http/cookiejar</a> package provides the basics for managing HTTP cookies.
+</li>
+
+<li> TODO:
+<code>net/http</code>: ParseTime, CloseNotifier, Request.PostFormValue, ServeMux.Handler, Transport.CancelRequest
+</li>
+
+<li> TODO:
+<code>net/mail</code>: ParseAddress, ParseAddressList
+</li>
+
+<li> TODO:
+<code>net/smtp</code>: Client.Hello
+</li>
+
+<li>
+The <a href="/pkg/net/textproto/"><code>net/textproto</code></a> package
+has two new functions,
+<a href="/pkg/net/textproto/#TrimBytes"><code>TrimBytes</code></a> and
+<a href="/pkg/net/textproto/#TrimString"><code>TrimString</code></a>,
+which do ASCII-only trimming of leading and trailing spaces.
+</li>
+
+<li> TODO:
+<code>net</code>: DialOption, DialOpt, ListenUnixgram, LookupNS, IPConn.ReadMsgIP, IPConn.WriteMsgIP, UDPConn.ReadMsgUDP, UDPConn.WriteMsgUDP, UnixConn.CloseRead, UnixConn.CloseWrite
+</li>
+
+<li>
+The new method <a href="/pkg/os/#FileMode.IsRegular"><code>os.FileMode.IsRegular</code> </a> makes it easy to ask if a file is a plain file.
+</li>
+
+<li>
+The <a href="/pkg/image/jpeg/"><code>image/jpeg</code></a> package now
+reads progressive JPEG files and handles a few more subsampling configurations.
+</li>
+
+<li>
+The <a href="/pkg/regexp/"><code>regexp</code></a> package
+now supports Unix-original leftmost-longest matches through the
+<a href="/pkg/regexp/#Regexp.Longest"><code>Regexp.Longest</code></a>
+method, while
+<a href="/pkg/regexp/#Regexp.Split"><code>Regexp.Split</code></a> slices
+strings into pieces based on separators defined by the regular expression.
+</li>
+
+<li>
+The <a href="/pkg/runtime/debug/"><code>runtime/debug</code></a> package
+has three new functions regarding memory usage.
+The <a href="/pkg/runtime/debug/#FreeOSMemory"><code>FreeOSMemory</code></a>
+function triggers a run of the garbage collector and then attempts to return unused
+memory to the operating system;
+the <a href="/pkg/runtime/debug/#ReadGCStats"><code>ReadGCStats</code></a>
+function retrieves statistics about the collector; and
+<a href="/pkg/runtime/debug/#SetGCPercent"><code>SetGCPercent</code></a>
+provides a programmatic way to control how often the collector runs,
+including disabling it altogether.
+</li>
+
+<li>
+The <a href="/pkg/sort/"><code>sort</code></a> package has a new function,
+<a href="/pkg/sort/#Reverse"><code>Reverse</code></a>.
+Wrapping the argument of a call to
+<a href="/pkg/sort/#Sort"><code>sort.Sort</code></a>
+with a call to <code>Reverse</code> causes the sort order to be reversed.
+</li>
+
+<li>
+The <a href="/pkg/strings/"><code>strings</code></a> package has two new functions,
+<a href="/pkg/strings/#TrimPrefix"><code>TrimPrefix</code></a>
+and
+<a href="/pkg/strings/#TrimSuffix"><code>TrimSuffix</code></a>
+with self-evident properties, and the the new method
+<a href="/pkg/strings/#Reader.WriteTo"><code>Reader.WriteTo</code></a> so the
+<a href="/pkg/strings/#Reader"><code>Reader</code></a>
+type now implements the
+<a href="/pkg/io/#WriterTo"><code>io.WriterTo</code></a> interface.
+</li>
+
+<li>
+The <a href="/pkg/syscall/"><code>syscall</code></a> package has received many updates to make it more inclusive of constants and system calls for each supported operating system.
+</li>
+
+<li>
+The <a href="/pkg/testing/"><code>testing</code></a> package now automates the generation of allocation
+statistics in benchmarks using the new
+<a href="/pkg/testing/#AllocsPerRun"><code>AllocsPerRun</code></a> function and the
+<a href="/pkg/testing/#BenchmarkResult.AllocsPerOp"><code>AllocsPerOp</code></a> method of
+<a href="/pkg/testing/#BenchmarkResult"><code>BenchmarkResult</code></a>.
+There is also a new
+<a href="/pkg/testing/#Verbose"><code>Verbose</code></a> function to test the state of the <code>-v</code>
+command-line flag,
+and a new
+<a href="/pkg/testing/#B.Skip"><code>Skip</code></a> method of
+<a href="/pkg/testing/#B"><code>testing.B</code></a> and
+<a href="/pkg/testing/#T"><code>testing.T</code></a>
+to simplify skipping an inappropriate test.
+</li>
+
+<li>
+In the <a href="/pkg/text/template/"><code>text/template</code></a>
+and
+<a href="/pkg/html/template/"><code>html/template</code></a> packages,
+templates can now use parentheses to group the elements of pipelines, simplifying the construction of complex pipelines.
+TODO: Link to example.
+Also, as part of the new parser, the
+<a href="/pkg/text/template/parse/#Node"><code>Node</code></a> interface got two new methods to provide
+better error reporting.
+Although this violates the Go 1 compatibility rules,
+no existing code should be affected because this interface is explicitly intended only to be used
+by the
+<a href="/pkg/text/template/"><code>text/template</code></a>
+and
+<a href="/pkg/html/template/"><code>html/template</code></a>
+packages and there are safeguards to guarantee that.
+</li>
+
+<li>
+In the <a href="/pkg/unicode/utf8/"><code>unicode/utf8</code></a> package,
+the new function <a href="/pkg/unicode/utf8/#ValidRune"><code>ValidRune</code></a> reports whether the rune is a valid Unicode code point.
+To be valid, a rune must be in range and not be a surrogate half.
+</li>
+
+<li>
+The implementation of the <a href="/pkg/unicode/"><code>unicode</code></a> package has been updated to Unicode version 6.2.0.
+</li>
+</ul>
diff --git a/doc/go_faq.html b/doc/go_faq.html
index 5c68aa7e5..3e742d9f7 100644
--- a/doc/go_faq.html
+++ b/doc/go_faq.html
@@ -949,6 +949,38 @@ combined with the Go project's mostly linear, non-branching use of
version control, a switch to git doesn't seem worthwhile.
</p>
+<h3 id="git_https">
+Why does "go get" use HTTPS when cloning a repository?</h3>
+
+<p>
+Companies often permit outgoing traffic only on the standard TCP ports 80 (HTTP)
+and 443 (HTTPS), blocking outgoing traffic on other ports, including TCP port 9418
+(git) and TCP port 22 (SSH).
+When using HTTPS instead of HTTP, <code>git</code> enforces certificate validation by
+default, providing protection against man-in-the-middle, eavesdropping and tampering attacks.
+The <code>go get</code> command therefore uses HTTPS for safety.
+</p>
+
+<p>
+If you use <code>git</code> and prefer to push changes through SSH using your existing key
+it's easy to work around this. For GitHub, try one of these solutions:
+</p>
+<ul>
+<li>Manually clone the repository in the expected package directory:
+<pre>
+$ cd $GOPATH/src/github.com/username
+$ git clone git@github.com:username/package.git
+</pre>
+</li>
+<li>Force <code>git push</code> to use the <code>SSH</code> protocol by appending
+these two lines to <code>~/.gitconfig</code>:
+<pre>
+[url "git@github.com:"]
+ pushInsteadOf = https://github.com/
+</pre>
+</li>
+</ul>
+
<h2 id="Pointers">Pointers and Allocation</h2>
<h3 id="pass_by_value">
@@ -974,6 +1006,57 @@ struct. If the interface value holds a pointer, copying the interface value
makes a copy of the pointer, but again not the data it points to.
</p>
+<h3 id="pointer_to_interface">
+When should I use a pointer to an interface?</h3>
+
+<p>
+Almost never. Pointers to interface values arise only in rare, tricky situations involving
+disguising an interface value's type for delayed evaluation.
+</p>
+
+<p>
+It is however a common mistake to pass a pointer to an interface value
+to a function expecting an interface. The compiler will complain about this
+error but the situation can still be confusing, because sometimes a
+<a href="#different_method_sets">pointer
+is necessary to satisfy an interface</a>.
+The insight is that although a pointer to a concrete type can satisfy
+an interface, with one exception <em>a pointer to an interface can never satisfy a interface</em>.
+</p>
+
+<p>
+Consider the variable declaration,
+</p>
+
+<pre>
+var w io.Writer
+</pre>
+
+<p>
+The printing function <code>fmt.Fprintf</code> takes as its first argument
+a value that satisfies <code>io.Writer</code>—something that implements
+the canonical <code>Write</code> method. Thus we can write
+</p>
+
+<pre>
+fmt.Fprintf(w, "hello, world\n")
+</pre>
+
+<p>
+If however we pass the address of <code>w</code>, the program will not compile.
+</p>
+
+<pre>
+fmt.Fprintf(&amp;w, "hello, world\n") // Compile-time error.
+</pre>
+
+<p>
+The one exception is that any value, even a pointer to an interface, can be assigned to
+a variable of empty interface type (<code>interface{}</code>).
+Even so, it's almost certainly a mistake if the value is a pointer to an interface;
+the result can be confusing.
+</p>
+
<h3 id="methods_on_values_or_pointers">
Should I define methods on values or pointers?</h3>
@@ -1407,7 +1490,7 @@ test cases. The standard Go library is full of illustrative examples, such as in
What compiler technology is used to build the compilers?</h3>
<p>
-<code>Gccgo</code> has a C++ front-end with a recursive descent parser coupled to the
+<code>Gccgo</code> has a front end written in C++, with a recursive descent parser coupled to the
standard GCC back end. <code>Gc</code> is written in C using
<code>yacc</code>/<code>bison</code> for the parser.
Although it's a new program, it fits in the Plan 9 C compiler suite
diff --git a/doc/go_spec.html b/doc/go_spec.html
index 0cb9f54b1..881d16656 100644
--- a/doc/go_spec.html
+++ b/doc/go_spec.html
@@ -1,6 +1,6 @@
<!--{
"Title": "The Go Programming Language Specification",
- "Subtitle": "Version of March 1, 2013",
+ "Subtitle": "Version of March 22, 2013",
"Path": "/ref/spec"
}-->
@@ -639,8 +639,8 @@ 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 <a href="#Qualified_identifiers">qualified</a>) <i>type name</i>
-(§<a href="#Type_declarations">Type declarations</a>) or a <i>type literal</i>,
+(possibly <a href="#Qualified_identifiers">qualified</a>)
+<a href="#Type_declarations"><i>type name</i></a> or a <i>type literal</i>,
which composes a new type from previously declared types.
</p>
@@ -866,8 +866,8 @@ distinct arrays always represent distinct storage.
The array underlying a slice may extend past the end of the slice.
The <i>capacity</i> is a measure of that extent: it is the sum of
the length of the slice and the length of the array beyond the slice;
-a slice of length up to that capacity can be created by `slicing' a new
-one from the original slice (§<a href="#Slices">Slices</a>).
+a slice of length up to that capacity can be created by
+<a href="#Slices"><i>slicing</i></a> a new one from the original slice.
The capacity of a slice <code>a</code> can be discovered using the
built-in function <a href="#Length_and_capacity"><code>cap(a)</code></a>.
</p>
@@ -1236,8 +1236,8 @@ KeyType = Type .
</pre>
<p>
-The comparison operators <code>==</code> and <code>!=</code>
-(§<a href="#Comparison_operators">Comparison operators</a>) must be fully defined
+The <a href="#Comparison_operators">comparison operators</a>
+<code>==</code> and <code>!=</code> must be fully defined
for operands of the key type; thus the key type must not be a function, map, or
slice.
If the key type is an interface type, these
@@ -1469,12 +1469,13 @@ Any value may be assigned to the <a href="#Blank_identifier">blank identifier</a
<h2 id="Blocks">Blocks</h2>
<p>
-A <i>block</i> is a sequence of declarations and statements within matching
-brace brackets.
+A <i>block</i> is a possibly empty sequence of declarations and statements
+within matching brace brackets.
</p>
<pre class="ebnf">
-Block = "{" { Statement ";" } "}" .
+Block = "{" StatementList "}" .
+StatementList = { Statement ";" } .
</pre>
<p>
@@ -1490,10 +1491,13 @@ In addition to explicit blocks in the source code, there are implicit blocks:
<li>Each file has a <i>file block</i> containing all Go source text
in that file.</li>
- <li>Each <code>if</code>, <code>for</code>, and <code>switch</code>
+ <li>Each <a href="#If_statements">"if"</a>,
+ <a href="#For_statements">"for"</a>, and
+ <a href="#Switch_statements">"switch"</a>
statement is considered to be in its own implicit block.</li>
- <li>Each clause in a <code>switch</code> or <code>select</code> statement
+ <li>Each clause in a <a href="#Switch_statements">"switch"</a>
+ or <a href="#Select_statements">"select"</a> statement
acts as an implicit block.</li>
</ol>
@@ -1567,8 +1571,9 @@ declarations.
<p>
Labels are declared by <a href="#Labeled_statements">labeled statements</a> and are
-used in the <code>break</code>, <code>continue</code>, and <code>goto</code>
-statements (§<a href="#Break_statements">Break statements</a>, §<a href="#Continue_statements">Continue statements</a>, §<a href="#Goto_statements">Goto statements</a>).
+used in the <a href="#Break_statements">"break"</a>,
+<a href="#Continue_statements">"continue"</a>, and
+<a href="#Goto_statements">"goto"</a> statements.
It is illegal to define a label that is never used.
In contrast to other identifiers, labels are not block scoped and do
not conflict with identifiers that are not labels. The scope of a label
@@ -1868,7 +1873,7 @@ var _, found = entries[name] // map lookup; only interested in "found"
<p>
If a list of expressions is given, the variables are initialized
-by assigning the expressions to the variables (§<a href="#Assignments">Assignments</a>)
+by <a href="#Assignments">assigning</a> the expressions to the variables
in order; all expressions must be consumed and all variables initialized from them.
Otherwise, each variable is initialized to its <a href="#The_zero_value">zero value</a>.
</p>
@@ -1935,9 +1940,11 @@ a, a := 1, 2 // illegal: double declaration of a or
<p>
Short variable declarations may appear only inside functions.
-In some contexts such as the initializers for <code>if</code>,
-<code>for</code>, or <code>switch</code> statements,
-they can be used to declare local temporary variables (§<a href="#Statements">Statements</a>).
+In some contexts such as the initializers for
+<a href="#If_statements">"if"</a>,
+<a href="#For_statements">"for"</a>, or
+<a href="#Switch_statements">"switch"</a> statements,
+they can be used to declare local temporary variables.
</p>
<h3 id="Function_declarations">Function declarations</h3>
@@ -1948,9 +1955,27 @@ to a function.
</p>
<pre class="ebnf">
-FunctionDecl = "func" FunctionName Signature [ Body ] .
+FunctionDecl = "func" FunctionName ( Function | Signature ) .
FunctionName = identifier .
-Body = Block .
+Function = Signature FunctionBody .
+FunctionBody = Block .
+</pre>
+
+<p>
+If the function's <a href="#Function_types">signature</a> declares
+result parameters, the function body's statement list must end in
+a <a href="#Terminating_statements">terminating statement</a>.
+</p>
+
+<pre>
+func findMarker(c <-chan int) int {
+ for i := range c {
+ if x := <-c; isMarker(x) {
+ return x
+ }
+ }
+ // invalid: missing return statement.
+}
</pre>
<p>
@@ -1972,13 +1997,13 @@ func flushICache(begin, end uintptr) // implemented externally
<h3 id="Method_declarations">Method declarations</h3>
<p>
-A method is a function with a <i>receiver</i>.
-A method declaration binds an identifier, the <i>method name</i>, to a method.
-It also associates the method with the receiver's <i>base type</i>.
+A method is a <a href="#Function_declarations">function</a> with a <i>receiver</i>.
+A method declaration binds an identifier, the <i>method name</i>, to a method,
+and associates the method with the receiver's <i>base type</i>.
</p>
<pre class="ebnf">
-MethodDecl = "func" Receiver MethodName Signature [ Body ] .
+MethodDecl = "func" Receiver MethodName ( Function | Signature ) .
Receiver = "(" [ identifier ] [ "*" ] BaseTypeName ")" .
BaseTypeName = identifier .
</pre>
@@ -2185,7 +2210,7 @@ For array and slice literals the following rules apply:
</ul>
<p>
-Taking the address of a composite literal (§<a href="#Address_operators">Address operators</a>)
+<a href="#Address_operators">Taking the address</a> of a composite literal
generates a pointer to a unique instance of the literal's value.
</p>
<pre>
@@ -2284,12 +2309,11 @@ noteFrequency := map[string]float32{
<h3 id="Function_literals">Function literals</h3>
<p>
-A function literal represents an anonymous function.
-It consists of a specification of the function type and a function body.
+A function literal represents an anonymous <a href="#Function_declarations">function</a>.
</p>
<pre class="ebnf">
-FunctionLit = FunctionType Body .
+FunctionLit = "func" Function .
</pre>
<pre>
@@ -2414,8 +2438,15 @@ expression is illegal.
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>
+If <code>x</code> is of pointer type and has the value
+<code>nil</code> and <code>x.f</code> denotes a struct field,
+assigning to or evaluating <code>x.f</code>
+causes a <a href="#Run_time_panics">run-time panic</a>.
+</li>
+<li>
+If <code>x</code> is of interface type and has the value
+<code>nil</code>, <a href="#Calls">calling</a> or
+<a href="#Method_values">evaluating</a> the method <code>x.f</code>
causes a <a href="#Run_time_panics">run-time panic</a>.
</li>
</ol>
@@ -2503,7 +2534,8 @@ rules apply:
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>,
+ <li>the index <code>x</code> must be of integer type or untyped;
+ 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>
@@ -2894,9 +2926,7 @@ The right operand in a shift expression must have unsigned integer type
or be an untyped constant that can be converted to unsigned integer type.
If the left operand of a non-constant shift expression is an untyped constant,
the type of the constant is what it would be if the shift expression were
-replaced by its left operand alone; the type is <code>int</code> if it cannot
-be determined from the context (for instance, if the shift expression is an
-operand in a comparison against an untyped constant).
+replaced by its left operand alone.
</p>
<pre>
@@ -2905,10 +2935,12 @@ var i = 1&lt;&lt;s // 1 has type int
var j int32 = 1&lt;&lt;s // 1 has type int32; j == 0
var k = uint64(1&lt;&lt;s) // 1 has type uint64; k == 1&lt;&lt;33
var m int = 1.0&lt;&lt;s // 1.0 has type int
-var n = 1.0&lt;&lt;s != 0 // 1.0 has type int; n == false if ints are 32bits in size
+var n = 1.0&lt;&lt;s != i // 1.0 has type int; n == false if ints are 32bits in size
var o = 1&lt;&lt;s == 2&lt;&lt;s // 1 and 2 have type int; o == true if ints are 32bits in size
var p = 1&lt;&lt;s == 1&lt;&lt;33 // illegal if ints are 32bits in size: 1 has type int, but 1&lt;&lt;33 overflows int
var u = 1.0&lt;&lt;s // illegal: 1.0 has type float64, cannot shift
+var u1 = 1.0&lt;&lt;s != 0 // illegal: 1.0 has type float64, cannot shift
+var u2 = 1&lt;&lt;s != 1.0 // illegal: 1 has type float64, cannot shift
var v float32 = 1&lt;&lt;s // illegal: 1 has type float32, cannot shift
var w int64 = 1.0&lt;&lt;33 // 1.0&lt;&lt;33 is a constant shift expression
</pre>
@@ -3080,8 +3112,8 @@ occurs is implementation-specific.
For unsigned integer values, the operations <code>+</code>,
<code>-</code>, <code>*</code>, and <code>&lt;&lt;</code> are
computed modulo 2<sup><i>n</i></sup>, where <i>n</i> is the bit width of
-the unsigned integer's type
-(§<a href="#Numeric_types">Numeric types</a>). Loosely speaking, these unsigned integer operations
+the <a href="#Numeric_types">unsigned integer</a>'s type.
+Loosely speaking, these unsigned integer operations
discard high bits upon overflow, and programs may rely on ``wrap around''.
</p>
<p>
@@ -3098,7 +3130,7 @@ not occur. For instance, it may not assume that <code>x &lt; x + 1</code> is alw
<h3 id="Comparison_operators">Comparison operators</h3>
<p>
-Comparison operators compare two operands and yield a boolean value.
+Comparison operators compare two operands and yield an untyped boolean value.
</p>
<pre class="grammar">
@@ -3158,8 +3190,8 @@ These terms and the result of the comparisons are defined as follows:
<li>
Channel values are comparable.
- Two channel values are equal if they were created by the same call to <code>make</code>
- (§<a href="#Making_slices_maps_and_channels">Making slices, maps, and channels</a>)
+ Two channel values are equal if they were created by the same call to
+ <a href="#Making_slices_maps_and_channels"><code>make</code></a>
or if both have value <code>nil</code>.
</li>
@@ -3206,20 +3238,17 @@ Comparison of pointer, channel, and interface values to <code>nil</code>
is also allowed and follows from the general rules above.
</p>
-<p>
-The result of a comparison can be assigned to any boolean type.
-If the context does not demand a specific boolean type,
-the result has type <code>bool</code>.
-</p>
-
<pre>
-type MyBool bool
+const c = 3 < 4 // c is the untyped bool constant true
+type MyBool bool
var x, y int
var (
- b1 MyBool = x == y // result of comparison has type MyBool
- b2 bool = x == y // result of comparison has type bool
- b3 = x == y // result of comparison has type bool
+ // The result of a comparison is an untyped bool.
+ // The usual assignment rules apply.
+ b3 = x == y // b3 has type bool
+ b4 bool = x == y // b4 has type bool
+ b5 MyBool = x == y // b5 has type MyBool
)
</pre>
@@ -3341,6 +3370,7 @@ type T struct {
}
func (tv T) Mv(a int) int { return 0 } // value receiver
func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver
+
var t T
</pre>
@@ -3426,7 +3456,8 @@ the receiver is provided as the first argument to the call.
That is, given <code>f := T.Mv</code>, <code>f</code> is invoked
as <code>f(t, 7)</code> not <code>t.f(7)</code>.
To construct a function that binds the receiver, use a
-<a href="#Function_literals">closure</a>.
+<a href="#Function_literals">function literal</a> or
+<a href="#Method_values">method value</a>.
</p>
<p>
@@ -3434,6 +3465,111 @@ It is legal to derive a function value from a method of an interface type.
The resulting function takes an explicit receiver of that interface type.
</p>
+<h3 id="Method_values">Method values</h3>
+
+<p>
+If the expression <code>x</code> has static type <code>T</code> and
+<code>M</code> is in the <a href="#Method_sets">method set</a> of type <code>T</code>,
+<code>x.M</code> is called a <i>method value</i>.
+The method value <code>x.M</code> is a function value that is callable
+with the same arguments as a method call of <code>x.M</code>.
+The expression <code>x</code> is evaluated and saved during the evaluation of the
+method value; the saved copy is then used as the receiver in any calls,
+which may be executed later.
+</p>
+
+<p>
+The type <code>T</code> may be an interface or non-interface type.
+</p>
+
+<p>
+As in the discussion of <a href="#Method_expressions">method expressions</a> above,
+consider a struct type <code>T</code> with two methods,
+<code>Mv</code>, whose receiver is of type <code>T</code>, and
+<code>Mp</code>, whose receiver is of type <code>*T</code>.
+</p>
+
+<pre>
+type T struct {
+ a int
+}
+func (tv T) Mv(a int) int { return 0 } // value receiver
+func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver
+
+var t T
+var pt *T
+func makeT() T
+</pre>
+
+<p>
+The expression
+</p>
+
+<pre>
+t.Mv
+</pre>
+
+<p>
+yields a function value of type
+</p>
+
+<pre>
+func(int) int
+</pre>
+
+<p>
+These two invocations are equivalent:
+</p>
+
+<pre>
+t.Mv(7)
+f := t.Mv; f(7)
+</pre>
+
+<p>
+Similarly, the expression
+</p>
+
+<pre>
+pt.Mp
+</pre>
+
+<p>
+yields a function value of type
+</p>
+
+<pre>
+func(float32) float32
+</pre>
+
+<p>
+As with <a href="#Selectors">selectors</a>, a reference to a non-interface method with a value receiver
+using a pointer will automatically dereference that pointer: <code>pt.Mv</code> is equivalent to <code>(*pt).Mv</code>.
+</p>
+
+<p>
+As with <a href="#Calls">method calls</a>, a reference to a non-interface method with a pointer receiver
+using an addressable value will automatically take the address of that value: <code>t.Mv</code> is equivalent to <code>(&amp;t).Mv</code>.
+</p>
+
+<pre>
+f := t.Mv; f(7) // like t.Mv(7)
+f := pt.Mp; f(7) // like pt.Mp(7)
+f := pt.Mv; f(7) // like (*pt).Mv(7)
+f := t.Mp; f(7) // like (&amp;t).Mp(7)
+f := makeT().Mp // invalid: result of makeT() is not addressable
+</pre>
+
+<p>
+Although the examples above use non-interface types, it is also legal to create a method value
+from a value of interface type.
+</p>
+
+<pre>
+var i interface { M(int) } = myVal
+f := i.M; f(7) // like i.M(7)
+</pre>
+
<h3 id="Conversions">Conversions</h3>
<p>
@@ -3484,8 +3620,8 @@ type <code>T</code> in any of these cases:
<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
- (§<a href="#Conversions_to_and_from_a_string_type">Conversions to and from a string type</a>).
+ The <a href="#Conversions_to_and_from_a_string_type">same rule</a>
+ as for non-constant <code>x</code> applies in this case.
</li>
</ul>
@@ -3683,8 +3819,8 @@ A constant <a href="#Comparison_operators">comparison</a> always yields
an untyped boolean constant. If the left operand of a constant
<a href="#Operators">shift expression</a> is an untyped constant, the
result is an integer constant; otherwise it is a constant of the same
-type as the left operand, which must be of integer type
-(§<a href="#Arithmetic_operators">Arithmetic operators</a>).
+type as the left operand, which must be of
+<a href="#Numeric_types">integer type</a>.
Applying all other operators to untyped constants results in an untyped
constant of the same kind (that is, a boolean, integer, floating-point,
complex, or string constant).
@@ -3843,6 +3979,84 @@ Statement =
SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | Assignment | ShortVarDecl .
</pre>
+<h3 id="Terminating_statements">Terminating statements</h3>
+
+<p>
+A terminating statement is one of the following:
+</p>
+
+<ol>
+<li>
+ A <a href="#Return_statements">"return"</a> or
+ <a href="#Goto_statements">"goto"</a> statement.
+ <!-- ul below only for regular layout -->
+ <ul> </ul>
+</li>
+
+<li>
+ A call to the built-in function
+ <a href="#Handling_panics"><code>panic</code></a>.
+ <!-- ul below only for regular layout -->
+ <ul> </ul>
+</li>
+
+<li>
+ A <a href="#Blocks">block</a> in which the statement list ends in a terminating statement.
+ <!-- ul below only for regular layout -->
+ <ul> </ul>
+</li>
+
+<li>
+ An <a href="#If_statements">"if" statement</a> in which:
+ <ul>
+ <li>the "else" branch is present, and</li>
+ <li>both branches are terminating statements.</li>
+ </ul>
+</li>
+
+<li>
+ A <a href="#For_statements">"for" statement</a> in which:
+ <ul>
+ <li>there are no "break" statements referring to the "for" statement, and</li>
+ <li>the loop condition is absent.</li>
+ </ul>
+</li>
+
+<li>
+ A <a href="#Switch_statements">"switch" statement</a> in which:
+ <ul>
+ <li>there are no "break" statements referring to the "switch" statement,</li>
+ <li>there is a default case, and</li>
+ <li>the statement lists in each case, including the default, end in a terminating
+ statement, or a possibly labeled <a href="#Fallthrough_statements">"fallthrough"
+ statement</a>.</li>
+ </ul>
+</li>
+
+<li>
+ A <a href="#Select_statements">"select" statement</a> in which:
+ <ul>
+ <li>there are no "break" statements referring to the "select" statement, and</li>
+ <li>the statement lists in each case, including the default if present,
+ end in a terminating statement.</li>
+ </ul>
+</li>
+
+<li>
+ A <a href="#Labeled_statements">labeled statement</a> labeling
+ a terminating statement.
+</li>
+</ol>
+
+<p>
+All other statements are not terminating.
+</p>
+
+<p>
+A <a href="#Blocks">statement list</a> ends in a terminating statement if the list
+is not empty and its final statement is terminating.
+</p>
+
<h3 id="Empty_statements">Empty statements</h3>
@@ -4149,7 +4363,7 @@ the expression <code>true</code>.
<pre class="ebnf">
ExprSwitchStmt = "switch" [ SimpleStmt ";" ] [ Expression ] "{" { ExprCaseClause } "}" .
-ExprCaseClause = ExprSwitchCase ":" { Statement ";" } .
+ExprCaseClause = ExprSwitchCase ":" StatementList .
ExprSwitchCase = "case" ExpressionList | "default" .
</pre>
@@ -4213,7 +4427,7 @@ expression <code>x</code>. As with type assertions, <code>x</code> must be of
<pre class="ebnf">
TypeSwitchStmt = "switch" [ SimpleStmt ";" ] TypeSwitchGuard "{" { TypeCaseClause } "}" .
TypeSwitchGuard = [ identifier ":=" ] PrimaryExpr "." "(" "type" ")" .
-TypeCaseClause = TypeSwitchCase ":" { Statement ";" } .
+TypeCaseClause = TypeSwitchCase ":" StatementList .
TypeSwitchCase = "case" TypeList | "default" .
TypeList = Type { "," Type } .
</pre>
@@ -4229,8 +4443,7 @@ in the TypeSwitchGuard.
</p>
<p>
-The type in a case may be <code>nil</code>
-(§<a href="#Predeclared_identifiers">Predeclared identifiers</a>);
+The type in a case may be <a href="#Predeclared_identifiers"><code>nil</code></a>;
that case is used when the expression in the TypeSwitchGuard
is a <code>nil</code> interface value.
</p>
@@ -4382,8 +4595,8 @@ the range clause is equivalent to the same clause with only the first variable p
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>),
+length is evaluated; if that length is constant
+<a href="#Length_and_capacity">by definition</a>,
the range expression itself will not be evaluated.
</p>
@@ -4536,7 +4749,7 @@ cases all referring to communication operations.
<pre class="ebnf">
SelectStmt = "select" "{" { CommClause } "}" .
-CommClause = CommCase ":" { Statement ";" } .
+CommClause = CommCase ":" StatementList .
CommCase = "case" ( SendStmt | RecvStmt ) | "default" .
RecvStmt = [ ExpressionList "=" | IdentifierList ":=" ] RecvExpr .
RecvExpr = Expression .
@@ -4661,7 +4874,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 <a href="#Function_types">result parameters</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.
@@ -4681,8 +4894,8 @@ 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
+Regardless of how they are declared, all the result values are initialized to
+the <a href="#The_zero_value">zero values</a> for their type upon entry to the
function. A "return" statement that specifies results sets the result parameters before
any deferred functions are executed.
</p>
@@ -4699,7 +4912,9 @@ TODO: Define when return is required.<br />
<p>
A "break" statement terminates execution of the innermost
-"for", "switch" or "select" statement.
+<a href="#For_statements">"for"</a>,
+<a href="#Switch_statements">"switch"</a>, or
+<a href="#Select_statements">"select"</a> statement.
</p>
<pre class="ebnf">
@@ -4708,10 +4923,8 @@ BreakStmt = "break" [ Label ] .
<p>
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>).
+"for", "switch", or "select" statement,
+and that is the one whose execution terminates.
</p>
<pre>
@@ -4728,7 +4941,7 @@ L:
<p>
A "continue" statement begins the next iteration of the
-innermost "for" loop at its post statement (§<a href="#For_statements">For statements</a>).
+innermost <a href="#For_statements">"for" loop</a> at its post statement.
</p>
<pre class="ebnf">
@@ -4738,8 +4951,7 @@ ContinueStmt = "continue" [ Label ] .
<p>
If there is a label, it must be that of an enclosing
"for" statement, and that is the one whose execution
-advances
-(§<a href="#For_statements">For statements</a>).
+advances.
</p>
<h3 id="Goto_statements">Goto statements</h3>
@@ -4958,8 +5170,8 @@ constant and <code>s</code> is evaluated.
<p>
The built-in function <code>new</code> takes a type <code>T</code> and
returns a value of type <code>*T</code>.
-The memory is initialized as described in the section on initial values
-(§<a href="#The_zero_value">The zero value</a>).
+The memory is initialized as described in the section on
+<a href="#The_zero_value">initial values</a>.
</p>
<pre class="grammar">
@@ -4991,8 +5203,8 @@ The built-in function <code>make</code> takes a type <code>T</code>,
which must be a slice, map or channel type,
optionally followed by a type-specific list of expressions.
It returns a value of type <code>T</code> (not <code>*T</code>).
-The memory is initialized as described in the section on initial values
-(§<a href="#The_zero_value">The zero value</a>).
+The memory is initialized as described in the section on
+<a href="#The_zero_value">initial values</a>.
</p>
<pre class="grammar">
@@ -5010,7 +5222,7 @@ make(T, n) channel asynchronous channel of type T, buffer size n
<p>
-The size arguments <code>n</code> and <code>m</code> must be integer values.
+The size arguments <code>n</code> and <code>m</code> must be of integer type or untyped.
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
@@ -5184,14 +5396,14 @@ func recover() interface{}
</pre>
<p>
-A <code>panic</code> call in a function <code>F</code> terminates the execution
-of <code>F</code>.
+While executing a function <code>F</code>,
+an explicit call to <code>panic</code> or a <a href="#Run_time_panics">run-time panic</a>
+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
+are then executed as usual.
+Next, any deferred functions run by <code>F's</code> caller are run,
+and so on up to any deferred by the top-level function in the executing goroutine.
+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>
@@ -5204,17 +5416,36 @@ panic(Error("cannot parse"))
<p>
The <code>recover</code> function allows a program to manage behavior
-of a panicking goroutine. Executing a <code>recover</code> call
-<i>inside</i> a deferred function (but not any function called by it) stops
-the panicking sequence by restoring normal execution, and retrieves
-the error value passed to the call of <code>panic</code>. If
-<code>recover</code> is called outside the deferred function it will
-not stop a panicking sequence. In this case, or when the goroutine
-is not panicking, or if the argument supplied to <code>panic</code>
-was <code>nil</code>, <code>recover</code> returns <code>nil</code>.
+of a panicking goroutine.
+Suppose a function <code>G</code> defers a function <code>D</code> that calls
+<code>recover</code> and a panic occurs in a function on the same goroutine in which <code>G</code>
+is executing.
+When the running of deferred functions reaches <code>D</code>,
+the return value of <code>D</code>'s call to <code>recover</code> will be the value passed to the call of <code>panic</code>.
+If <code>D</code> returns normally, without starting a new
+<code>panic</code>, the panicking sequence stops. In that case,
+the state of functions called between <code>G</code> and the call to <code>panic</code>
+is discarded, and normal execution resumes.
+Any functions deferred by <code>G</code> before <code>D</code> are then run and <code>G</code>'s
+execution terminates by returning to its caller.
</p>
<p>
+The return value of <code>recover</code> is <code>nil</code> if any of the following conditions holds:
+</p>
+<ul>
+<li>
+<code>panic</code>'s argument was <code>nil</code>;
+</li>
+<li>
+the goroutine is not panicking;
+</li>
+<li>
+<code>recover</code> was not called directly by a deferred function.
+</li>
+</ul>
+
+<p>
The <code>protect</code> function in the example below invokes
the function argument <code>g</code> and protects callers from
run-time panics raised by <code>g</code>.
@@ -5367,7 +5598,8 @@ import . "lib/math" Sin
<p>
An import declaration declares a dependency relation between
the importing and imported package.
-It is illegal for a package to import itself or to import a package without
+It is illegal for a package to import itself, directly or indirectly,
+or to directly import a package without
referring to any of its exported identifiers. To import a package solely for
its side-effects (initialization), use the <a href="#Blank_identifier">blank</a>
identifier as explicit package name:
@@ -5495,19 +5727,23 @@ in unspecified order.
</p>
<p>
Within a package, package-level variables are initialized,
-and constant values are determined, in
-data-dependent order: if the initializer of <code>A</code>
-depends on the value of <code>B</code>, <code>A</code>
+and constant values are determined, according to
+order of reference: if the initializer of <code>A</code>
+depends on <code>B</code>, <code>A</code>
will be set after <code>B</code>.
-It is an error if such dependencies form a cycle.
-Dependency analysis is done lexically: <code>A</code>
+Dependency analysis does not depend on the actual values
+of the items being initialized, only on their appearance
+in the source.
+<code>A</code>
depends on <code>B</code> if the value of <code>A</code>
contains a mention of <code>B</code>, contains a value
whose initializer
mentions <code>B</code>, or mentions a function that
mentions <code>B</code>, recursively.
+It is an error if such dependencies form a cycle.
If two items are not interdependent, they will be initialized
-in the order they appear in the source.
+in the order they appear in the source, possibly in multiple files,
+as presented to the compiler.
Since the dependency analysis is done per package, it can produce
unspecified results if <code>A</code>'s initializer calls a function defined
in another package that refers to <code>B</code>.
@@ -5645,8 +5881,10 @@ as if <code>v</code> was declared via <code>var v = x</code>.
</p>
<p>
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.
+<code>s.f</code>, denoting a field <code>f</code> of the struct denoted by <code>s</code>
+or <code>*s</code>, and returns the field offset in bytes relative to the struct's address.
+If <code>f</code> is an <a href="#Struct_types">embedded field</a>, it must be reachable
+without pointer indirections through fields of the struct.
For a struct <code>s</code> with field <code>f</code>:
</p>
@@ -5675,7 +5913,7 @@ Calls to <code>Alignof</code>, <code>Offsetof</code>, and
<h3 id="Size_and_alignment_guarantees">Size and alignment guarantees</h3>
<p>
-For the numeric types (§<a href="#Numeric_types">Numeric types</a>), the following sizes are guaranteed:
+For the <a href="#Numeric_types">numeric types</a>, the following sizes are guaranteed:
</p>
<pre class="grammar">
diff --git a/doc/progs/eff_unused1.go b/doc/progs/eff_unused1.go
new file mode 100644
index 000000000..f990a19f7
--- /dev/null
+++ b/doc/progs/eff_unused1.go
@@ -0,0 +1,18 @@
+// skip
+
+package main
+
+import (
+ "fmt"
+ "io"
+ "log"
+ "os"
+)
+
+func main() {
+ fd, err := os.Open("test.go")
+ if err != nil {
+ log.Fatal(err)
+ }
+ // TODO: use fd.
+}
diff --git a/doc/progs/eff_unused2.go b/doc/progs/eff_unused2.go
new file mode 100644
index 000000000..3e6e041c7
--- /dev/null
+++ b/doc/progs/eff_unused2.go
@@ -0,0 +1,22 @@
+// compile
+
+package main
+
+import (
+ "fmt"
+ "io"
+ "log"
+ "os"
+)
+
+var _ = fmt.Printf // For debugging; delete when done.
+var _ io.Reader // For debugging; delete when done.
+
+func main() {
+ fd, err := os.Open("test.go")
+ if err != nil {
+ log.Fatal(err)
+ }
+ // TODO: use fd.
+ _ = fd
+}
diff --git a/doc/progs/run b/doc/progs/run
index da777f329..71759c565 100755
--- a/doc/progs/run
+++ b/doc/progs/run
@@ -16,6 +16,7 @@ effective_go="
eff_bytesize
eff_qr
eff_sequence
+ eff_unused2
"
error_handling="
diff --git a/doc/progs/unused1.go b/doc/progs/unused1.go
deleted file mode 100644
index 96a6d98a3..000000000
--- a/doc/progs/unused1.go
+++ /dev/null
@@ -1,12 +0,0 @@
-// skip
-
-package main
-
-import (
- "fmt"
- "io"
-)
-
-func main() {
- greeting := "hello, world"
-}
diff --git a/doc/progs/unused2.go b/doc/progs/unused2.go
deleted file mode 100644
index 5c5f9d74f..000000000
--- a/doc/progs/unused2.go
+++ /dev/null
@@ -1,16 +0,0 @@
-// compile
-
-package main
-
-import (
- "fmt"
- "io"
-)
-
-var _ = fmt.Printf
-var _ io.Reader
-
-func main() {
- greeting := "hello, world"
- _ = greeting
-}