diff options
author | Ondřej Surý <ondrej@sury.org> | 2012-04-06 15:14:11 +0200 |
---|---|---|
committer | Ondřej Surý <ondrej@sury.org> | 2012-04-06 15:14:11 +0200 |
commit | 505c19580e0f43fe5224431459cacb7c21edd93d (patch) | |
tree | 79e2634c253d60afc0cc0b2f510dc7dcbb48497b /doc | |
parent | 1336a7c91e596c423a49d1194ea42d98bca0d958 (diff) | |
download | golang-505c19580e0f43fe5224431459cacb7c21edd93d.tar.gz |
Imported Upstream version 1upstream/1
Diffstat (limited to 'doc')
195 files changed, 14613 insertions, 8111 deletions
diff --git a/doc/GoCourseDay1.pdf b/doc/GoCourseDay1.pdf Binary files differdeleted file mode 100644 index 5a7749c18..000000000 --- a/doc/GoCourseDay1.pdf +++ /dev/null diff --git a/doc/GoCourseDay2.pdf b/doc/GoCourseDay2.pdf Binary files differdeleted file mode 100644 index 0d82ba4d3..000000000 --- a/doc/GoCourseDay2.pdf +++ /dev/null diff --git a/doc/GoCourseDay3.pdf b/doc/GoCourseDay3.pdf Binary files differdeleted file mode 100644 index 5a5463ba2..000000000 --- a/doc/GoCourseDay3.pdf +++ /dev/null diff --git a/doc/Makefile b/doc/Makefile index e4e3f83b3..b6e475b84 100644 --- a/doc/Makefile +++ b/doc/Makefile @@ -2,10 +2,26 @@ # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. -include ../src/Make.inc +RAWHTML=\ + articles/defer_panic_recover.rawhtml\ + articles/error_handling.rawhtml\ + articles/slices_usage_and_internals.rawhtml\ + articles/laws_of_reflection.rawhtml\ + articles/c_go_cgo.rawhtml\ + articles/concurrency_patterns.rawhtml\ + articles/godoc_documenting_go_code.rawhtml\ + articles/gobs_of_data.rawhtml\ + articles/json_and_go.rawhtml\ + articles/json_rpc_tale_of_interfaces.rawhtml\ + articles/image_draw.rawhtml\ + articles/image_package.rawhtml\ + effective_go.rawhtml\ + go1.rawhtml\ -TARG=tmpltohtml -GOFILES=\ - tmpltohtml.go\ +all: $(RAWHTML) -include ../src/Make.cmd +%.rawhtml: %.html + godoc -url /doc/$< >$@ + +clean: + rm -f $(RAWHTML) diff --git a/doc/all.css b/doc/all.css deleted file mode 100644 index f8f8c653f..000000000 --- a/doc/all.css +++ /dev/null @@ -1,204 +0,0 @@ -/* General Styles */ -body { - font-family: "Bitstream Vera Sans", Verdana, sans-serif; - font-size: 81.25%; - line-height: 1.23em; - padding: 0; - margin: 1.23em; - background: white; - color: black; -} -a { - color: #04a; - text-decoration: none; -} -a:visited { - color: #04a; -} -a:hover { - color: #a40; - text-decoration: underline; -} -a:active { - color: #c00; -} -code, pre { - font-size: 1.2em; -} -pre { - background: #F0F0F0; - padding: 0.5em 1em; -} - -/* Top bar */ -#container { - width: 100%; - margin: auto; -} -#topnav { - height: 55px; - background: url(/doc/logo.png) no-repeat top left; -} -a#logo-box { - display: block; - height: 55px; -} -h1#title { - display: none; -} -#nav-main { - float: right; - width: 500px; - margin-top: -5px; - text-align: center; -} -#nav-main ul { - padding-left: 0; - margin-left: 0; - margin-bottom: 0.5em; -} -#nav-main li a { - display: inline; - display: inline-block; - padding: .46em .62em .38em .62em; -} -#nav-main li a:link, -#nav-main li a:visited { - color: #000; -} -#nav-main li { - display: inline; - display: inline-block; - background: #e6e6e6 url(/doc/button_background.png) repeat-x; - border: solid 1px #999; - margin-left: -1px; - text-shadow: #fff 0 1px 0; - box-shadow: 0 1px 1px #ccc; - -moz-box-shadow: 0 1px 1px #ccc; - -webkit-box-shadow: 0 1px 1px #ccc; -} -#nav-main li:first-child { - -moz-border-top-left-radius: 4px; - border-top-left-radius: 4px; - -moz-border-bottom-left-radius: 4px; - border-bottom-left-radius: 4px; -} -#nav-main li:last-child { - -moz-border-top-right-radius: 4px; - border-top-right-radius: 4px; - -moz-border-bottom-right-radius: 4px; - border-bottom-right-radius: 4px; -} -#nav-main .quickref { - color: #444; -} -#nav-main .quickref .sep { - color: #999; -} -#search { - width: 120px; - margin-left: 0.5em; -} -#search.inactive { - text-align: center; - color: #444; -} - -/* Footer */ -#site-info { - position: relative; - text-align: center; -} -#site-info, #site-info a:link, #site-info a:visited { - color: #aaa; -} - -/* Content */ -#content { - clear: both; - padding: 0; - position: relative; - margin-top: 1.5em; - margin-bottom: 1.5em; - border-top: solid 1px #aaa; - border-bottom: solid 1px #aaa; -} -.left-column { - width: 49%; - float: left; -} -.right-column { - width: 49%; - float: right; -} -.end-columns { - clear: both; -} -#content h1 { - padding: 0; -} -#content h2 { - border-top: 2px solid #ddd; - padding: 8px 0; - margin: 1.5em 0 0; -} -#content .subtitle { - margin-top: 1em; - display: block; -} -.navtop a { - font-weight: normal; font-size: 7pt; - float: right; color: #999; -} - -/* Content and Code Highlighting */ -pre.ebnf, pre.grammar { - background: #FFFFE0; -} -span.ln { - font-size: 80%; - color: #777777; -} -span.comment { - color: #002090; -} -span.highlight { - background: #FF9900; - font-weight: bold; -} -span.highlight-comment { - background: #FF9900; - font-weight: bold; - color: #002090; -} -span.selection { - background: #FFFF00 -} -span.selection-comment { - color: #002090; - background: #FFFF00 -} -span.selection-highlight { - background: #FF9900; - font-weight: bold; -} -span.selection-highlight-comment { - background: #FF9900; - font-weight: bold; - color: #002090; -} -span.alert { - color: #D00000; -} -#nav table { - width: 100%; -} -.detail { - padding: 0.25em 1em; - background: #F4F4F4; -} -sup.new { - color: red; - font-size: 8px; - line-height: 0; -} diff --git a/doc/articles/c_go_cgo.html b/doc/articles/c_go_cgo.html new file mode 100644 index 000000000..ac6bb29a2 --- /dev/null +++ b/doc/articles/c_go_cgo.html @@ -0,0 +1,180 @@ +<!--{ +"Title": "C? Go? Cgo!", +"Template": true +}--> + +<p> +Cgo lets Go packages call C code. Given a Go source file written with some +special features, cgo outputs Go and C files that can be combined into a +single Go package. +</p> + +<p> +To lead with an example, here's a Go package that provides two functions - +<code>Random</code> and <code>Seed</code> - that wrap C's <code>random</code> +and <code>srandom</code> functions. +</p> + +{{code "/doc/progs/cgo1.go" `/package rand/` `/END/`}} + +<p> +Let's look at what's happening here, starting with the import statement. +</p> + +<p> +The <code>rand</code> package imports <code>"C"</code>, but you'll find there's +no such package in the standard Go library. That's because <code>C</code> is a +"pseudo-package", a special name interpreted by cgo as a reference to C's +name space. +</p> + +<p> +The <code>rand</code> package contains four references to the <code>C</code> +package: the calls to <code>C.random</code> and <code>C.srandom</code>, the +conversion <code>C.uint(i)</code>, and the <code>import</code> statement. +</p> + +<p> +The <code>Random</code> function calls the standard C library's <code>random</code> +function and returns the result. In C, <code>random</code> returns a value of the +C type <code>long</code>, which cgo represents as the type <code>C.long</code>. +It must be converted to a Go type before it can be used by Go code outside this +package, using an ordinary Go type conversion: +</p> + +{{code "/doc/progs/cgo1.go" `/func Random/` `/STOP/`}} + +<p> +Here's an equivalent function that uses a temporary variable to illustrate +the type conversion more explicitly: +</p> + +{{code "/doc/progs/cgo2.go" `/func Random/` `/STOP/`}} + +<p> +The <code>Seed</code> function does the reverse, in a way. It takes a +regular Go <code>int</code>, converts it to the C <code>unsigned int</code> +type, and passes it to the C function <code>srandom</code>. +</p> + +{{code "/doc/progs/cgo1.go" `/func Seed/` `/END/`}} + +<p> +Note that cgo knows the <code>unsigned int</code> type as <code>C.uint</code>; +see the <a href="/cmd/cgo">cgo documentation</a> for a complete list of +these numeric type names. +</p> + +<p> +The one detail of this example we haven't examined yet is the comment +above the <code>import</code> statement. +</p> + +{{code "/doc/progs/cgo1.go" `/\/\*/` `/STOP/`}} + +<p> +Cgo recognizes this comment. Any lines starting +with <code>#cgo</code> +followed +by a space character are removed; these become directives for cgo. +The remaining lines are used as a header when compiling the C parts of +the package. In this case those lines are just a +single <code>#include</code> +statement, but they can be almost any C code. The <code>#cgo</code> +directives are +used to provide flags for the compiler and linker when building the C +parts of the package. +</p> + +<p> +There is a limitation: if your program uses any <code>//export</code> +directives, then the C code in the comment may only include declarations +(<code>extern int f();</code>), not definitions (<code>int f() { +return 1; }</code>). You can use <code>//export</code> directives to +make Go functions accessible to C code. +</p> + +<p> +The <code>#cgo</code> and <code>//export</code> directives are +documented in +the <a href="/cmd/cgo/">cgo documentation</a>. +</p> + +<p> +<b>Strings and things</b> +</p> + +<p> +Unlike Go, C doesn't have an explicit string type. Strings in C are +represented by a zero-terminated array of chars. +</p> + +<p> +Conversion between Go and C strings is done with the +<code>C.CString</code>, <code>C.GoString</code>, and +<code>C.GoStringN</code> functions. These conversions make a copy of the +string data. +</p> + +<p> +This next example implements a <code>Print</code> function that writes a +string to standard output using C's <code>fputs</code> function from the +<code>stdio</code> library: +</p> + +{{code "/doc/progs/cgo3.go" `/package print/` `/END/`}} + +<p> +Memory allocations made by C code are not known to Go's memory manager. +When you create a C string with <code>C.CString</code> (or any C memory +allocation) you must remember to free the memory when you're done with it +by calling <code>C.free</code>. +</p> + +<p> +The call to <code>C.CString</code> returns a pointer to the start of the +char array, so before the function exits we convert it to an +<a href="/pkg/unsafe/#Pointer"><code>unsafe.Pointer</code></a> and release +the memory allocation with <code>C.free</code>. A common idiom in cgo programs +is to <a href="/doc/articles/defer_panic_recover.html"><code>defer</code></a> +the free immediately after allocating (especially when the code that follows +is more complex than a single function call), as in this rewrite of +<code>Print</code>: +</p> + +{{code "/doc/progs/cgo4.go" `/func Print/` `/END/`}} + +<p> +<b>Building cgo packages</b> +</p> + +<p> +To build cgo packages, just use <a href="/cmd/go/#Compile_packages_and_dependencies">" +<code>go build</code>"</a> or +<a href="/cmd/go/#Compile_and_install_packages_and_dependencies">"<code>go install</code> +"</a> as usual. The go tool recognizes the special <code>"C"</code> import and automatically +uses cgo for those files. +</p> + +<p> +<b>More cgo resources</b> +</p> + +<p> +The <a href="/cmd/cgo/">cgo command</a> documentation has more detail about +the C pseudo-package and the build process. The <a href="/misc/cgo/">cgo examples</a> +in the Go tree demonstrate more advanced concepts. +</p> + +<p> +For a simple, idiomatic example of a cgo-based package, see Russ Cox's <a +href="http://code.google.com/p/gosqlite/source/browse/sqlite/sqlite.go">gosqlite</a>. +Also, the Go Project Dashboard lists <a +href="https://godashboard.appspot.com/project?tag=cgo">several other +cgo packages</a>. +</p> + +<p> +Finally, if you're curious as to how all this works internally, take a look +at the introductory comment of the runtime package's <a href="/src/pkg/runtime/cgocall.c">cgocall.c</a>. +</p> diff --git a/doc/articles/concurrency_patterns.html b/doc/articles/concurrency_patterns.html new file mode 100644 index 000000000..63c8cd59e --- /dev/null +++ b/doc/articles/concurrency_patterns.html @@ -0,0 +1,79 @@ +<!--{ +"Title": "Go Concurrency Patterns: Timing out, moving on", +"Template": true +}--> + +<p> +Concurrent programming has its own idioms. A good example is timeouts. Although +Go's channels do not support them directly, they are easy to implement. Say we +want to receive from the channel <code>ch</code>, but want to wait at most one +second for the value to arrive. We would start by creating a signalling channel +and launching a goroutine that sleeps before sending on the channel: +</p> + +{{code "/doc/progs/timeout1.go" `/timeout :=/` `/STOP/`}} + +<p> +We can then use a <code>select</code> statement to receive from either +<code>ch</code> or <code>timeout</code>. If nothing arrives on <code>ch</code> +after one second, the timeout case is selected and the attempt to read from +<cde>ch</cde> is abandoned. +</p> + +{{code "/doc/progs/timeout1.go" `/select {/` `/STOP/`}} + +<p> +The <code>timeout</code> channel is buffered with space for 1 value, allowing +the timeout goroutine to send to the channel and then exit. The goroutine +doesn't know (or care) whether the value is received. This means the goroutine +won't hang around forever if the <code>ch</code> receive happens before the +timeout is reached. The <code>timeout</code> channel will eventually be +deallocated by the garbage collector. +</p> + +<p> +(In this example we used <code>time.Sleep</code> to demonstrate the mechanics +of goroutines and channels. In real programs you should use <code> +<a href="/pkg/time/#After">time.After</a></code>, a function that returns +a channel and sends on that channel after the specified duration.) +</p> + +<p> +Let's look at another variation of this pattern. In this example we have a +program that reads from multiple replicated databases simultaneously. The +program needs only one of the answers, and it should accept the answer that +arrives first. +</p> + +<p> +The function <code>Query</code> takes a slice of database connections and a +<code>query</code> string. It queries each of the databases in parallel and +returns the first response it receives: +</p> + +{{code "/doc/progs/timeout2.go" `/func Query/` `/STOP/`}} + +<p> +In this example, the closure does a non-blocking send, which it achieves by +using the send operation in <code>select</code> statement with a +<code>default</code> case. If the send cannot go through immediately the +default case will be selected. Making the send non-blocking guarantees that +none of the goroutines launched in the loop will hang around. However, if the +result arrives before the main function has made it to the receive, the send +could fail since no one is ready. +</p> + +<p> +This problem is a textbook of example of what is known as a +<a href="https://en.wikipedia.org/wiki/Race_condition">race condition</a>, but +the fix is trivial. We just make sure to buffer the channel <code>ch</code> (by +adding the buffer length as the second argument to <a href="/pkg/builtin/#make">make</a>), +guaranteeing that the first send has a place to put the value. This ensures the +send will always succeed, and the first value to arrive will be retrieved +regardless of the order of execution. +</p> + +<p> +These two examples demonstrate the simplicity with which Go can express complex +interactions between goroutines. +</p> diff --git a/doc/articles/defer_panic_recover.html b/doc/articles/defer_panic_recover.html new file mode 100644 index 000000000..c964cd368 --- /dev/null +++ b/doc/articles/defer_panic_recover.html @@ -0,0 +1,197 @@ +<!--{ + "Title": "Defer, Panic, and Recover", + "Template": true +}--> + +<p> +Go has the usual mechanisms for control flow: if, for, switch, goto. It also +has the go statement to run code in a separate goroutine. Here I'd like to +discuss some of the less common ones: defer, panic, and recover. +</p> + +<p> +A <b>defer statement</b> pushes a function call onto a list. The list of saved +calls is executed after the surrounding function returns. Defer is commonly +used to simplify functions that perform various clean-up actions. +</p> + +<p> +For example, let's look at a function that opens two files and copies the +contents of one file to the other: +</p> + +{{code "/doc/progs/defer.go" `/func CopyFile/` `/STOP/`}} + +<p> +This works, but there is a bug. If the call to os.Create fails, the +function will return without closing the source file. This can be easily +remedied by putting a call to src.Close before the second return statement, +but if the function were more complex the problem might not be so easily +noticed and resolved. By introducing defer statements we can ensure that the +files are always closed: +</p> + +{{code "/doc/progs/defer2.go" `/func CopyFile/` `/STOP/`}} + +<p> +Defer statements allow us to think about closing each file right after opening +it, guaranteeing that, regardless of the number of return statements in the +function, the files <i>will</i> be closed. +</p> + +<p> +The behavior of defer statements is straightforward and predictable. There are +three simple rules: +</p> + +<p> +1. <i>A deferred function's arguments are evaluated when the defer statement is +evaluated.</i> +</p> + +<p> +In this example, the expression "i" is evaluated when the Println call is +deferred. The deferred call will print "0" after the function returns. +</p> + +{{code "/doc/progs/defer.go" `/func a/` `/STOP/`}} + +<p> +2. <i>Deferred function calls are executed in Last In First Out order +</i>after<i> the surrounding function returns.</i> +</p> + +<p> +This function prints "3210": +</p> + +{{code "/doc/progs/defer.go" `/func b/` `/STOP/`}} + +<p> +3. <i>Deferred functions may read and assign to the returning function's named +return values.</i> +</p> + +<p> +In this example, a deferred function increments the return value i <i>after</i> +the surrounding function returns. Thus, this function returns 2: +</p> + +{{code "/doc/progs/defer.go" `/func c/` `/STOP/`}} + +<p> +This is convenient for modifying the error return value of a function; we will +see an example of this shortly. +</p> + +<p> +<b>Panic</b> is a built-in function that stops the ordinary flow of control and +begins <i>panicking</i>. When the function F calls panic, execution of F stops, +any deferred functions in F are executed normally, and then F returns to its +caller. To the caller, F then behaves like a call to panic. The process +continues up the stack until all functions in the current goroutine have +returned, at which point the program crashes. Panics can be initiated by +invoking panic directly. They can also be caused by runtime errors, such as +out-of-bounds array accesses. +</p> + +<p> +<b>Recover</b> is a built-in function that regains control of a panicking +goroutine. Recover is only useful inside deferred functions. During normal +execution, a call to recover will return nil and have no other effect. If the +current goroutine is panicking, a call to recover will capture the value given +to panic and resume normal execution. +</p> + +<p> +Here's an example program that demonstrates the mechanics of panic and defer: +</p> + +{{code "/doc/progs/defer2.go" `/package main/` `/STOP/`}} + +<p> +The function g takes the int i, and panics if i is greater than 3, or else it +calls itself with the argument i+1. The function f defers a function that calls +recover and prints the recovered value (if it is non-nil). Try to picture what +the output of this program might be before reading on. +</p> + +<p> +The program will output: +</p> + +<pre>Calling g. +Printing in g 0 +Printing in g 1 +Printing in g 2 +Printing in g 3 +Panicking! +Defer in g 3 +Defer in g 2 +Defer in g 1 +Defer in g 0 +Recovered in f 4 +Returned normally from f.</pre> + +<p> +If we remove the deferred function from f the panic is not recovered and +reaches the top of the goroutine's call stack, terminating the program. This +modified program will output: +</p> + +<pre>Calling g. +Printing in g 0 +Printing in g 1 +Printing in g 2 +Printing in g 3 +Panicking! +Defer in g 3 +Defer in g 2 +Defer in g 1 +Defer in g 0 +panic: 4 + +panic PC=0x2a9cd8 +[stack trace omitted]</pre> + +<p> +For a real-world example of <b>panic</b> and <b>recover</b>, see the +<a href="/pkg/encoding/json/">json package</a> from the Go standard library. +It decodes JSON-encoded data with a set of recursive functions. +When malformed JSON is encountered, the parser calls panic to unwind the +stack to the top-level function call, which recovers from the panic and returns +an appropriate error value (see the 'error' and 'unmarshal' methods of +the decodeState type in +<a href="/src/pkg/encoding/json/decode.go">decode.go</a>). +</p> + +<p> +The convention in the Go libraries is that even when a package uses panic +internally, its external API still presents explicit error return values. +</p> + +<p> +Other uses of <b>defer</b> (beyond the file.Close example given earlier) +include releasing a mutex: +</p> + +<pre>mu.Lock() +defer mu.Unlock()</pre> + +<p> +printing a footer: +</p> + +<pre>printHeader() +defer printFooter()</pre> + +<p> +and more. +</p> + +<p> +In summary, the defer statement (with or without panic and recover) provides an +unusual and powerful mechanism for control flow. It can be used to model a +number of features implemented by special-purpose structures in other +programming languages. Try it out. +</p> diff --git a/doc/articles/error_handling.html b/doc/articles/error_handling.html new file mode 100644 index 000000000..8f4fffb48 --- /dev/null +++ b/doc/articles/error_handling.html @@ -0,0 +1,316 @@ +<!--{ + "Title": "Error Handling and Go", + "Template": true +}--> + +<p> +If you have written any Go code you have probably encountered the built-in +<code>error</code> type. Go code uses <code>error</code> values to +indicate an abnormal state. For example, the <code>os.Open</code> function +returns a non-nil <code>error</code> value when it fails to open a file. +</p> + +{{code "/doc/progs/error.go" `/func Open/`}} + +<p> +The following code uses <code>os.Open</code> to open a file. If an error +occurs it calls <code>log.Fatal</code> to print the error message and stop. +</p> + +{{code "/doc/progs/error.go" `/func openFile/` `/STOP/`}} + +<p> +You can get a lot done in Go knowing just this about the <code>error</code> +type, but in this article we'll take a closer look at <code>error</code> and +discuss some good practices for error handling in Go. +</p> + +<p> +<b>The error type</b> +</p> + +<p> +The <code>error</code> type is an interface type. An <code>error</code> +variable represents any value that can describe itself as a string. Here is the +interface's declaration: +</p> + +<pre>type error interface { + Error() string +}</pre> + +<p> +The <code>error</code> type, as with all built in types, is +<a href="/doc/go_spec.html#Predeclared_identifiers">predeclared</a> in the +<a href="/doc/go_spec.html#Blocks">universe block</a>. +</p> + +<p> +The most commonly-used <code>error</code> implementation is the +<a href="/pkg/errors/">errors</a> package's unexported <code>errorString</code> type. +</p> + +{{code "/doc/progs/error.go" `/errorString/` `/STOP/`}} + +<p> +You can construct one of these values with the <code>errors.New</code> +function. It takes a string that it converts to an <code>errors.errorString</code> +and returns as an <code>error</code> value. +</p> + +{{code "/doc/progs/error.go" `/New/` `/STOP/`}} + +<p> +Here's how you might use <code>errors.New</code>: +</p> + +{{code "/doc/progs/error.go" `/func Sqrt/` `/STOP/`}} + +<p> +A caller passing a negative argument to <code>Sqrt</code> receives a non-nil +<code>error</code> value (whose concrete representation is an +<code>errors.errorString</code> value). The caller can access the error string +("math: square root of...") by calling the <code>error</code>'s +<code>Error</code> method, or by just printing it: +</p> + +{{code "/doc/progs/error.go" `/func printErr/` `/STOP/`}} + +<p> +The <a href="/pkg/fmt/">fmt</a> package formats an <code>error</code> value +by calling its <code>Error() string</code> method. +</p> + +<p> +It is the error implementation's responsibility to summarize the context. +The error returned by <code>os.Open</code> formats as "open /etc/passwd: +permission denied," not just "permission denied." The error returned by our +<code>Sqrt</code> is missing information about the invalid argument. +</p> + +<p> +To add that information, a useful function is the <code>fmt</code> package's +<code>Errorf</code>. It formats a string according to <code>Printf</code>'s +rules and returns it as an <code>error</code> created by +<code>errors.New</code>. +</p> + +{{code "/doc/progs/error.go" `/fmtError/` `/STOP/`}} + +<p> +In many cases <code>fmt.Errorf</code> is good enough, but since +<code>error</code> is an interface, you can use arbitrary data structures as +error values, to allow callers to inspect the details of the error. +</p> + +<p> +For instance, our hypothetical callers might want to recover the invalid +argument passed to <code>Sqrt</code>. We can enable that by defining a new +error implementation instead of using <code>errors.errorString</code>: +</p> + +{{code "/doc/progs/error.go" `/type NegativeSqrtError/` `/STOP/`}} + +<p> +A sophisticated caller can then use a +<a href="/doc/go_spec.html#Type_assertions">type assertion</a> to check for a +<code>NegativeSqrtError</code> and handle it specially, while callers that just +pass the error to <code>fmt.Println</code> or <code>log.Fatal</code> will see +no change in behavior. +</p> + +<p> +As another example, the <a href="/pkg/encoding/json/">json</a> package specifies a +<code>SyntaxError</code> type that the <code>json.Decode</code> function +returns when it encounters a syntax error parsing a JSON blob. +</p> + +{{code "/doc/progs/error.go" `/type SyntaxError/` `/STOP/`}} + +<p> +The <code>Offset</code> field isn't even shown in the default formatting of the +error, but callers can use it to add file and line information to their error +messages: +</p> + +{{code "/doc/progs/error.go" `/func decodeError/` `/STOP/`}} + +<p> +(This is a slightly simplified version of some +<a href="http://camlistore.org/code/?p=camlistore.git;a=blob;f=lib/go/camli/jsonconfig/eval.go#l68">actual code</a> +from the <a href="http://camlistore.org">Camlistore</a> project.) +</p> + +<p> +The <code>error</code> interface requires only a <code>Error</code> method; +specific error implementations might have additional methods. For instance, the +<a href="/pkg/net/">net</a> package returns errors of type +<code>error</code>, following the usual convention, but some of the error +implementations have additional methods defined by the <code>net.Error</code> +interface: +</p> + +<pre>package net + +type Error interface { + error + Timeout() bool // Is the error a timeout? + Temporary() bool // Is the error temporary? +}</pre> + +<p> +Client code can test for a <code>net.Error</code> with a type assertion and +then distinguish transient network errors from permanent ones. For instance, a +web crawler might sleep and retry when it encounters a temporary error and give +up otherwise. +</p> + +{{code "/doc/progs/error.go" `/func netError/` `/STOP/`}} + +<p> +<b>Simplifying repetitive error handling</b> +</p> + +<p> +In Go, error handling is important. The language's design and conventions +encourage you to explicitly check for errors where they occur (as distinct from +the convention in other languages of throwing exceptions and sometimes catching +them). In some cases this makes Go code verbose, but fortunately there are some +techniques you can use to minimize repetitive error handling. +</p> + +<p> +Consider an <a href="http://code.google.com/appengine/docs/go/">App Engine</a> +application with an HTTP handler that retrieves a record from the datastore and +formats it with a template. +</p> + +{{code "/doc/progs/error2.go" `/func init/` `/STOP/`}} + +<p> +This function handles errors returned by the <code>datastore.Get</code> +function and <code>viewTemplate</code>'s <code>Execute</code> method. In both +cases, it presents a simple error message to the user with the HTTP status code +500 ("Internal Server Error"). This looks like a manageable amount of code, but +add some more HTTP handlers and you quickly end up with many copies of +identical error handling code. +</p> + +<p> +To reduce the repetition we can define our own HTTP <code>appHandler</code> +type that includes an <code>error</code> return value: +</p> + +{{code "/doc/progs/error3.go" `/type appHandler/`}} + +<p> +Then we can change our <code>viewRecord</code> function to return errors: +</p> + +{{code "/doc/progs/error3.go" `/func viewRecord/` `/STOP/`}} + +<p> +This is simpler than the original version, but the <a +href="/pkg/net/http/">http</a> package doesn't understand functions that return +<code>error</code>. +To fix this we can implement the <code>http.Handler</code> interface's +<code>ServeHTTP</code> method on <code>appHandler</code>: +</p> + +{{code "/doc/progs/error3.go" `/ServeHTTP/` `/STOP/`}} + +<p> +The <code>ServeHTTP</code> method calls the <code>appHandler</code> function +and displays the returned error (if any) to the user. Notice that the method's +receiver, <code>fn</code>, is a function. (Go can do that!) The method invokes +the function by calling the receiver in the expression <code>fn(w, r)</code>. +</p> + +<p> +Now when registering <code>viewRecord</code> with the http package we use the +<code>Handle</code> function (instead of <code>HandleFunc</code>) as +<code>appHandler</code> is an <code>http.Handler</code> (not an +<code>http.HandlerFunc</code>). +</p> + +{{code "/doc/progs/error3.go" `/func init/` `/STOP/`}} + +<p> +With this basic error handling infrastructure in place, we can make it more +user friendly. Rather than just displaying the error string, it would be better +to give the user a simple error message with an appropriate HTTP status code, +while logging the full error to the App Engine developer console for debugging +purposes. +</p> + +<p> +To do this we create an <code>appError</code> struct containing an +<code>error</code> and some other fields: +</p> + +{{code "/doc/progs/error4.go" `/type appError/` `/STOP/`}} + +<p> +Next we modify the appHandler type to return <code>*appError</code> values: +</p> + +{{code "/doc/progs/error4.go" `/type appHandler/`}} + +<p> +(It's usually a mistake to pass back the concrete type of an error rather than +<code>error</code>, +for reasons discussed in <a href="/doc/go_faq.html#nil_error">the Go FAQ</a>, +but it's the right thing to do here because <code>ServeHTTP</code> is the only +place that sees the value and uses its contents.) +</p> + +<p> +And make <code>appHandler</code>'s <code>ServeHTTP</code> method display the +<code>appError</code>'s <code>Message</code> to the user with the correct HTTP +status <code>Code</code> and log the full <code>Error</code> to the developer +console: +</p> + +{{code "/doc/progs/error4.go" `/ServeHTTP/` `/STOP/`}} + +<p> +Finally, we update <code>viewRecord</code> to the new function signature and +have it return more context when it encounters an error: +</p> + +{{code "/doc/progs/error4.go" `/func viewRecord/` `/STOP/`}} + +<p> +This version of <code>viewRecord</code> is the same length as the original, but +now each of those lines has specific meaning and we are providing a friendlier +user experience. +</p> + +<p> +It doesn't end there; we can further improve the error handling in our +application. Some ideas: +</p> + +<ul> +<li>give the error handler a pretty HTML template, +<li>make debugging easier by writing the stack trace to the HTTP response when +the user is an administrator, +<li>write a constructor function for <code>appError</code> that stores the +stack trace for easier debugging, +<li>recover from panics inside the <code>appHandler</code>, logging the error +to the console as "Critical," while telling the user "a serious error +has occurred." This is a nice touch to avoid exposing the user to inscrutable +error messages caused by programming errors. +See the <a href="defer_panic_recover.html">Defer, Panic, and Recover</a> +article for more details. +</ul> + +<p> +<b>Conclusion</b> +</p> + +<p> +Proper error handling is an essential requirement of good software. By +employing the techniques described in this post you should be able to write +more reliable and succinct Go code. +</p> diff --git a/doc/articles/go_command.html b/doc/articles/go_command.html new file mode 100644 index 000000000..1e9e70fd8 --- /dev/null +++ b/doc/articles/go_command.html @@ -0,0 +1,265 @@ +<!--{ + "title": "About the go command" +}--> + +<p>The Go distribution includes a command, named +"<code><a href="/cmd/go/">go</a></code>", that +automates the downloading, building, installation, and testing of Go packages +and commands. This document talks about why we wrote a new command, what it +is, what it's not, and how to use it.</p> + +<h2>Motivation</h2> + +<p>You might have seen early Go talks in which Rob Pike jokes that the idea +for Go arose while waiting for a large Google server to compile. That +really was the motivation for Go: to build a language that worked well +for building the large software that Google writes and runs. It was +clear from the start that such a language must provide a way to +express dependencies between code libraries clearly, hence the package +grouping and the explicit import blocks. It was also clear from the +start that you might want arbitrary syntax for describing the code +being imported; this is why import paths are string literals.</p> + +<p>An explicit goal for Go from the beginning was to be able to build Go +code using only the information found in the source itself, not +needing to write a makefile or one of the many modern replacements for +makefiles. If Go needed a configuration file to explain how to build +your program, then Go would have failed.</p> + +<p>At first, there was no Go compiler, and the initial development +focused on building one and then building libraries for it. For +expedience, we postponed the automation of building Go code by using +make and writing makefiles. When compiling a single package involved +multiple invocations of the Go compiler, we even used a program to +write the makefiles for us. You can find it if you dig through the +repository history.</p> + +<p>The purpose of the new go command is our return to this ideal, that Go +programs should compile without configuration or additional effort on +the part of the developer beyond writing the necessary import +statements.</p> + +<h2>Configuration versus convention</h2> + +<p>The way to achieve the simplicity of a configuration-free system is to +establish conventions. The system works only to the extent that those conventions +are followed. When we first launched Go, many people published packages that +had to be installed in certain places, under certain names, using certain build +tools, in order to be used. That's understandable: that's the way it works in +most other languages. Over the last few years we consistently reminded people +about the <code>goinstall</code> command +(now replaced by <a href="/cmd/go/#Download_and_install_packages_and_dependencies"><code>go get</code></a>) +and its conventions: first, that the import path is derived in a known way from +the URL of the source code; second, that that the place to store the sources in +the local file system is derived in a known way from the import path; third, +that each directory in a source tree corresponds to a single package; and +fourth, that the package is built using only information in the source code. +Today, the vast majority of packages follow these conventions. +The Go ecosystem is simpler and more powerful as a result.</p> + +<p>We received many requests to allow a makefile in a package directory to +provide just a little extra configuration beyond what's in the source code. +But that would have introduced new rules. Because we did not accede to such +requests, we were able to write the go command and eliminate our use of make +or any other build system.</p> + +<p>It is important to understand that the go command is not a general +build tool. It cannot be configured and it does not attempt to build +anything but Go packages. These are important simplifying +assumptions: they simplify not only the implementation but also, more +important, the use of the tool itself.</p> + +<h2>Go's conventions</h2> + +<p>The <code>go</code> command requires that code adheres to a few key, +well-established conventions.</p> + +<p>First, the import path is derived in an known way from the URL of the +source code. For Bitbucket, GitHub, Google Code, and Launchpad, the +root directory of the repository is identified by the repository's +main URL, without the <code>http://</code> prefix. Subdirectories are named by +adding to that path. For example, the supplemental networking +libraries for Go are obtained by running</p> + +<pre> +hg clone http://code.google.com/p/go.net +</pre> + +<p>and thus the import path for the root directory of that repository is +"<code>code.google.com/p/go.net</code>". The websocket package is stored in a +subdirectory, so its import path is +"<code>code.google.com/p/go.net/websocket</code>".</p> + +<p>These paths are on the long side, but in exchange we get an +automatically managed name space for import paths and the ability for +a tool like the go command to look at an unfamiliar import path and +deduce where to obtain the source code.</p> + +<p>Second, the place to store sources in the local file system is derived +in a known way from the import path. Specifically, the first choice +is <code>$GOPATH/src/<import-path></code>. If <code>$GOPATH</code> is +unset, the go command will fall back to storing source code alongside the +standard Go packages, in <code>$GOROOT/src/pkg/<import-path></code>. +If <code>$GOPATH</code> is set to a list of paths, the go command tries +<code><dir>/src/<import-path></code> for each of the directories in +that list.</p> + +<p>Each of those trees contains, by convention, a top-level directory named +"<code>bin</code>", for holding compiled executables, and a top-level directory +named "<code>pkg</code>", for holding compiled packages that can be imported, +and the "<code>src</code>" directory, for holding package source files. +Imposing this structure lets us keep each of these directory trees +self-contained: the compiled form and the sources are always near each +other.</p> + +<p>These naming conventions also let us work in the reverse direction, +from a directory name to its import path. This mapping is important +for many of the go command's subcommands, as we'll see below.</p> + +<p>Third, each directory in a source tree corresponds to a single +package. By restricting a directory to a single package, we don't have +to create hybrid import paths that specify first the directory and +then the package within that directory. Also, most file management +tools and UIs work on directories as fundamental units. Tying the +fundamental Go unit—the package—to file system structure means +that file system tools become Go package tools. Copying, moving, or +deleting a package corresponds to copying, moving, or deleting a +directory.</p> + +<p>Fourth, each package is built using only the information present in +the source files. This makes it much more likely that the tool will +be able to adapt to changing build environments and conditions. For +example, if we allowed extra configuration such as compiler flags or +command line recipes, then that configuration would need to be updated +each time the build tools changed; it would also be inherently tied +to the use of a specific tool chain.</p> + +<h2>Getting started with the go command</h2> + +<p>Finally, a quick tour of how to use the go command, to supplement +the information in <a href="/doc/code.html">How to Write Go Code</a>, +which you might want to read first. Assuming you want +to keep your source code separate from the Go distribution source +tree, the first step is to set <code>$GOPATH</code>, the one piece of global +configuration that the go command needs. The <code>$GOPATH</code> can be a +list of directories, but by far the most common usage should be to set it to a +single directory. In particular, you do not need a separate entry in +<code>$GOPATH</code> for each of your projects. One <code>$GOPATH</code> can +support many projects.</p> + +<p>Here’s an example. Let’s say we decide to keep our Go code in the directory +<code>$HOME/mygo</code>. We need to create that directory and set +<code>$GOPATH</code> accordingly.</p> + +<pre> +$ mkdir $HOME/mygo +$ export GOPATH=$HOME/mygo +$ +</pre> + +<p>Into this directory, we now add some source code. Suppose we want to use +the indexing library from the codesearch project along with a left-leaning +red-black tree. We can install both with the "<code>go get</code>" +subcommand:</p> + +<pre> +$ go get code.google.com/p/codesearch/index +$ go get github.com/petar/GoLLRB/llrb +$ +</pre> + +<p>Both of these projects are now downloaded and installed into our +<code>$GOPATH</code> directory. The one tree now contains the two directories +<code>src/code.google.com/p/codesearch/index/</code> and +<code>src/github.com/petar/GoLLRB/llrb/</code>, along with the compiled +packages (in <code>pkg/</code>) for those libraries and their dependencies.</p> + +<p>Because we used version control systems (Mercurial and Git) to check +out the sources, the source tree also contains the other files in the +corresponding repositories, such as related packages. The "<code>go list</code>" +subcommand lists the import paths corresponding to its arguments, and +the pattern "<code>./...</code>" means start in the current directory +("<code>./</code>") and find all packages below that directory +("<code>...</code>"):</p> + +<pre> +$ go list ./... +code.google.com/p/codesearch/cmd/cgrep +code.google.com/p/codesearch/cmd/cindex +code.google.com/p/codesearch/cmd/csearch +code.google.com/p/codesearch/index +code.google.com/p/codesearch/regexp +code.google.com/p/codesearch/sparse +github.com/petar/GoLLRB/example +github.com/petar/GoLLRB/llrb +$ +</pre> + +<p>We can also test those packages:</p> + +<pre> +$ go test ./... +? code.google.com/p/codesearch/cmd/cgrep [no test files] +? code.google.com/p/codesearch/cmd/cindex [no test files] +? code.google.com/p/codesearch/cmd/csearch [no test files] +ok code.google.com/p/codesearch/index 0.239s +ok code.google.com/p/codesearch/regexp 0.021s +? code.google.com/p/codesearch/sparse [no test files] +? github.com/petar/GoLLRB/example [no test files] +ok github.com/petar/GoLLRB/llrb 0.231s +$ +</pre> + +<p>If a go subcommand is invoked with no paths listed, it operates on the +current directory:</p> + +<pre> +$ cd $GOPATH/src/code.google.com/p/codesearch/regexp +$ go list +code.google.com/p/codesearch/regexp +$ go test -v +=== RUN TestNstateEnc +--- PASS: TestNstateEnc (0.00 seconds) +=== RUN TestMatch +--- PASS: TestMatch (0.01 seconds) +=== RUN TestGrep +--- PASS: TestGrep (0.00 seconds) +PASS +ok code.google.com/p/codesearch/regexp 0.021s +$ go install +$ +</pre> + +<p>That "<code>go install</code>" subcommand installs the latest copy of the +package into the pkg directory. Because the go command can analyze the +dependency graph, "<code>go install</code>" also installs any packages that +this package imports but that are out of date, recursively.</p> + +<p>Notice that "<code>go install</code>" was able to determine the name of the +import path for the package in the current directory, because of the convention +for directory naming. It would be a little more convenient if we could pick +the name of the directory where we kept source code, and we probably wouldn't +pick such a long name, but that ability would require additional configuration +and complexity in the tool. Typing an extra directory name or two is a small +price to pay for the increased simplicity and power.</p> + +<p>As the example shows, it’s fine to work with packages from many different +projects at once within a single <code>$GOPATH</code> root directory.</p> + +<h2>Limitations</h2> + +<p>As mentioned above, the go command is not a general-purpose build +tool. In particular, it does not have any facility for generating Go +source files during a build. Instead, if you want to use a tool like +yacc or the protocol buffer compiler, you will need to write a +makefile (or a configuration file for the build tool of your choice) +to generate the Go files and then check those generated source files +into your repository. This is more work for you, the package author, +but it is significantly less work for your users, who can use +"<code>go get</code>" without needing to obtain and build +any additional tools.</p> + +<h2>More information</h2> + +<p>For more information, read <a href="/doc/code.html">How to Write Go Code</a> +and see the <a href="/cmd/go/">go command documentation</a>.</p> diff --git a/doc/articles/gobs_of_data.html b/doc/articles/gobs_of_data.html new file mode 100644 index 000000000..6b836b2c3 --- /dev/null +++ b/doc/articles/gobs_of_data.html @@ -0,0 +1,315 @@ +<!--{ +"Title": "Gobs of data", +"Template": true +}--> + +<p> +To transmit a data structure across a network or to store it in a file, it must +be encoded and then decoded again. There are many encodings available, of +course: <a href="http://www.json.org/">JSON</a>, +<a href="http://www.w3.org/XML/">XML</a>, Google's +<a href="http://code.google.com/p/protobuf">protocol buffers</a>, and more. +And now there's another, provided by Go's <a href="/pkg/encoding/gob/">gob</a> +package. +</p> + +<p> +Why define a new encoding? It's a lot of work and redundant at that. Why not +just use one of the existing formats? Well, for one thing, we do! Go has +<a href="/pkg/">packages</a> supporting all the encodings just mentioned (the +<a href="http://code.google.com/p/goprotobuf">protocol buffer package</a> is in +a separate repository but it's one of the most frequently downloaded). And for +many purposes, including communicating with tools and systems written in other +languages, they're the right choice. +</p> + +<p> +But for a Go-specific environment, such as communicating between two servers +written in Go, there's an opportunity to build something much easier to use and +possibly more efficient. +</p> + +<p> +Gobs work with the language in a way that an externally-defined, +language-independent encoding cannot. At the same time, there are lessons to be +learned from the existing systems. +</p> + +<p> +<b>Goals</b> +</p> + +<p> +The gob package was designed with a number of goals in mind. +</p> + +<p> +First, and most obvious, it had to be very easy to use. First, because Go has +reflection, there is no need for a separate interface definition language or +"protocol compiler". The data structure itself is all the package should need +to figure out how to encode and decode it. On the other hand, this approach +means that gobs will never work as well with other languages, but that's OK: +gobs are unashamedly Go-centric. +</p> + +<p> +Efficiency is also important. Textual representations, exemplified by XML and +JSON, are too slow to put at the center of an efficient communications network. +A binary encoding is necessary. +</p> + +<p> +Gob streams must be self-describing. Each gob stream, read from the beginning, +contains sufficient information that the entire stream can be parsed by an +agent that knows nothing a priori about its contents. This property means that +you will always be able to decode a gob stream stored in a file, even long +after you've forgotten what data it represents. +</p> + +<p> +There were also some things to learn from our experiences with Google protocol +buffers. +</p> + +<p> +<b>Protocol buffer misfeatures</b> +</p> + +<p> +Protocol buffers had a major effect on the design of gobs, but have three +features that were deliberately avoided. (Leaving aside the property that +protocol buffers aren't self-describing: if you don't know the data definition +used to encode a protocol buffer, you might not be able to parse it.) +</p> + +<p> +First, protocol buffers only work on the data type we call a struct in Go. You +can't encode an integer or array at the top level, only a struct with fields +inside it. That seems a pointless restriction, at least in Go. If all you want +to send is an array of integers, why should you have to put it into a +struct first? +</p> + +<p> +Next, a protocol buffer definition may specify that fields <code>T.x</code> and +<code>T.y</code> are required to be present whenever a value of type +<code>T</code> is encoded or decoded. Although such required fields may seem +like a good idea, they are costly to implement because the codec must maintain a +separate data structure while encoding and decoding, to be able to report when +required fields are missing. They're also a maintenance problem. Over time, one +may want to modify the data definition to remove a required field, but that may +cause existing clients of the data to crash. It's better not to have them in the +encoding at all. (Protocol buffers also have optional fields. But if we don't +have required fields, all fields are optional and that's that. There will be +more to say about optional fields a little later.) +</p> + +<p> +The third protocol buffer misfeature is default values. If a protocol buffer +omits the value for a "defaulted" field, then the decoded structure behaves as +if the field were set to that value. This idea works nicely when you have +getter and setter methods to control access to the field, but is harder to +handle cleanly when the container is just a plain idiomatic struct. Required +fields are also tricky to implement: where does one define the default values, +what types do they have (is text UTF-8? uninterpreted bytes? how many bits in a +float?) and despite the apparent simplicity, there were a number of +complications in their design and implementation for protocol buffers. We +decided to leave them out of gobs and fall back to Go's trivial but effective +defaulting rule: unless you set something otherwise, it has the "zero value" +for that type - and it doesn't need to be transmitted. +</p> + +<p> +So gobs end up looking like a sort of generalized, simplified protocol buffer. +How do they work? +</p> + +<p> +<b>Values</b> +</p> + +<p> +The encoded gob data isn't about <code>int8</code>s and <code>uint16</code>s. +Instead, somewhat analogous to constants in Go, its integer values are abstract, +sizeless numbers, either signed or unsigned. When you encode an +<code>int8</code>, its value is transmitted as an unsized, variable-length +integer. When you encode an <code>int64</code>, its value is also transmitted as +an unsized, variable-length integer. (Signed and unsigned are treated +distinctly, but the same unsized-ness applies to unsigned values too.) If both +have the value 7, the bits sent on the wire will be identical. When the receiver +decodes that value, it puts it into the receiver's variable, which may be of +arbitrary integer type. Thus an encoder may send a 7 that came from an +<code>int8</code>, but the receiver may store it in an <code>int64</code>. This +is fine: the value is an integer and as a long as it fits, everything works. (If +it doesn't fit, an error results.) This decoupling from the size of the variable +gives some flexibility to the encoding: we can expand the type of the integer +variable as the software evolves, but still be able to decode old data. +</p> + +<p> +This flexibility also applies to pointers. Before transmission, all pointers are +flattened. Values of type <code>int8</code>, <code>*int8</code>, +<code>**int8</code>, <code>****int8</code>, etc. are all transmitted as an +integer value, which may then be stored in <code>int</code> of any size, or +<code>*int</code>, or <code>******int</code>, etc. Again, this allows for +flexibility. +</p> + +<p> +Flexibility also happens because, when decoding a struct, only those fields +that are sent by the encoder are stored in the destination. Given the value +</p> + +{{code "/doc/progs/gobs1.go" `/type T/` `/STOP/`}} + +<p> +the encoding of <code>t</code> sends only the 7 and 8. Because it's zero, the +value of <code>Y</code> isn't even sent; there's no need to send a zero value. +</p> + +<p> +The receiver could instead decode the value into this structure: +</p> + +{{code "/doc/progs/gobs1.go" `/type U/` `/STOP/`}} + +<p> +and acquire a value of <code>u</code> with only <code>X</code> set (to the +address of an <code>int8</code> variable set to 7); the <code>Z</code> field is +ignored - where would you put it? When decoding structs, fields are matched by +name and compatible type, and only fields that exist in both are affected. This +simple approach finesses the "optional field" problem: as the type +<code>T</code> evolves by adding fields, out of date receivers will still +function with the part of the type they recognize. Thus gobs provide the +important result of optional fields - extensibility - without any additional +mechanism or notation. +</p> + +<p> +From integers we can build all the other types: bytes, strings, arrays, slices, +maps, even floats. Floating-point values are represented by their IEEE 754 +floating-point bit pattern, stored as an integer, which works fine as long as +you know their type, which we always do. By the way, that integer is sent in +byte-reversed order because common values of floating-point numbers, such as +small integers, have a lot of zeros at the low end that we can avoid +transmitting. +</p> + +<p> +One nice feature of gobs that Go makes possible is that they allow you to define +your own encoding by having your type satisfy the +<a href="/pkg/encoding/gob/#GobEncoder">GobEncoder</a> and +<a href="/pkg/encoding/gob/#GobDecoder">GobDecoder</a> interfaces, in a manner +analogous to the <a href="/pkg/encoding/json/">JSON</a> package's +<a href="/pkg/encoding/json/#Marshaler">Marshaler</a> and +<a href="/pkg/encoding/json/#Unmarshaler">Unmarshaler</a> and also to the +<a href="/pkg/fmt/#Stringer">Stringer</a> interface from +<a href="/pkg/fmt/">package fmt</a>. This facility makes it possible to +represent special features, enforce constraints, or hide secrets when you +transmit data. See the <a href="/pkg/encoding/gob/">documentation</a> for +details. +</p> + +<p> +<b>Types on the wire</b> +</p> + +<p> +The first time you send a given type, the gob package includes in the data +stream a description of that type. In fact, what happens is that the encoder is +used to encode, in the standard gob encoding format, an internal struct that +describes the type and gives it a unique number. (Basic types, plus the layout +of the type description structure, are predefined by the software for +bootstrapping.) After the type is described, it can be referenced by its type +number. +</p> + +<p> +Thus when we send our first type <code>T</code>, the gob encoder sends a +description of <code>T</code> and tags it with a type number, say 127. All +values, including the first, are then prefixed by that number, so a stream of +<code>T</code> values looks like: +</p> + +<pre> +("define type id" 127, definition of type T)(127, T value)(127, T value), ... +</pre> + +<p> +These type numbers make it possible to describe recursive types and send values +of those types. Thus gobs can encode types such as trees: +</p> + +{{code "/doc/progs/gobs1.go" `/type Node/` `/STOP/`}} + +<p> +(It's an exercise for the reader to discover how the zero-defaulting rule makes +this work, even though gobs don't represent pointers.) +</p> + +<p> +With the type information, a gob stream is fully self-describing except for the +set of bootstrap types, which is a well-defined starting point. +</p> + +<p> +<b>Compiling a machine</b> +</p> + +<p> +The first time you encode a value of a given type, the gob package builds a +little interpreted machine specific to that data type. It uses reflection on +the type to construct that machine, but once the machine is built it does not +depend on reflection. The machine uses package unsafe and some trickery to +convert the data into the encoded bytes at high speed. It could use reflection +and avoid unsafe, but would be significantly slower. (A similar high-speed +approach is taken by the protocol buffer support for Go, whose design was +influenced by the implementation of gobs.) Subsequent values of the same type +use the already-compiled machine, so they can be encoded right away. +</p> + +<p> +Decoding is similar but harder. When you decode a value, the gob package holds +a byte slice representing a value of a given encoder-defined type to decode, +plus a Go value into which to decode it. The gob package builds a machine for +that pair: the gob type sent on the wire crossed with the Go type provided for +decoding. Once that decoding machine is built, though, it's again a +reflectionless engine that uses unsafe methods to get maximum speed. +</p> + +<p> +<b>Use</b> +</p> + +<p> +There's a lot going on under the hood, but the result is an efficient, +easy-to-use encoding system for transmitting data. Here's a complete example +showing differing encoded and decoded types. Note how easy it is to send and +receive values; all you need to do is present values and variables to the +<a href="/pkg/encoding/gob/">gob package</a> and it does all the work. +</p> + +{{code "/doc/progs/gobs2.go" `/package main/` `$`}} + +<p> +You can compile and run this example code in the +<a href="http://play.golang.org/p/_-OJV-rwMq">Go Playground</a>. +</p> + +<p> +The <a href="/pkg/net/rpc/">rpc package</a> builds on gobs to turn this +encode/decode automation into transport for method calls across the network. +That's a subject for another article. +</p> + +<p> +<b>Details</b> +</p> + +<p> +The <a href="/pkg/encoding/gob/">gob package documentation</a>, especially the +file <a href="/src/pkg/encoding/gob/doc.go">doc.go</a>, expands on many of the +details described here and includes a full worked example showing how the +encoding represents data. If you are interested in the innards of the gob +implementation, that's a good place to start. +</p> diff --git a/doc/articles/godoc_documenting_go_code.html b/doc/articles/godoc_documenting_go_code.html new file mode 100644 index 000000000..ca66076ad --- /dev/null +++ b/doc/articles/godoc_documenting_go_code.html @@ -0,0 +1,139 @@ +<!--{ +"Title": "Godoc: documenting Go code", +"Template": true +}--> + +<p> +The Go project takes documentation seriously. Documentation is a huge part of +making software accessible and maintainable. Of course it must be well-written +and accurate, but it also must be easy to write and to maintain. Ideally, it +should be coupled to the code itself so the documentation evolves along with the +code. The easier it is for programmers to produce good documentation, the better +for everyone. +</p> + +<p> +To that end, we have developed the <a href="/cmd/godoc/">godoc</a> documentation +tool. This article describes godoc's approach to documentation, and explains how +you can use our conventions and tools to write good documentation for your own +projects. +</p> + +<p> +Godoc parses Go source code - including comments - and produces documentation as +HTML or plain text. The end result is documentation tightly coupled with the +code it documents. For example, through godoc's web interface you can navigate +from a function's <a href="/pkg/strings/#HasPrefix">documentation</a> to its +<a href="/src/pkg/strings/strings.go?#L312">implementation</a> with one click. +</p> + +<p> +Godoc is conceptually related to Python's +<a href="http://www.python.org/dev/peps/pep-0257/">Docstring</a> and Java's +<a href="http://www.oracle.com/technetwork/java/javase/documentation/index-jsp-135444.html">Javadoc</a>, +but its design is simpler. The comments read by godoc are not language +constructs (as with Docstring) nor must they have their own machine-readable +syntax (as with Javadoc). Godoc comments are just good comments, the sort you +would want to read even if godoc didn't exist. +</p> + +<p> +The convention is simple: to document a type, variable, constant, function, or +even a package, write a regular comment directly preceding its declaration, with +no intervening blank line. Godoc will then present that comment as text +alongside the item it documents. For example, this is the documentation for the +<code>fmt</code> package's <a href="/pkg/fmt/#Fprint"><code>Fprint</code></a> +function: +</p> + +{{code "/src/pkg/fmt/print.go" `/Fprint formats using the default/` `/func Fprint/`}} + +<p> +Notice this comment is a complete sentence that begins with the name of the +element it describes. This important convention allows us to generate +documentation in a variety of formats, from plain text to HTML to UNIX man +pages, and makes it read better when tools truncate it for brevity, such as when +they extract the first line or sentence. +</p> + +<p> +Comments on package declarations should provide general package documentation. +These comments can be short, like the <a href="/pkg/sort/"><code>sort</code></a> +package's brief description: +</p> + +{{code "/src/pkg/sort/sort.go" `/Package sort provides/` `/package sort/`}} + +<p> +They can also be detailed like the <a href="/pkg/encoding/gob/">gob package</a>'s +overview. That package uses another convention for packages +that need large amounts of introductory documentation: the package comment is +placed in its own file, <a href="/src/pkg/encoding/gob/doc.go">doc.go</a>, which +contains only those comments and a package clause. +</p> + +<p> +When writing package comments of any size, keep in mind that their first +sentence will appear in godoc's <a href="/pkg/">package list</a>. +</p> + +<p> +Comments that are not adjacent to a top-level declaration are omitted from +godoc's output, with one notable exception. Top-level comments that begin with +the word <code>"BUG(who)”</code> are recognized as known bugs, and included in +the "Bugs” section of the package documentation. The "who” part should be the +user name of someone who could provide more information. For example, this is a +known issue from the <a href="/pkg/bytes/#bugs">bytes package</a>: +</p> + +<pre> +// BUG(r): The rule Title uses for word boundaries does not handle Unicode punctuation properly. +</pre> + +<p> +Godoc treats executable commands somewhat differently. Instead of inspecting the +command source code, it looks for a Go source file belonging to the special +package "documentation”. The comment on the "package documentation” clause is +used as the command's documentation. For example, see the +<a href="/cmd/godoc/">godoc documentation</a> and its corresponding +<a href="/src/cmd/godoc/doc.go">doc.go</a> file. +</p> + +<p> +There are a few formatting rules that Godoc uses when converting comments to +HTML: +</p> + +<ul> +<li> +Subsequent lines of text are considered part of the same paragraph; you must +leave a blank line to separate paragraphs. +</li> +<li> +Pre-formatted text must be indented relative to the surrounding comment text +(see gob's <a href="/src/pkg/encoding/gob/doc.go">doc.go</a> for an example). +</li> +<li> +URLs will be converted to HTML links; no special markup is necessary. +</li> +</ul> + +<p> +Note that none of these rules requires you to do anything out of the ordinary. +</p> + +<p> +In fact, the best thing about godoc's minimal approach is how easy it is to use. +As a result, a lot of Go code, including all of the standard library, already +follows the conventions. +</p> + +<p> +Your own code can present good documentation just by having comments as +described above. Any Go packages installed inside <code>$GOROOT/src/pkg</code> +and any <code>GOPATH</code> work spaces will already be accessible via godoc's +command-line and HTTP interfaces, and you can specify additional paths for +indexing via the <code>-path</code> flag or just by running <code>"godoc ."</code> +in the source directory. See the <a href="/cmd/godoc/">godoc documentation</a> +for more details. +</p> diff --git a/doc/articles/gos_declaration_syntax.html b/doc/articles/gos_declaration_syntax.html new file mode 100644 index 000000000..455cced1d --- /dev/null +++ b/doc/articles/gos_declaration_syntax.html @@ -0,0 +1,348 @@ +<!--{ +"Title": "Go's Declaration Syntax" +}--> + +<p> +Newcomers to Go wonder why the declaration syntax is different from the +tradition established in the C family. In this post we'll compare the +two approaches and explain why Go's declarations look as they do. +</p> + +<p> +<b>C syntax</b> +</p> + +<p> +First, let's talk about C syntax. C took an unusual and clever approach +to declaration syntax. Instead of describing the types with special +syntax, one writes an expression involving the item being declared, and +states what type that expression will have. Thus +</p> + +<pre> +int x; +</pre> + +<p> +declares x to be an int: the expression 'x' will have type int. In +general, to figure out how to write the type of a new variable, write an +expression involving that variable that evaluates to a basic type, then +put the basic type on the left and the expression on the right. +</p> + +<p> +Thus, the declarations +</p> + +<pre> +int *p; +int a[3]; +</pre> + +<p> +state that p is a pointer to int because '*p' has type int, and that a +is an array of ints because a[3] (ignoring the particular index value, +which is punned to be the size of the array) has type int. +</p> + +<p> +What about functions? Originally, C's function declarations wrote the +types of the arguments outside the parens, like this: +</p> + +<pre> +int main(argc, argv) + int argc; + char *argv[]; +{ /* ... */ } +</pre> + +<p> +Again, we see that main is a function because the expression main(argc, +argv) returns an int. In modern notation we'd write +</p> + +<pre> +int main(int argc, char *argv[]) { /* ... */ } +</pre> + +<p> +but the basic structure is the same. +</p> + +<p> +This is a clever syntactic idea that works well for simple types but can +get confusing fast. The famous example is declaring a function pointer. +Follow the rules and you get this: +</p> + +<pre> +int (*fp)(int a, int b); +</pre> + +<p> +Here, fp is a pointer to a function because if you write the expression +(*fp)(a, b) you'll call a function that returns int. What if one of fp's +arguments is itself a function? +</p> + +<pre> +int (*fp)(int (*ff)(int x, int y), int b) +</pre> + +<p> +That's starting to get hard to read. +</p> + +<p> +Of course, we can leave out the name of the parameters when we declare a +function, so main can be declared +</p> + +<pre> +int main(int, char *[]) +</pre> + +<p> +Recall that argv is declared like this, +</p> + +<pre> +char *argv[] +</pre> + +<p> +so you drop the name from the <em>middle</em> of its declaration to construct +its type. It's not obvious, though, that you declare something of type +char *[] by putting its name in the middle. +</p> + +<p> +And look what happens to fp's declaration if you don't name the +parameters: +</p> + +<pre> +int (*fp)(int (*)(int, int), int) +</pre> + +<p> +Not only is it not obvious where to put the name inside +</p> + +<pre> +int (*)(int, int) +</pre> + +<p> +it's not exactly clear that it's a function pointer declaration at all. +And what if the return type is a function pointer? +</p> + +<pre> +int (*(*fp)(int (*)(int, int), int))(int, int) +</pre> + +<p> +It's hard even to see that this declaration is about fp. +</p> + +<p> +You can construct more elaborate examples but these should illustrate +some of the difficulties that C's declaration syntax can introduce. +</p> + +<p> +There's one more point that needs to be made, though. Because type and +declaration syntax are the same, it can be difficult to parse +expressions with types in the middle. This is why, for instance, C casts +always parenthesize the type, as in +</p> + +<pre> +(int)M_PI +</pre> + +<p> +<b>Go syntax</b> +</p> + +<p> +Languages outside the C family usually use a distinct type syntax in +declarations. Although it's a separate point, the name usually comes +first, often followed by a colon. Thus our examples above become +something like (in a fictional but illustrative language) +</p> + +<pre> +x: int +p: pointer to int +a: array[3] of int +</pre> + +<p> +These declarations are clear, if verbose - you just read them left to +right. Go takes its cue from here, but in the interests of brevity it +drops the colon and removes some of the keywords: +</p> + +<pre> +x int +p *int +a [3]int +</pre> + +<p> +There is no direct correspondence between the look of [3]int and how to +use a in an expression. (We'll come back to pointers in the next +section.) You gain clarity at the cost of a separate syntax. +</p> + +<p> +Now consider functions. Let's transcribe the declaration for main, even +though the main function in Go takes no arguments: +</p> + +<pre> +func main(argc int, argv *[]byte) int +</pre> + +<p> +Superficially that's not much different from C, but it reads well from +left to right: +</p> + +<p> +<em>function main takes an int and a pointer to a slice of bytes and returns an int.</em> +</p> + +<p> +Drop the parameter names and it's just as clear - they're always first +so there's no confusion. +</p> + +<pre> +func main(int, *[]byte) int +</pre> + +<p> +One value of this left-to-right style is how well it works as the types +become more complex. Here's a declaration of a function variable +(analogous to a function pointer in C): +</p> + +<pre> +f func(func(int,int) int, int) int +</pre> + +<p> +Or if f returns a function: +</p> + +<pre> +f func(func(int,int) int, int) func(int, int) int +</pre> + +<p> +It still reads clearly, from left to right, and it's always obvious +which name is being declared - the name comes first. +</p> + +<p> +The distinction between type and expression syntax makes it easy to +write and invoke closures in Go: +</p> + +<pre> +sum := func(a, b int) int { return a+b } (3, 4) +</pre> + +<p> +<b>Pointers</b> +</p> + +<p> +Pointers are the exception that proves the rule. Notice that in arrays +and slices, for instance, Go's type syntax puts the brackets on the left +of the type but the expression syntax puts them on the right of the +expression: +</p> + +<pre> +var a []int +x = a[1] +</pre> + +<p> +For familiarity, Go's pointers use the * notation from C, but we could +not bring ourselves to make a similar reversal for pointer types. Thus +pointers work like this +</p> + +<pre> +var p *int +x = *p +</pre> + +<p> +We couldn't say +</p> + +<pre> +var p *int +x = p* +</pre> + +<p> +because that postfix * would conflate with multiplication. We could have +used the Pascal ^, for example: +</p> + +<pre> +var p ^int +x = p^ +</pre> + +<p> +and perhaps we should have (and chosen another operator for xor), +because the prefix asterisk on both types and expressions complicates +things in a number of ways. For instance, although one can write +</p> + +<pre> +[]int("hi") +</pre> + +<p> +as a conversion, one must parenthesize the type if it starts with a *: +</p> + +<pre> +(*int)(nil) +</pre> + +<p> +Had we been willing to give up * as pointer syntax, those parentheses +would be unnecessary. +</p> + +<p> +So Go's pointer syntax is tied to the familiar C form, but those ties +mean that we cannot break completely from using parentheses to +disambiguate types and expressions in the grammar. +</p> + +<p> +Overall, though, we believe Go's type syntax is easier to understand +than C's, especially when things get complicated. +</p> + +<p> +<b>Notes</b> +</p> + +<p> +Go's declarations read left to right. It's been pointed out that C's +read in a spiral! See <a href="http://c-faq.com/decl/spiral.anderson.html"> +The "Clockwise/Spiral Rule"</a> by David Anderson. +</p> diff --git a/doc/articles/image-20.png b/doc/articles/image-20.png Binary files differnew file mode 100644 index 000000000..063e43064 --- /dev/null +++ b/doc/articles/image-20.png diff --git a/doc/articles/image-2a.png b/doc/articles/image-2a.png Binary files differnew file mode 100644 index 000000000..3f1c0afff --- /dev/null +++ b/doc/articles/image-2a.png diff --git a/doc/articles/image-2b.png b/doc/articles/image-2b.png Binary files differnew file mode 100644 index 000000000..32b247011 --- /dev/null +++ b/doc/articles/image-2b.png diff --git a/doc/articles/image-2c.png b/doc/articles/image-2c.png Binary files differnew file mode 100644 index 000000000..f9abce5b5 --- /dev/null +++ b/doc/articles/image-2c.png diff --git a/doc/articles/image-2d.png b/doc/articles/image-2d.png Binary files differnew file mode 100644 index 000000000..ed0a9f92c --- /dev/null +++ b/doc/articles/image-2d.png diff --git a/doc/articles/image-2e.png b/doc/articles/image-2e.png Binary files differnew file mode 100644 index 000000000..483b208e3 --- /dev/null +++ b/doc/articles/image-2e.png diff --git a/doc/articles/image-2f.png b/doc/articles/image-2f.png Binary files differnew file mode 100644 index 000000000..3dce02d5f --- /dev/null +++ b/doc/articles/image-2f.png diff --git a/doc/articles/image-package-01.png b/doc/articles/image-package-01.png Binary files differnew file mode 100644 index 000000000..aad9b1243 --- /dev/null +++ b/doc/articles/image-package-01.png diff --git a/doc/articles/image-package-02.png b/doc/articles/image-package-02.png Binary files differnew file mode 100644 index 000000000..3dd4692f3 --- /dev/null +++ b/doc/articles/image-package-02.png diff --git a/doc/articles/image-package-03.png b/doc/articles/image-package-03.png Binary files differnew file mode 100644 index 000000000..5bc0bf732 --- /dev/null +++ b/doc/articles/image-package-03.png diff --git a/doc/articles/image-package-04.png b/doc/articles/image-package-04.png Binary files differnew file mode 100644 index 000000000..393dc1207 --- /dev/null +++ b/doc/articles/image-package-04.png diff --git a/doc/articles/image-package-05.png b/doc/articles/image-package-05.png Binary files differnew file mode 100644 index 000000000..54c47b67b --- /dev/null +++ b/doc/articles/image-package-05.png diff --git a/doc/articles/image_draw.html b/doc/articles/image_draw.html new file mode 100644 index 000000000..ba735ad2b --- /dev/null +++ b/doc/articles/image_draw.html @@ -0,0 +1,222 @@ +<!--{ + "Title": "The Go image/draw package", + "Template": true +}--> + +<p> +<a href="/pkg/image/draw/">Package image/draw</a> defines +only one operation: drawing a source image onto a destination +image, through an optional mask image. This one operation is +surprisingly versatile and can perform a number of common image +manipulation tasks elegantly and efficiently. +</p> + +<p> +Composition is performed pixel by pixel in the style of the Plan 9 +graphics library and the X Render extension. The model is based on +the classic "Compositing Digital Images" paper by Porter and Duff, +with an additional mask parameter: <code>dst = (src IN mask) OP dst</code>. +For a fully opaque mask, this reduces to the original Porter-Duff +formula: <code>dst = src OP dst</code>. In Go, a nil mask image is equivalent +to an infinitely sized, fully opaque mask image. +</p> + +<p> +The Porter-Duff paper presented +<a href="http://www.w3.org/TR/SVGCompositing/examples/compop-porterduff-examples.png">12 different composition operators</a>, +but with an explicit mask, only 2 of these are needed in practice: +source-over-destination and source. In Go, these operators are +represented by the <code>Over</code> and <code>Src</code> constants. The <code>Over</code> operator +performs the natural layering of a source image over a destination +image: the change to the destination image is smaller where the +source (after masking) is more transparent (that is, has lower +alpha). The <code>Src</code> operator merely copies the source (after masking) +with no regard for the destination image's original content. For +fully opaque source and mask images, the two operators produce the +same output, but the <code>Src</code> operator is usually faster. +</p> + +<p><b>Geometric Alignment</b></p> + +<p> +Composition requires associating destination pixels with source and +mask pixels. Obviously, this requires destination, source and mask +images, and a composition operator, but it also requires specifying +what rectangle of each image to use. Not every drawing should write +to the entire destination: when updating an animating image, it is +more efficient to only draw the parts of the image that have +changed. Not every drawing should read from the entire source: when +using a sprite that combines many small images into one large one, +only a part of the image is needed. Not every drawing should read +from the entire mask: a mask image that collects a font's glyphs is +similar to a sprite. Thus, drawing also needs to know three +rectangles, one for each image. Since each rectangle has the same +width and height, it suffices to pass a destination rectangle `r` +and two points <code>sp</code> and <code>mp</code>: the source rectangle is equal to <code>r</code> +translated so that <code>r.Min</code> in the destination image aligns with +<code>sp</code> in the source image, and similarly for <code>mp</code>. The effective +rectangle is also clipped to each image's bounds in their +respective co-ordinate space. +</p> + +<p> +<img src="image-20.png"> +</p> + +<p> +The <a href="/pkg/image/draw/#DrawMask"><code>DrawMask</code></a> +function takes seven arguments, but an explicit mask and mask-point +are usually unnecessary, so the +<a href="/pkg/image/draw/#Draw"><code>Draw</code></a> function takes five: +</p> + +<pre> +// Draw calls DrawMask with a nil mask. +func Draw(dst Image, r image.Rectangle, src image.Image, sp image.Point, op Op) +func DrawMask(dst Image, r image.Rectangle, src image.Image, sp image.Point, + mask image.Image, mp image.Point, op Op) +</pre> + +<p> +The destination image must be mutable, so the image/draw package +defines a <a href="/pkg/image/draw/#Image"><code>draw.Image</code></a> +interface which has a <code>Set</code> method. +</p> + +{{code "../src/pkg/image/draw/draw.go" `/type Image/` `/}/`}} + +<p><b>Filling a Rectangle</b></p> + +<p> +To fill a rectangle with a solid color, use an <code>image.Uniform</code> +source. The <code>ColorImage</code> type re-interprets a <code>Color</code> as a +practically infinite-sized <code>Image</code> of that color. For those +familiar with the design of Plan 9's draw library, there is no need +for an explicit "repeat bit" in Go's slice-based image types; the +concept is subsumed by <code>Uniform</code>. +</p> + +{{code "/doc/progs/image_draw.go" `/ZERO/` `/STOP/`}} + +<p> +To initialize a new image to all-blue: +</p> + +{{code "/doc/progs/image_draw.go" `/BLUE/` `/STOP/`}} + +<p> +To reset an image to transparent (or black, if the destination +image's color model cannot represent transparency), use +<code>image.Transparent</code>, which is an <code>image.Uniform</code>: +</p> + +{{code "/doc/progs/image_draw.go" `/RESET/` `/STOP/`}} + +<p> +<img src="image-2a.png"> +</p> + + +<p><b>Copying an Image</b></p> + +<p> +To copy from a rectangle <code>sr</code> in the source image to a rectangle +starting at a point <code>dp</code> in the destination, convert the source +rectangle into the destination image's co-ordinate space: +</p> + +{{code "/doc/progs/image_draw.go" `/RECT/` `/STOP/`}} + +<p> +Alternatively: +</p> + +{{code "/doc/progs/image_draw.go" `/RECT2/` `/STOP/`}} + +<p> +To copy the entire source image, use <code>sr = src.Bounds()</code>. +</p> + +<p> +<img src="image-2b.png"> +</p> + +<p><b>Scrolling an Image</b></p> + +<p> +Scrolling an image is just copying an image to itself, with +different destination and source rectangles. Overlapping +destination and source images are perfectly valid, just as Go's +built-in copy function can handle overlapping destination and +source slices. To scroll an image m by 20 pixels: +</p> + +{{code "/doc/progs/image_draw.go" `/SCROLL/` `/STOP/`}} + +<p><img src="image-2c.png"></p> + +<p><b>Converting an Image to RGBA</b></p> + +<p> +The result of decoding an image format might not be an +<code>image.RGBA</code>: decoding a GIF results in an <code>image.Paletted</code>, +decoding a JPEG results in a <code>ycbcr.YCbCr</code>, and the result of +decoding a PNG depends on the image data. To convert any image to +an <code>image.RGBA</code>: +</p> + +{{code "/doc/progs/image_draw.go" `/CONV/` `/STOP/`}} + +<p> +<img src="image-2d.png"> +</p> + +<p><b>Drawing Through a Mask</b></p> + +<p> +To draw an image through a circular mask with center <code>p</code> and radius +<code>r</code>: +</p> + +{{code "/doc/progs/image_draw.go" `/CIRCLESTRUCT/` `/STOP/`}} +{{code "/doc/progs/image_draw.go" `/CIRCLE2/` `/STOP/`}} + +<p> +<img src="image-2e.png"> +</p> + +<p><b>Drawing Font Glyphs</b></p> + +<p> +To draw a font glyph in blue starting from a point <code>p</code>, draw with +an <code>image.ColorImage</code> source and an <code>image.Alpha mask</code>. For +simplicity, we aren't performing any sub-pixel positioning or +rendering, or correcting for a font's height above a baseline. +</p> + +{{code "/doc/progs/image_draw.go" `/GLYPH/` `/STOP/`}} + +<p> +<img src="image-2f.png"> +</p> + +<p><b>Performance</b></p> + +<p> +The image/draw package implementation demonstrates how to provide +an image manipulation function that is both general purpose, yet +efficient for common cases. The <code>DrawMask</code> function takes arguments +of interface types, but immediately makes type assertions that its +arguments are of specific struct types, corresponding to common +operations like drawing one <code>image.RGBA</code> image onto another, or +drawing an <code>image.Alpha</code> mask (such as a font glyph) onto an +<code>image.RGBA</code> image. If a type assertion succeeds, that type +information is used to run a specialized implementation of the +general algorithm. If the assertions fail, the fallback code path +uses the generic <code>At</code> and <code>Set</code> methods. The fast-paths are purely +a performance optimization; the resultant destination image is the +same either way. In practice, only a small number of special cases +are necessary to support typical applications. +</p> + + diff --git a/doc/articles/image_package.html b/doc/articles/image_package.html new file mode 100644 index 000000000..a9d2f3581 --- /dev/null +++ b/doc/articles/image_package.html @@ -0,0 +1,312 @@ +<!--{ + "Title": "The Go image package", + "Template": true +}--> + +<p> +The <a href="/pkg/image/">image</a> and +<a href="/pkg/image/color/">image/color</a> packages define a number of types: +<code>color.Color</code> and <code>color.Model</code> describe colors, +<code>image.Point</code> and <code>image.Rectangle</code> describe basic 2-D +geometry, and <code>image.Image</code> brings the two concepts together to +represent a rectangular grid of colors. A +<a href="/doc/articles/image_draw.html">separate article</a> covers image +composition with the <a href="/pkg/image/draw/">image/draw</a> package. +</p> + +<p> +<b>Colors and Color Models</b> +</p> + +<p> +<a href="/pkg/image/color/#Color">Color</a> is an interface that defines the minimal +method set of any type that can be considered a color: one that can be converted +to red, green, blue and alpha values. The conversion may be lossy, such as +converting from CMYK or YCbCr color spaces. +</p> + +{{code "/src/pkg/image/color/color.go" `/type Color interface/` `/^}/`}} + +<p> +There are three important subtleties about the return values. First, the red, +green and blue are alpha-premultiplied: a fully saturated red that is also 25% +transparent is represented by RGBA returning a 75% r. Second, the channels have +a 16-bit effective range: 100% red is represented by RGBA returning an r of +65535, not 255, so that converting from CMYK or YCbCr is not as lossy. Third, +the type returned is <code>uint32</code>, even though the maximum value is 65535, to +guarantee that multiplying two values together won't overflow. Such +multiplications occur when blending two colors according to an alpha mask from a +third color, in the style of +<a href="https://en.wikipedia.org/wiki/Alpha_compositing">Porter and Duff's</a> +classic algebra: +</p> + +<pre> +dstr, dstg, dstb, dsta := dst.RGBA() +srcr, srcg, srcb, srca := src.RGBA() +_, _, _, m := mask.RGBA() +const M = 1<<16 - 1 +// The resultant red value is a blend of dstr and srcr, and ranges in [0, M]. +// The calculation for green, blue and alpha is similar. +dstr = (dstr*(M-m) + srcr*m) / M +</pre> + +<p> +The last line of that code snippet would have been more complicated if we worked +with non-alpha-premultiplied colors, which is why <code>Color</code> uses +alpha-premultiplied values. +</p> + +<p> +The image/color package also defines a number of concrete types that implement +the <code>Color</code> interface. For example, +<a href="/pkg/image/color/#RGBA"><code>RGBA</code></a> is a struct that represents +the classic "8 bits per channel" color. +</p> + +{{code "/src/pkg/image/color/color.go" `/type RGBA struct/` `/^}/`}} + +<p> +Note that the <code>R</code> field of an <code>RGBA</code> is an 8-bit +alpha-premultiplied color in the range [0, 255]. <code>RGBA</code> satisfies the +<code>Color</code> interface by multiplying that value by 0x101 to generate a +16-bit alpha-premultiplied color in the range [0, 65535]. Similarly, the +<a href="/pkg/image/color/#NRGBA"><code>NRGBA</code></a> struct type represents +an 8-bit non-alpha-premultiplied color, as used by the PNG image format. When +manipulating an <code>NRGBA</code>'s fields directly, the values are +non-alpha-premultiplied, but when calling the <code>RGBA</code> method, the +return values are alpha-premultiplied. +</p> + +<p> +A <a href="/pkg/image/color/#Model"><code>Model</code></a> is simply +something that can convert <code>Color</code>s to other <code>Color</code>s, possibly lossily. For +example, the <code>GrayModel</code> can convert any <code>Color</code> to a +desaturated <a href="/pkg/image/color/#Gray"><code>Gray</code></a>. A +<code>Palette</code> can convert any <code>Color</code> to one from a +limited palette. +</p> + +{{code "/src/pkg/image/color/color.go" `/type Model interface/` `/^}/`}} + +{{code "/src/pkg/image/color/color.go" `/type Palette \[\]Color/`}} + +<p> +<b>Points and Rectangles</b> +</p> + +<p> +A <a href="/pkg/image/#Point"><code>Point</code></a> is an (x, y) co-ordinate +on the integer grid, with axes increasing right and down. It is neither a pixel +nor a grid square. A <code>Point</code> has no intrinsic width, height or +color, but the visualizations below use a small colored square. +</p> + +{{code "/src/pkg/image/geom.go" `/type Point struct/` `/^}/`}} + +<p> +<img src="image-package-01.png" width="400" height="300"> +</p> + +{{code "/doc/progs/image_package1.go" `/p := image.Point/`}} + +<p> +A <a href="/pkg/image/#Rectangle"><code>Rectangle</code></a> is an axis-aligned +rectangle on the integer grid, defined by its top-left and bottom-right +<code>Point</code>. A <code>Rectangle</code> also has no intrinsic color, but +the visualizations below outline rectangles with a thin colored line, and call +out their <code>Min</code> and <code>Max</code> <code>Point</code>s. +</p> + +{{code "/src/pkg/image/geom.go" `/type Rectangle struct/` `/^}/`}} + +<p> +For convenience, <code>image.Rect(x0, y0, x1, y1)</code> is equivalent to +<code>image.Rectangle{image.Point{x0, y0}, image.Point{x1, y1}}</code>, but is +much easier to type. +</p> + +<p> +A <code>Rectangle</code> is inclusive at the top-left and exclusive at the +bottom-right. For a <code>Point p</code> and a <code>Rectangle r</code>, +<code>p.In(r)</code> if and only if +<code>r.Min.X <= p.X && p.X < r.Max.X</code>, and similarly for <code>Y</code>. This is analagous to how +a slice <code>s[i0:i1]</code> is inclusive at the low end and exclusive at the +high end. (Unlike arrays and slices, a <code>Rectangle</code> often has a +non-zero origin.) +</p> + +<p> +<img src="image-package-02.png" width="400" height="300"> +</p> + +{{code "/doc/progs/image_package2.go" `/r := image.Rect/` `/fmt.Println/`}} + +<p> +Adding a <code>Point</code> to a <code>Rectangle</code> translates the +<code>Rectangle</code>. Points and Rectangles are not restricted to be in the +bottom-right quadrant. +</p> + +<p> +<img src="image-package-03.png" width="400" height="300"> +</p> + +{{code "/doc/progs/image_package3.go" `/r := image.Rect/` `/fmt.Println/`}} + +<p> +Intersecting two Rectangles yields another Rectangle, which may be empty. +</p> + +<p> +<img src="image-package-04.png" width="400" height="300"> +</p> + +{{code "/doc/progs/image_package4.go" `/r := image.Rect/` `/fmt.Printf/`}} + +<p> +Points and Rectangles are passed and returned by value. A function that takes a +<code>Rectangle</code> argument will be as efficient as a function that takes +two <code>Point</code> arguments, or four <code>int</code> arguments. +</p> + +<p> +<b>Images</b> +</p> + +<p> +An <a href="/pkg/image/#Image">Image</a> maps every grid square in a +<code>Rectangle</code> to a <code>Color</code> from a <code>Model</code>. +"The pixel at (x, y)" refers to the color of the grid square defined by the +points (x, y), (x+1, y), (x+1, y+1) and (x, y+1). +</p> + +{{code "/src/pkg/image/image.go" `/type Image interface/` `/^}/`}} + +<p> +A common mistake is assuming that an <code>Image</code>'s bounds start at (0, +0). For example, an animated GIF contains a sequence of Images, and each +<code>Image</code> after the first typically only holds pixel data for the area +that changed, and that area doesn't necessarily start at (0, 0). The correct +way to iterate over an <code>Image</code> m's pixels looks like: +</p> + +<pre> +b := m.Bounds() +for y := b.Min.Y; y < b.Max.Y; y++ { + for x := b.Min.X; y < b.Max.X; x++ { + doStuffWith(m.At(x, y)) + } +} +</pre> + +<p> +<code>Image</code> implementations do not have to be based on an in-memory +slice of pixel data. For example, a +<a href="/pkg/image/#Uniform"><code>Uniform</code></a> is an +<code>Image</code> of enormous bounds and uniform color, whose in-memory +representation is simply that color. +</p> + +{{code "/src/pkg/image/names.go" `/type Uniform struct/` `/^}/`}} + +<p> +Typically, though, programs will want an image based on a slice. Struct types +like <a href="/pkg/image/#RGBA"><code>RGBA</code></a> and +<a href="/pkg/image/#Gray"><code>Gray</code></a> (which other packages refer +to as <code>image.RGBA</code> and <code>image.Gray</code>) hold slices of pixel +data and implement the <code>Image</code> interface. +</p> + +{{code "/src/pkg/image/image.go" `/type RGBA struct/` `/^}/`}} + +<p> +These types also provide a <code>Set(x, y int, c color.Color)</code> method +that allows modifying the image one pixel at a time. +</p> + +{{code "/doc/progs/image_package5.go" `/m := image.New/` `/m.Set/`}} + +<p> +If you're reading or writing a lot of pixel data, it can be more efficient, but +more complicated, to access these struct type's <code>Pix</code> field directly. +</p> + +<p> +The slice-based <code>Image</code> implementations also provide a +<code>SubImage</code> method, which returns an <code>Image</code> backed by the +same array. Modifying the pixels of a sub-image will affect the pixels of the +original image, analagous to how modifying the contents of a sub-slice +<code>s[i0:i1]</code> will affect the contents of the original slice +<code>s</code>. +</p> + +<img src="image-package-05.png" width="400" height="300"> + +{{code "/doc/progs/image_package6.go" `/m0 := image.New/` `/fmt.Println\(m0.Stride/`}} + +<p> +For low-level code that works on an image's <code>Pix</code> field, be aware +that ranging over <code>Pix</code> can affect pixels outside an image's bounds. +In the example above, the pixels covered by <code>m1.Pix</code> are shaded in +blue. Higher-level code, such as the <code>At</code> and <code>Set</code> +methods or the <a href="/pkg/image/draw/">image/draw package</a>, will clip +their operations to the image's bounds. +</p> + +<p> +<b>Image Formats</b> +</p> + +<p> +The standard package library supports a number of common image formats, such as +GIF, JPEG and PNG. If you know the format of a source image file, you can +decode from an <a href="/pkg/io/#Reader"><code>io.Reader</code></a> directly. +</p> + +<pre> +import ( + "image/jpeg" + "image/png" + "io" +) + +// convertJPEGToPNG converts from JPEG to PNG. +func convertJPEGToPNG(w io.Writer, r io.Reader) error { + img, err := jpeg.Decode(r) + if err != nil { + return err + } + return png.Encode(w, img) +} +</pre> + +<p> +If you have image data of unknown format, the +<a href="/pkg/image/#Decode"><code>image.Decode</code></a> function can detect +the format. The set of recognized formats is constructed at run time and is not +limited to those in the standard package library. An image format package +typically registers its format in an init function, and the main package will +"underscore import" such a package solely for the side effect of format +registration. +</p> + +<pre> +import ( + "image" + "image/png" + "io" + + _ "code.google.com/p/vp8-go/webp" + _ "image/jpeg" +) + +// convertToPNG converts from any recognized format to PNG. +func convertToPNG(w io.Writer, r io.Reader) error { + img, _, err := image.Decode(r) + if err != nil { + return err + } + return png.Encode(w, img) +} +</pre> diff --git a/doc/articles/index.html b/doc/articles/index.html new file mode 100644 index 000000000..5f70734ec --- /dev/null +++ b/doc/articles/index.html @@ -0,0 +1,7 @@ +<!--{ + "Title": "/doc/articles/" +}--> + +<p> +See the <a href="/doc/#articles">Documents page</a> for a complete list of Go articles. +</p> diff --git a/doc/articles/json_and_go.html b/doc/articles/json_and_go.html new file mode 100644 index 000000000..af7776c0a --- /dev/null +++ b/doc/articles/json_and_go.html @@ -0,0 +1,356 @@ +<!--{ +"Title": "JSON and Go", +"Template": true +}--> + +<p> +JSON (JavaScript Object Notation) is a simple data interchange format. +Syntactically it resembles the objects and lists of JavaScript. It is most +commonly used for communication between web back-ends and JavaScript programs +running in the browser, but it is used in many other places, too. Its home page, +<a href="http://json.org">json.org</a>, provides a wonderfully clear and concise +definition of the standard. +</p> + +<p> +With the <a href="/pkg/encoding/json/">json package</a> it's a snap to read and +write JSON data from your Go programs. +</p> + +<p> +<b>Encoding</b> +</p> + +<p> +To encode JSON data we use the +<a href="/pkg/encoding/json/#Marshal"><code>Marshal</code></a> function. +</p> + +<pre> +func Marshal(v interface{}) ([]byte, error) +</pre> + +<p> +Given the Go data structure, <code>Message</code>, +</p> + +{{code "/doc/progs/json1.go" `/type Message/` `/STOP/`}} + +<p> +and an instance of <code>Message</code> +</p> + +{{code "/doc/progs/json1.go" `/m :=/`}} + +<p> +we can marshal a JSON-encoded version of m using <code>json.Marshal</code>: +</p> + +{{code "/doc/progs/json1.go" `/b, err :=/`}} + +<p> +If all is well, <code>err</code> will be <code>nil</code> and <code>b</code> +will be a <code>[]byte</code> containing this JSON data: +</p> + +<pre> +b == []byte(`{"Name":"Alice","Body":"Hello","Time":1294706395881547000}`) +</pre> + +<p> +Only data structures that can be represented as valid JSON will be encoded: +</p> + +<ul> +<li> +JSON objects only support strings as keys; to encode a Go map type it must be +of the form <code>map[string]T</code> (where <code>T</code> is any Go type +supported by the json package). +</li> +<li> +Channel, complex, and function types cannot be encoded. +</li> +<li> +Cyclic data structures are not supported; they will cause <code>Marshal</code> +to go into an infinite loop. +</li> +<li> +Pointers will be encoded as the values they point to (or 'null' if the pointer +is <code>nil</code>). +</li> +</ul> + +<p> +The json package only accesses the exported fields of struct types (those that +begin with an uppercase letter). Therefore only the the exported fields of a +struct will be present in the JSON output. +</p> + +<p> +<b>Decoding</b> +</p> + +<p> +To decode JSON data we use the +<a href="/pkg/encoding/json/#Unmarshal"><code>Unmarshal</code></a> function. +</p> + +<pre> +func Unmarshal(data []byte, v interface{}) error +</pre> + +<p> +We must first create a place where the decoded data will be stored +</p> + +{{code "/doc/progs/json1.go" `/var m Message/`}} + +<p> +and call <code>json.Unmarshal</code>, passing it a <code>[]byte</code> of JSON +data and a pointer to <code>m</code> +</p> + +{{code "/doc/progs/json1.go" `/err := json.Unmarshal/`}} + +<p> +If <code>b</code> contains valid JSON that fits in <code>m</code>, after the +call <code>err</code> will be <code>nil</code> and the data from <code>b</code> +will have been stored in the struct <code>m</code>, as if by an assignment +like: +</p> + +{{code "/doc/progs/json1.go" `/m = Message/` `/STOP/`}} + +<p> +How does <code>Unmarshal</code> identify the fields in which to store the +decoded data? For a given JSON key <code>"Foo"</code>, <code>Unmarshal</code> +will look through the destination struct's fields to find (in order of +preference): +</p> + +<ul> +<li> +An exported field with a tag of <code>"Foo"</code> (see the +<a href="/ref/spec#Struct_types">Go spec</a> for more on struct tags), +</li> +<li> +An exported field named <code>"Foo"</code>, or +</li> +<li> +An exported field named <code>"FOO"</code> or <code>"FoO"</code> or some other +case-insensitive match of <code>"Foo"</code>. +</li> +</ul> + +<p> +What happens when the structure of the JSON data doesn't exactly match the Go +type? +</p> + +{{code "/doc/progs/json1.go" `/"Food":"Pickle"/` `/STOP/`}} + +<p> +<code>Unmarshal</code> will decode only the fields that it can find in the +destination type. In this case, only the Name field of m will be populated, +and the Food field will be ignored. This behavior is particularly useful when +you wish to pick only a few specific fields out of a large JSON blob. It also +means that any unexported fields in the destination struct will be unaffected +by <code>Unmarshal</code>. +</p> + +<p> +But what if you don't know the structure of your JSON data beforehand? +</p> + +<p> +<b>Generic JSON with interface{}</b> +</p> + +<p> +The <code>interface{}</code> (empty interface) type describes an interface with +zero methods. Every Go type implements at least zero methods and therefore +satisfies the empty interface. +</p> + +<p> +The empty interface serves as a general container type: +</p> + +{{code "/doc/progs/json2.go" `/var i interface{}/` `/STOP/`}} + +<p> +A type assertion accesses the underlying concrete type: +</p> + +{{code "/doc/progs/json2.go" `/r := i/` `/STOP/`}} + +<p> +Or, if the underlying type is unknown, a type switch determines the type: +</p> + +{{code "/doc/progs/json2.go" `/switch v/` `/STOP/`}} + + +The json package uses <code>map[string]interface{}</code> and +<code>[]interface{}</code> values to store arbitrary JSON objects and arrays; +it will happily unmarshal any valid JSON blob into a plain +<code>interface{}</code> value. The default concrete Go types are: + +<ul> +<li> +<code>bool</code> for JSON booleans, +</li> +<li> +<code>float64</code> for JSON numbers, +</li> +<li> +<code>string</code> for JSON strings, and +</li> +<li> +<code>nil</code> for JSON null. +</li> +</ul> + +<p> +<b>Decoding arbitrary data</b> +</p> + +<p> +Consider this JSON data, stored in the variable <code>b</code>: +</p> + +{{code "/doc/progs/json3.go" `/b :=/`}} + +<p> +Without knowing this data's structure, we can decode it into an +<code>interface{}</code> value with <code>Unmarshal</code>: +</p> + +{{code "/doc/progs/json3.go" `/var f interface/` `/STOP/`}} + +<p> +At this point the Go value in <code>f</code> would be a map whose keys are +strings and whose values are themselves stored as empty interface values: +</p> + +{{code "/doc/progs/json3.go" `/f = map/` `/STOP/`}} + +<p> +To access this data we can use a type assertion to access <code>f</code>'s +underlying <code>map[string]interface{}</code>: +</p> + +{{code "/doc/progs/json3.go" `/m := f/`}} + +<p> +We can then iterate through the map with a range statement and use a type switch +to access its values as their concrete types: +</p> + +{{code "/doc/progs/json3.go" `/for k, v/` `/STOP/`}} + +<p> +In this way you can work with unknown JSON data while still enjoying the +benefits of type safety. +</p> + +<p> +<b>Reference Types</b> +</p> + +<p> +Let's define a Go type to contain the data from the previous example: +</p> + +{{code "/doc/progs/json4.go" `/type FamilyMember/` `/STOP/`}} + +{{code "/doc/progs/json4.go" `/var m FamilyMember/` `/STOP/`}} + +<p> +Unmarshaling that data into a <code>FamilyMember</code> value works as +expected, but if we look closely we can see a remarkable thing has happened. +With the var statement we allocated a <code>FamilyMember</code> struct, and +then provided a pointer to that value to <code>Unmarshal</code>, but at that +time the <code>Parents</code> field was a <code>nil</code> slice value. To +populate the <code>Parents</code> field, <code>Unmarshal</code> allocated a new +slice behind the scenes. This is typical of how <code>Unmarshal</code> works +with the supported reference types (pointers, slices, and maps). +</p> + +<p> +Consider unmarshaling into this data structure: +</p> + +<pre> +type Foo struct { + Bar *Bar +} +</pre> + +<p> +If there were a <code>Bar</code> field in the JSON object, +<code>Unmarshal</code> would allocate a new <code>Bar</code> and populate it. +If not, <code>Bar</code> would be left as a <code>nil</code> pointer. +</p> + +<p> +From this a useful pattern arises: if you have an application that receives a +few distinct message types, you might define "receiver" structure like +</p> + +<pre> +type IncomingMessage struct { + Cmd *Command + Msg *Message +} +</pre> + +<p> +and the sending party can populate the <code>Cmd</code> field and/or the +<code>Msg</code> field of the top-level JSON object, depending on the type of +message they want to communicate. <code>Unmarshal</code>, when decoding the +JSON into an <code>IncomingMessage</code> struct, will only allocate the data +structures present in the JSON data. To know which messages to process, the +programmer need simply test that either <code>Cmd</code> or <code>Msg</code> is +not <code>nil</code>. +</p> + +<p> +<b>Streaming Encoders and Decoders</b> +</p> + +<p> +The json package provides <code>Decoder</code> and <code>Encoder</code> types +to support the common operation of reading and writing streams of JSON data. +The <code>NewDecoder</code> and <code>NewEncoder</code> functions wrap the +<a href="/pkg/io/#Reader"><code>io.Reader</code></a> and +<a href="/pkg/io/#Writer"><code>io.Writer</code></a> interface types. +</p> + +<pre> +func NewDecoder(r io.Reader) *Decoder +func NewEncoder(w io.Writer) *Encoder +</pre> + +<p> +Here's an example program that reads a series of JSON objects from standard +input, removes all but the <code>Name</code> field from each object, and then +writes the objects to standard output: +</p> + +{{code "/doc/progs/json5.go" `/package main/` `$`}} + +<p> +Due to the ubiquity of Readers and Writers, these <code>Encoder</code> and +<code>Decoder</code> types can be used in a broad range of scenarios, such as +reading and writing to HTTP connections, WebSockets, or files. +</p> + +<p> +<b>References</b> +</p> + +<p> +For more information see the <a href="/pkg/encoding/json/">json package documentation</a>. For an example usage of +json see the source files of the <a href="/pkg/net/rpc/jsonrpc/">jsonrpc package</a>. +</p> diff --git a/doc/articles/json_rpc_tale_of_interfaces.html b/doc/articles/json_rpc_tale_of_interfaces.html new file mode 100644 index 000000000..a545f55f6 --- /dev/null +++ b/doc/articles/json_rpc_tale_of_interfaces.html @@ -0,0 +1,78 @@ +<!--{ +"Title": "JSON-RPC: a tale of interfaces" +}--> + +<p> +Here we present an example where Go's +<a href="/doc/effective_go.html#interfaces_and_types">interfaces</a> made it +easy to refactor some existing code to make it more flexible and extensible. +Originally, the standard library's <a href="/pkg/net/rpc/">RPC package</a> used +a custom wire format called <a href="/pkg/encoding/gob/">gob</a>. For a +particular application, we wanted to use <a href="/pkg/encoding/json/">JSON</a> +as an alternate wire format. +</p> + +<p> +We first defined a pair of interfaces to describe the functionality of the +existing wire format, one for the client, and one for the server (depicted +below). +</p> + +<pre> +type ServerCodec interface { + ReadRequestHeader(*Request) error + ReadRequestBody(interface{}) error + WriteResponse(*Response, interface{}) error + Close() error +} +</pre> + +<p> +On the server side, we then changed two internal function signatures to accept +the <code>ServerCodec</code> interface instead of our existing +<code>gob.Encoder</code>. Here's one of them: +</p> + +<pre> +func sendResponse(sending *sync.Mutex, req *Request, + reply interface{}, enc *gob.Encoder, errmsg string) +</pre> + +<p> +became +</p> + +<pre> +func sendResponse(sending *sync.Mutex, req *Request, + reply interface{}, enc ServerCodec, errmsg string) +</pre> + +<p> +We then wrote a trivial <code>gobServerCodec</code> wrapper to reproduce the +original functionality. From there it is simple to build a +<code>jsonServerCodec</code>. +</p> + +<p> +After some similar changes to the client side, this was the full extent of the +work we needed to do on the RPC package. This whole exercise took about 20 +minutes! After tidying up and testing the new code, the +<a href="http://code.google.com/p/go/source/diff?spec=svn9daf796ebf1cae97b2fcf760a4ab682f1f063f29&r=9daf796ebf1cae97b2fcf760a4ab682f1f063f29&format=side&path=/src/pkg/rpc/server.go">final changeset</a> +was submitted. +</p> + +<p> +In an inheritance-oriented language like Java or C++, the obvious path would be +to generalize the RPC class, and create JsonRPC and GobRPC subclasses. However, +this approach becomes tricky if you want to make a further generalization +orthogonal to that hierarchy. (For example, if you were to implement an +alternate RPC standard). In our Go package, we took a route that is both +conceptually simpler and requires less code be written or changed. +</p> + +<p> +A vital quality for any codebase is maintainability. As needs change, it is +essential to adapt your code easily and cleanly, lest it become unwieldy to work +with. We believe Go's lightweight, composition-oriented type system provides a +means of structuring code that scales. +</p> diff --git a/doc/articles/laws_of_reflection.html b/doc/articles/laws_of_reflection.html new file mode 100644 index 000000000..826a054f2 --- /dev/null +++ b/doc/articles/laws_of_reflection.html @@ -0,0 +1,649 @@ +<!--{ + "Title": "The Laws of Reflection", + "Template": true +}--> + +<p> +Reflection in computing is the +ability of a program to examine its own structure, particularly +through types; it's a form of metaprogramming. It's also a great +source of confusion. +</p> + +<p> +In this article we attempt to clarify things by explaining how +reflection works in Go. Each language's reflection model is +different (and many languages don't support it at all), but +this article is about Go, so for the rest of this article the word +"reflection" should be taken to mean "reflection in Go". +</p> + +<p><b>Types and interfaces</b></p> + +<p> +Because reflection builds on the type system, let's start with a +refresher about types in Go. +</p> + +<p> +Go is statically typed. Every variable has a static type, that is, +exactly one type known and fixed at compile time: <code>int</code>, +<code>float32</code>, <code>*MyType</code>, <code>[]byte</code>, +and so on. If we declare +</p> + +{{code "/doc/progs/interface.go" `/type MyInt/` `/STOP/`}} + +<p> +then <code>i</code> has type <code>int</code> and <code>j</code> +has type <code>MyInt</code>. The variables <code>i</code> and +<code>j</code> have distinct static types and, although they have +the same underlying type, they cannot be assigned to one another +without a conversion. +</p> + +<p> +One important category of type is interface types, which represent +fixed sets of methods. An interface variable can store any concrete +(non-interface) value as long as that value implements the +interface's methods. A well-known pair of examples is +<code>io.Reader</code> and <code>io.Writer</code>, the types +<code>Reader</code> and <code>Writer</code> from the +<a href="/pkg/io/">io package</a>: +</p> + +{{code "/doc/progs/interface.go" `/// Reader/` `/STOP/`}} + +<p> +Any type that implements a <code>Read</code> (or +<code>Write</code>) method with this signature is said to implement +<code>io.Reader</code> (or <code>io.Writer</code>). For the +purposes of this discussion, that means that a variable of type +<code>io.Reader</code> can hold any value whose type has a +<code>Read</code> method: +</p> + +{{code "/doc/progs/interface.go" `/func readers/` `/STOP/`}} + +<p> +It's important to be clear that whatever concrete value +<code>r</code> may hold, <code>r</code>'s type is always +<code>io.Reader</code>: Go is statically typed and the static type +of <code>r</code> is <code>io.Reader</code>.</p> + +<p> +An extremely important example of an interface type is the empty +interface: +</p> + +<pre> +interface{} +</pre> + +<p> +It represents the empty set of methods and is satisfied by any +value at all, since any value has zero or more methods. +</p> + +<p> +Some people say that Go's interfaces are dynamically typed, but +that is misleading. They are statically typed: a variable of +interface type always has the same static type, and even though at +run time the value stored in the interface variable may change +type, that value will always satisfy the interface. +</p> + +<p> +We need to be precise about all this because reflection and +interfaces are closely related. +</p> + +<p><b>The representation of an interface</b></p> + +<p> +Russ Cox has written a +<a href="http://research.swtch.com/2009/12/go-data-structures-interfaces.html">detailed blog post</a> +about the representation of interface values in Go. It's not necessary to +repeat the full story here, but a simplified summary is in order. +</p> + +<p> +A variable of interface type stores a pair: the concrete value +assigned to the variable, and that value's type descriptor. +To be more precise, the value is the underlying concrete data item +that implements the interface and the type describes the full type +of that item. For instance, after +</p> + +{{code "/doc/progs/interface.go" `/func typeAssertions/` `/STOP/`}} + +<p> +<code>r</code> contains, schematically, the (value, type) pair, +(<code>tty</code>, <code>*os.File</code>). Notice that the type +<code>*os.File</code> implements methods other than +<code>Read</code>; even though the interface value provides access +only to the <code>Read</code> method, the value inside carries all +the type information about that value. That's why we can do things +like this: +</p> + +{{code "/doc/progs/interface.go" `/var w io.Writer/` `/STOP/`}} + +<p> +The expression in this assignment is a type assertion; what it +asserts is that the item inside <code>r</code> also implements +<code>io.Writer</code>, and so we can assign it to <code>w</code>. +After the assignment, <code>w</code> will contain the pair +(<code>tty</code>, <code>*os.File</code>). That's the same pair as +was held in <code>r</code>. The static type of the interface +determines what methods may be invoked with an interface variable, +even though the concrete value inside may have a larger set of +methods. +</p> + +<p> +Continuing, we can do this: +</p> + +{{code "/doc/progs/interface.go" `/var empty interface{}/` `/STOP/`}} + +<p> +and our empty interface value <code>e</code> will again contain +that same pair, (<code>tty</code>, <code>*os.File</code>). That's +handy: an empty interface can hold any value and contains all the +information we could ever need about that value. +</p> + +<p> +(We don't need a type assertion here because it's known statically +that <code>w</code> satisfies the empty interface. In the example +where we moved a value from a <code>Reader</code> to a +<code>Writer</code>, we needed to be explicit and use a type +assertion because <code>Writer</code>'s methods are not a +subset of <code>Reader</code>'s.) +</p> + +<p> +One important detail is that the pair inside an interface always +has the form (value, concrete type) and cannot have the form +(value, interface type). Interfaces do not hold interface +values. +</p> + +<p> +Now we're ready to reflect. +</p> + +<p><b>The first law of reflection</b></p> + +<p><b>1. Reflection goes from interface value to reflection object.</b></p> + +<p> +At the basic level, reflection is just a mechanism to examine the +type and value pair stored inside an interface variable. To get +started, there are two types we need to know about in +<a href="/pkg/reflect/">package reflect</a>: +<a href="/pkg/reflect/#Type">Type</a> and +<a href="/pkg/reflect/#Value">Value</a>. Those two types +give access to the contents of an interface variable, and two +simple functions, called <code>reflect.TypeOf</code> and +<code>reflect.ValueOf</code>, retrieve <code>reflect.Type</code> +and <code>reflect.Value</code> pieces out of an interface value. +(Also, from the <code>reflect.Value</code> it's easy to get +to the <code>reflect.Type</code>, but let's keep the +<code>Value</code> and <code>Type</code> concepts separate for +now.) +</p> + +<p> +Let's start with <code>TypeOf</code>: +</p> + +{{code "/doc/progs/interface2.go" `/package main/` `/STOP main/`}} + +<p> +This program prints +</p> + +<pre> +type: float64 +</pre> + +<p> +You might be wondering where the interface is here, since the program looks +like it's passing the <code>float64</code> variable <code>x</code>, not an +interface value, to <code>reflect.TypeOf</code>. But it's there; as +<a href="/pkg/reflect/#Type.TypeOf">godoc reports</a>, the signature of +<code>reflect.TypeOf</code> includes an empty interface: +</p> + +<pre> +// TypeOf returns the reflection Type of the value in the interface{}. +func TypeOf(i interface{}) Type +</pre> + +<p> +When we call <code>reflect.TypeOf(x)</code>, <code>x</code> is +first stored in an empty interface, which is then passed as the +argument; <code>reflect.TypeOf</code> unpacks that empty interface +to recover the type information. +</p> + +<p> +The <code>reflect.ValueOf</code> function, of course, recovers the +value (from here on we'll elide the boilerplate and focus just on +the executable code): +</p> + +{{code "/doc/progs/interface2.go" `/START f9/` `/STOP/`}} + +<p> +prints +</p> + +<pre> +value: <float64 Value> +</pre> + +<p> +Both <code>reflect.Type</code> and <code>reflect.Value</code> have +lots of methods to let us examine and manipulate them. One +important example is that <code>Value</code> has a +<code>Type</code> method that returns the <code>Type</code> of a +<code>reflect.Value</code>. Another is that both <code>Type</code> +and <code>Value</code> have a <code>Kind</code> method that returns +a constant indicating what sort of item is stored: +<code>Uint</code>, <code>Float64</code>, <code>Slice</code>, and so +on. Also methods on <code>Value</code> with names like +<code>Int</code> and <code>Float</code> let us grab values (as +<code>int64</code> and <code>float64</code>) stored inside: +</p> + +{{code "/doc/progs/interface2.go" `/START f1/` `/STOP/`}} + +<p> +prints +</p> + +<pre> +type: float64 +kind is float64: true +value: 3.4 +</pre> + +<p> +There are also methods like <code>SetInt</code> and +<code>SetFloat</code> but to use them we need to understand +settability, the subject of the third law of reflection, discussed +below. +</p> + +<p> +The reflection library has a couple of properties worth singling +out. First, to keep the API simple, the "getter" and "setter" +methods of <code>Value</code> operate on the largest type that can +hold the value: <code>int64</code> for all the signed integers, for +instance. That is, the <code>Int</code> method of +<code>Value</code> returns an <code>int64</code> and the +<code>SetInt</code> value takes an <code>int64</code>; it may be +necessary to convert to the actual type involved: +</p> + +{{code "/doc/progs/interface2.go" `/START f2/` `/STOP/`}} + +<p> +The second property is that the <code>Kind</code> of a reflection +object describes the underlying type, not the static type. If a +reflection object contains a value of a user-defined integer type, +as in +</p> + +{{code "/doc/progs/interface2.go" `/START f3/` `/STOP/`}} + +<p> +the <code>Kind</code> of <code>v</code> is still +<code>reflect.Int</code>, even though the static type of +<code>x</code> is <code>MyInt</code>, not <code>int</code>. In +other words, the <code>Kind</code> cannot discriminate an int from +a <code>MyInt</code> even though the <code>Type</code> can. +</p> + +<p><b>The second law of reflection</b></p> + +<p><b>2. Reflection goes from reflection object to interface +value.</b></p> + +<p> +Like physical reflection, reflection in Go generates its own +inverse. +</p> + +<p> +Given a <code>reflect.Value</code> we can recover an interface +value using the <code>Interface</code> method; in effect the method +packs the type and value information back into an interface +representation and returns the result: +</p> + +<pre> +// Interface returns v's value as an interface{}. +func (v Value) Interface() interface{} +</pre> + +<p> +As a consequence we can say +</p> + +{{code "/doc/progs/interface2.go" `/START f3b/` `/STOP/`}} + +<p> +to print the <code>float64</code> value represented by the +reflection object <code>v</code>. +</p> + +<p> +We can do even better, though. The arguments to +<code>fmt.Println</code>, <code>fmt.Printf</code> and so on are all +passed as empty interface values, which are then unpacked by the +<code>fmt</code> package internally just as we have been doing in +the previous examples. Therefore all it takes to print the contents +of a <code>reflect.Value</code> correctly is to pass the result of +the <code>Interface</code> method to the formatted print +routine: +</p> + +{{code "/doc/progs/interface2.go" `/START f3c/` `/STOP/`}} + +<p> +(Why not <code>fmt.Println(v)</code>? Because <code>v</code> is a +<code>reflect.Value</code>; we want the concrete value it holds.) +Since our value is a <code>float64</code>, we can even use a +floating-point format if we want: +</p> + +{{code "/doc/progs/interface2.go" `/START f3d/` `/STOP/`}} + +<p> +and get in this case +</p> + +<pre> +3.4e+00 +</pre> + +<p> +Again, there's no need to type-assert the result of +<code>v.Interface()</code> to <code>float64</code>; the empty +interface value has the concrete value's type information inside +and <code>Printf</code> will recover it. +</p> + +<p> +In short, the <code>Interface</code> method is the inverse of the +<code>ValueOf</code> function, except that its result is always of +static type <code>interface{}</code>. +</p> + +<p> +Reiterating: Reflection goes from interface values to reflection +objects and back again. +</p> + +<p><b>The third law of reflection</b></p> + +<p><b>3. To modify a reflection object, the value must be settable.</b></p> + +<p> +The third law is the most subtle and confusing, but it's easy +enough to understand if we start from first principles. +</p> + +<p> +Here is some code that does not work, but is worth studying. +</p> + +{{code "/doc/progs/interface2.go" `/START f4/` `/STOP/`}} + +<p> +If you run this code, it will panic with the cryptic message +</p> + +<pre> +panic: reflect.Value.SetFloat using unaddressable value +</pre> + +<p> +The problem is not that the value <code>7.1</code> is not +addressable; it's that <code>v</code> is not settable. Settability +is a property of a reflection <code>Value</code>, and not all +reflection <code>Values</code> have it. +</p> + +<p> +The <code>CanSet</code> method of <code>Value</code> reports the +settability of a <code>Value</code>; in our case, +</p> + +{{code "/doc/progs/interface2.go" `/START f5/` `/STOP/`}} + +<p> +prints +</p> + +<pre> +settability of v: false +</pre> + +<p> +It is an error to call a <code>Set</code> method on an non-settable +<code>Value</code>. But what is settability? +</p> + +<p> +Settability is a bit like addressability, but stricter. It's the +property that a reflection object can modify the actual storage +that was used to create the reflection object. Settability is +determined by whether the reflection object holds the original +item. When we say +</p> + +{{code "/doc/progs/interface2.go" `/START f6/` `/STOP/`}} + +<p> +we pass a <em>copy</em> of <code>x</code> to +<code>reflect.ValueOf</code>, so the interface value created as the +argument to <code>reflect.ValueOf</code> is a <em>copy</em> of +<code>x</code>, not <code>x</code> itself. Thus, if the +statement +</p> + +{{code "/doc/progs/interface2.go" `/START f6b/` `/STOP/`}} + +<p> +were allowed to succeed, it would not update <code>x</code>, even +though <code>v</code> looks like it was created from +<code>x</code>. Instead, it would update the copy of <code>x</code> +stored inside the reflection value and <code>x</code> itself would +be unaffected. That would be confusing and useless, so it is +illegal, and settability is the property used to avoid this +issue. +</p> + +<p> +If this seems bizarre, it's not. It's actually a familiar situation +in unusual garb. Think of passing <code>x</code> to a +function: +</p> + +<pre> +f(x) +</pre> + +<p> +We would not expect <code>f</code> to be able to modify +<code>x</code> because we passed a copy of <code>x</code>'s value, +not <code>x</code> itself. If we want <code>f</code> to modify +<code>x</code> directly we must pass our function the address of +<code>x</code> (that is, a pointer to <code>x</code>):</p> + +<p> +<code>f(&x)</code> +</p> + +<p> +This is straightforward and familiar, and reflection works the same +way. If we want to modify <code>x</code> by reflection, we must +give the reflection library a pointer to the value we want to +modify. +</p> + +<p> +Let's do that. First we initialize <code>x</code> as usual +and then create a reflection value that points to it, called +<code>p</code>. +</p> + +{{code "/doc/progs/interface2.go" `/START f7/` `/STOP/`}} + +<p> +The output so far is +</p> + +<pre> +type of p: *float64 +settability of p: false +</pre> + +<p> +The reflection object <code>p</code> isn't settable, but it's not +<code>p</code> we want to set, it's (in effect) <code>*p</code>. To +get to what <code>p</code> points to, we call the <code>Elem</code> +method of <code>Value</code>, which indirects through the pointer, +and save the result in a reflection <code>Value</code> called +<code>v</code>: +</p> + +{{code "/doc/progs/interface2.go" `/START f7b/` `/STOP/`}} + +<p> +Now <code>v</code> is a settable reflection object, as the output +demonstrates, +</p> + +<pre> +settability of v: true +</pre> + +<p> +and since it represents <code>x</code>, we are finally able to use +<code>v.SetFloat</code> to modify the value of +<code>x</code>: +</p> + +{{code "/doc/progs/interface2.go" `/START f7c/` `/STOP/`}} + +<p> +The output, as expected, is +</p> + +<pre> +7.1 +7.1 +</pre> + +<p> +Reflection can be hard to understand but it's doing exactly what +the language does, albeit through reflection <code>Types</code> and +<code>Values</code> that can disguise what's going on. Just keep in +mind that reflection Values need the address of something in order +to modify what they represent. +</p> + +<p><b>Structs</b></p> + +<p> +In our previous example <code>v</code> wasn't a pointer itself, it +was just derived from one. A common way for this situation to arise +is when using reflection to modify the fields of a structure. As +long as we have the address of the structure, we can modify its +fields. +</p> + +<p> +Here's a simple example that analyzes a struct value, <code>t</code>. We create +the reflection object with the address of the struct because we'll want to +modify it later. Then we set <code>typeOfT</code> to its type and iterate over +the fields using straightforward method calls +(see <a href="/pkg/reflect/">package reflect</a> for details). +Note that we extract the names of the fields from the struct type, but the +fields themselves are regular <code>reflect.Value</code> objects. +</p> + +{{code "/doc/progs/interface2.go" `/START f8/` `/STOP/`}} + +<p> +The output of this program is +</p> + +<pre> +0: A int = 23 +1: B string = skidoo +</pre> + +<p> +There's one more point about settability introduced in +passing here: the field names of <code>T</code> are upper case +(exported) because only exported fields of a struct are +settable. +</p> + +<p> +Because <code>s</code> contains a settable reflection object, we +can modify the fields of the structure. +</p> + +{{code "/doc/progs/interface2.go" `/START f8b/` `/STOP/`}} + +<p> +And here's the result: +</p> + +<pre> +t is now {77 Sunset Strip} +</pre> + +<p> +If we modified the program so that <code>s</code> was created from +<code>t</code>, not <code>&t</code>, the calls to +<code>SetInt</code> and <code>SetString</code> would fail as the +fields of <code>t</code> would not be settable. +</p> + +<p><b>Conclusion</b></p> + +<p> +Here again are the laws of reflection: +</p> + +<ol> +<li>Reflection goes from interface value to reflection +object.</li> +<li>Reflection goes from reflection object to interface +value.</li> +<li>To modify a reflection object, the value must be settable.</li> +</ol> + +<p> +Once you understand these laws reflection in Go becomes much easier +to use, although it remains subtle. It's a powerful tool that +should be used with care and avoided unless strictly +necessary. +</p> + +<p> +There's plenty more to reflection that we haven't covered — +sending and receiving on channels, allocating memory, using slices +and maps, calling methods and functions — but this post is +long enough. We'll cover some of those topics in a later +article. +</p> diff --git a/doc/articles/slice-1.png b/doc/articles/slice-1.png Binary files differnew file mode 100644 index 000000000..ba465cf71 --- /dev/null +++ b/doc/articles/slice-1.png diff --git a/doc/articles/slice-2.png b/doc/articles/slice-2.png Binary files differnew file mode 100644 index 000000000..a57581e8c --- /dev/null +++ b/doc/articles/slice-2.png diff --git a/doc/articles/slice-3.png b/doc/articles/slice-3.png Binary files differnew file mode 100644 index 000000000..64ece5e87 --- /dev/null +++ b/doc/articles/slice-3.png diff --git a/doc/articles/slice-array.png b/doc/articles/slice-array.png Binary files differnew file mode 100644 index 000000000..a533702cf --- /dev/null +++ b/doc/articles/slice-array.png diff --git a/doc/articles/slice-struct.png b/doc/articles/slice-struct.png Binary files differnew file mode 100644 index 000000000..f9141fc59 --- /dev/null +++ b/doc/articles/slice-struct.png diff --git a/doc/articles/slices_usage_and_internals.html b/doc/articles/slices_usage_and_internals.html new file mode 100644 index 000000000..810b0a41f --- /dev/null +++ b/doc/articles/slices_usage_and_internals.html @@ -0,0 +1,438 @@ +<!--{ + "Title": "Slices: usage and internals", + "Template": true +}--> + +<p> +Go's slice type provides a convenient and efficient means of working with +sequences of typed data. Slices are analogous to arrays in other languages, but +have some unusual properties. This article will look at what slices are and how +they are used. +</p> + +<p> +<b>Arrays</b> +</p> + +<p> +The slice type is an abstraction built on top of Go's array type, and so to +understand slices we must first understand arrays. +</p> + +<p> +An array type definition specifies a length and an element type. For example, +the type <code>[4]int</code> represents an array of four integers. An array's +size is fixed; its length is part of its type (<code>[4]int</code> and +<code>[5]int</code> are distinct, incompatible types). Arrays can be indexed in +the usual way, so the expression <code>s[n]</code> accesses the <i>n</i>th +element: +</p> + +<pre> +var a [4]int +a[0] = 1 +i := a[0] +// i == 1 +</pre> + +<p> +Arrays do not need to be initialized explicitly; the zero value of an array is +a ready-to-use array whose elements are themselves zeroed: +</p> + +<pre> +// a[2] == 0, the zero value of the int type +</pre> + +<p> +The in-memory representation of <code>[4]int</code> is just four integer values laid out sequentially: +</p> + +<p> +<img src="slice-array.png"> +</p> + +<p> +Go's arrays are values. An array variable denotes the entire array; it is not a +pointer to the first array element (as would be the case in C). This means +that when you assign or pass around an array value you will make a copy of its +contents. (To avoid the copy you could pass a <i>pointer</i> to the array, but +then that's a pointer to an array, not an array.) One way to think about arrays +is as a sort of struct but with indexed rather than named fields: a fixed-size +composite value. +</p> + +<p> +An array literal can be specified like so: +</p> + +<pre> +b := [2]string{"Penn", "Teller"} +</pre> + +<p> +Or, you can have the compiler count the array elements for you: +</p> + +<pre> +b := [...]string{"Penn", "Teller"} +</pre> + +<p> +In both cases, the type of <code>b</code> is <code>[2]string</code>. +</p> + +<p> +<b>Slices</b> +</p> + +<p> +Arrays have their place, but they're a bit inflexible, so you don't see them +too often in Go code. Slices, though, are everywhere. They build on arrays to +provide great power and convenience. +</p> + +<p> +The type specification for a slice is <code>[]T</code>, where <code>T</code> is +the type of the elements of the slice. Unlike an array type, a slice type has +no specified length. +</p> + +<p> +A slice literal is declared just like an array literal, except you leave out +the element count: +</p> + +<pre> +letters := []string{"a", "b", "c", "d"} +</pre> + +<p> +A slice can be created with the built-in function called <code>make</code>, +which has the signature, +</p> + +<pre> +func make([]T, len, cap) []T +</pre> + +<p> +where T stands for the element type of the slice to be created. The +<code>make</code> function takes a type, a length, and an optional capacity. +When called, <code>make</code> allocates an array and returns a slice that +refers to that array. +</p> + +<pre> +var s []byte +s = make([]byte, 5, 5) +// s == []byte{0, 0, 0, 0, 0} +</pre> + +<p> +When the capacity argument is omitted, it defaults to the specified length. +Here's a more succinct version of the same code: +</p> + +<pre> +s := make([]byte, 5) +</pre> + +<p> +The length and capacity of a slice can be inspected using the built-in +<code>len</code> and <code>cap</code> functions. +</p> + +<pre> +len(s) == 5 +cap(s) == 5 +</pre> + +<p> +The next two sections discuss the relationship between length and capacity. +</p> + +<p> +The zero value of a slice is <code>nil</code>. The <code>len</code> and +<code>cap</code> functions will both return 0 for a nil slice. +</p> + +<p> +A slice can also be formed by "slicing" an existing slice or array. Slicing is +done by specifying a half-open range with two indices separated by a colon. For +example, the expression <code>b[1:4]</code> creates a slice including elements +1 through 3 of <code>b</code> (the indices of the resulting slice will be 0 +through 2). +</p> + +<pre> +b := []byte{'g', 'o', 'l', 'a', 'n', 'g'} +// b[1:4] == []byte{'o', 'l', 'a'}, sharing the same storage as b +</pre> + +<p> +The start and end indices of a slice expression are optional; they default to zero and the slice's length respectively: +</p> + +<pre> +// b[:2] == []byte{'g', 'o'} +// b[2:] == []byte{'l', 'a', 'n', 'g'} +// b[:] == b +</pre> + +<p> +This is also the syntax to create a slice given an array: +</p> + +<pre> +x := [3]string{"Лайка", "Белка", "Стрелка"} +s := x[:] // a slice referencing the storage of x +</pre> + +<p> +<b>Slice internals</b> +</p> + +<p> +A slice is a descriptor of an array segment. It consists of a pointer to the +array, the length of the segment, and its capacity (the maximum length of the +segment). +</p> + +<p> +<img src="slice-struct.png"> +</p> + +<p> +Our variable <code>s</code>, created earlier by <code>make([]byte, 5)</code>, +is structured like this: +</p> + +<p> +<img src="slice-1.png"> +</p> + +<p> +The length is the number of elements referred to by the slice. The capacity is +the number of elements in the underlying array (beginning at the element +referred to by the slice pointer). The distinction between length and capacity +will be made clear as we walk through the next few examples. +</p> + +<p> +As we slice <code>s</code>, observe the changes in the slice data structure and +their relation to the underlying array: +</p> + +<pre> +s = s[2:4] +</pre> + +<p> +<img src="slice-2.png"> +</p> + +<p> +Slicing does not copy the slice's data. It creates a new slice value that +points to the original array. This makes slice operations as efficient as +manipulating array indices. Therefore, modifying the <i>elements</i> (not the +slice itself) of a re-slice modifies the elements of the original slice: +</p> + +<pre> +d := []byte{'r', 'o', 'a', 'd'} +e := d[2:] +// e == []byte{'a', 'd'} +e[1] == 'm' +// e == []byte{'a', 'm'} +// d == []byte{'r', 'o', 'a', 'm'} +</pre> + +<p> +Earlier we sliced <code>s</code> to a length shorter than its capacity. We can +grow s to its capacity by slicing it again: +</p> + +<pre> +s = s[:cap(s)] +</pre> + +<p> +<img src="slice-3.png"> +</p> + +<p> +A slice cannot be grown beyond its capacity. Attempting to do so will cause a +runtime panic, just as when indexing outside the bounds of a slice or array. +Similarly, slices cannot be re-sliced below zero to access earlier elements in +the array. +</p> + +<p> +<b>Growing slices (the copy and append functions)</b> +</p> + +<p> +To increase the capacity of a slice one must create a new, larger slice and +copy the contents of the original slice into it. This technique is how dynamic +array implementations from other languages work behind the scenes. The next +example doubles the capacity of <code>s</code> by making a new slice, +<code>t</code>, copying the contents of <code>s</code> into <code>t</code>, and +then assigning the slice value <code>t</code> to <code>s</code>: +</p> + +<pre> +t := make([]byte, len(s), (cap(s)+1)*2) // +1 in case cap(s) == 0 +for i := range s { + t[i] = s[i] +} +s = t +</pre> + +<p> +The looping piece of this common operation is made easier by the built-in copy +function. As the name suggests, copy copies data from a source slice to a +destination slice. It returns the number of elements copied. +</p> + +<pre> +func copy(dst, src []T) int +</pre> + +<p> +The <code>copy</code> function supports copying between slices of different +lengths (it will copy only up to the smaller number of elements). In addition, +<code>copy</code> can handle source and destination slices that share the same +underlying array, handling overlapping slices correctly. +</p> + +<p> +Using <code>copy</code>, we can simplify the code snippet above: +</p> + +<pre> +t := make([]byte, len(s), (cap(s)+1)*2) +copy(t, s) +s = t +</pre> + +<p> +A common operation is to append data to the end of a slice. This function +appends byte elements to a slice of bytes, growing the slice if necessary, and +returns the updated slice value: +</p> + +{{code "/doc/progs/slices.go" `/AppendByte/` `/STOP/`}} + +<p> +One could use <code>AppendByte</code> like this: +</p> + +<pre> +p := []byte{2, 3, 5} +p = AppendByte(p, 7, 11, 13) +// p == []byte{2, 3, 5, 7, 11, 13} +</pre> + +<p> +Functions like <code>AppendByte</code> are useful because they offer complete +control over the way the slice is grown. Depending on the characteristics of +the program, it may be desirable to allocate in smaller or larger chunks, or to +put a ceiling on the size of a reallocation. +</p> + +<p> +But most programs don't need complete control, so Go provides a built-in +<code>append</code> function that's good for most purposes; it has the +signature +</p> + +<pre> +func append(s []T, x ...T) []T +</pre> + +<p> +The <code>append</code> function appends the elements <code>x</code> to the end +of the slice <code>s</code>, and grows the slice if a greater capacity is +needed. +</p> + +<pre> +a := make([]int, 1) +// a == []int{0} +a = append(a, 1, 2, 3) +// a == []int{0, 1, 2, 3} +</pre> + +<p> +To append one slice to another, use <code>...</code> to expand the second +argument to a list of arguments. +</p> + +<pre> +a := []string{"John", "Paul"} +b := []string{"George", "Ringo", "Pete"} +a = append(a, b...) // equivalent to "append(a, b[0], b[1], b[2])" +// a == []string{"John", "Paul", "George", "Ringo", "Pete"} +</pre> + +<p> +Since the zero value of a slice (<code>nil</code>) acts like a zero-length +slice, you can declare a slice variable and then append to it in a loop: +</p> + +{{code "/doc/progs/slices.go" `/Filter/` `/STOP/`}} + +<p> +<b>A possible "gotcha"</b> +</p> + +<p> +As mentioned earlier, re-slicing a slice doesn't make a copy of the underlying +array. The full array will be kept in memory until it is no longer referenced. +Occasionally this can cause the program to hold all the data in memory when +only a small piece of it is needed. +</p> + +<p> +For example, this <code>FindDigits</code> function loads a file into memory and +searches it for the first group of consecutive numeric digits, returning them +as a new slice. +</p> + +{{code "/doc/progs/slices.go" `/digit/` `/STOP/`}} + +<p> +This code behaves as advertised, but the returned <code>[]byte</code> points +into an array containing the entire file. Since the slice references the +original array, as long as the slice is kept around the garbage collector can't +release the array; the few useful bytes of the file keep the entire contents in +memory. +</p> + +<p> +To fix this problem one can copy the interesting data to a new slice before +returning it: +</p> + +{{code "/doc/progs/slices.go" `/CopyDigits/` `/STOP/`}} + +<p> +A more concise version of this function could be constructed by using +<code>append</code>. This is left as an exercise for the reader. +</p> + +<p> +<b>Further Reading</b> +</p> + +<p> +<a href="/doc/effective_go.html">Effective Go</a> contains an +in-depth treatment of <a href="/doc/effective_go.html#slices">slices</a> +and <a href="/doc/effective_go.html#arrays">arrays</a>, +and the Go <a href="/doc/go_spec.html">language specification</a> +defines <a href="/doc/go_spec.html#Slice_types">slices</a> and their +<a href="/doc/go_spec.html#Length_and_capacity">associated</a> +<a href="/doc/go_spec.html#Making_slices_maps_and_channels">helper</a> +<a href="/doc/go_spec.html#Appending_and_copying_slices">functions</a>. +</p> diff --git a/doc/codelab/wiki/Makefile b/doc/articles/wiki/Makefile index 09c3291a0..0cb907185 100644 --- a/doc/codelab/wiki/Makefile +++ b/doc/articles/wiki/Makefile @@ -2,24 +2,19 @@ # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. -include ../../../src/Make.inc - all: index.html -include ../../../src/Make.common - -CLEANFILES+=index.html srcextract.bin htmlify.bin get.bin +CLEANFILES:=srcextract.bin htmlify.bin get.bin -index.html: srcextract.bin htmlify.bin +index.html: wiki.html srcextract.bin htmlify.bin PATH=.:$$PATH awk '/^!/{system(substr($$0,2)); next} {print}' < wiki.html | tr -d '\r' > index.html test: get.bin bash ./test.sh rm -f get.6 get.bin -%.bin: %.$O - $(LD) -o $@ $< - -%.$O: %.go - $(GC) $*.go +%.bin: %.go + go build -o $@ $^ +clean: + rm -f $(CLEANFILES) diff --git a/doc/codelab/wiki/edit.html b/doc/articles/wiki/edit.html index c14953b17..c14953b17 100644 --- a/doc/codelab/wiki/edit.html +++ b/doc/articles/wiki/edit.html diff --git a/doc/codelab/wiki/final-noclosure.go b/doc/articles/wiki/final-noclosure.go index 067f502c6..a23cf7a27 100644 --- a/doc/codelab/wiki/final-noclosure.go +++ b/doc/articles/wiki/final-noclosure.go @@ -1,11 +1,15 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + package main import ( - "http" + "errors" + "html/template" "io/ioutil" - "os" + "net/http" "regexp" - "template" ) type Page struct { @@ -13,12 +17,12 @@ type Page struct { Body []byte } -func (p *Page) save() os.Error { +func (p *Page) save() error { filename := p.Title + ".txt" return ioutil.WriteFile(filename, p.Body, 0600) } -func loadPage(title string) (*Page, os.Error) { +func loadPage(title string) (*Page, error) { filename := title + ".txt" body, err := ioutil.ReadFile(filename) if err != nil { @@ -61,21 +65,21 @@ func saveHandler(w http.ResponseWriter, r *http.Request) { p := &Page{Title: title, Body: []byte(body)} err = p.save() if err != nil { - http.Error(w, err.String(), http.StatusInternalServerError) + http.Error(w, err.Error(), http.StatusInternalServerError) return } http.Redirect(w, r, "/view/"+title, http.StatusFound) } func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) { - t, err := template.ParseFile(tmpl+".html") + t, err := template.ParseFiles(tmpl + ".html") if err != nil { - http.Error(w, err.String(), http.StatusInternalServerError) + http.Error(w, err.Error(), http.StatusInternalServerError) return } err = t.Execute(w, p) if err != nil { - http.Error(w, err.String(), http.StatusInternalServerError) + http.Error(w, err.Error(), http.StatusInternalServerError) } } @@ -83,11 +87,11 @@ const lenPath = len("/view/") var titleValidator = regexp.MustCompile("^[a-zA-Z0-9]+$") -func getTitle(w http.ResponseWriter, r *http.Request) (title string, err os.Error) { +func getTitle(w http.ResponseWriter, r *http.Request) (title string, err error) { title = r.URL.Path[lenPath:] if !titleValidator.MatchString(title) { http.NotFound(w, r) - err = os.NewError("Invalid Page Title") + err = errors.New("Invalid Page Title") } return } diff --git a/doc/codelab/wiki/final-noerror.go b/doc/articles/wiki/final-noerror.go index b8edbee9b..e11d268e2 100644 --- a/doc/codelab/wiki/final-noerror.go +++ b/doc/articles/wiki/final-noerror.go @@ -1,10 +1,13 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + package main import ( - "http" + "html/template" "io/ioutil" - "os" - "template" + "net/http" ) type Page struct { @@ -12,12 +15,12 @@ type Page struct { Body []byte } -func (p *Page) save() os.Error { +func (p *Page) save() error { filename := p.Title + ".txt" return ioutil.WriteFile(filename, p.Body, 0600) } -func loadPage(title string) (*Page, os.Error) { +func loadPage(title string) (*Page, error) { filename := title + ".txt" body, err := ioutil.ReadFile(filename) if err != nil { @@ -34,14 +37,14 @@ func editHandler(w http.ResponseWriter, r *http.Request) { if err != nil { p = &Page{Title: title} } - t, _ := template.ParseFile("edit.html") + t, _ := template.ParseFiles("edit.html") t.Execute(w, p) } func viewHandler(w http.ResponseWriter, r *http.Request) { title := r.URL.Path[lenPath:] p, _ := loadPage(title) - t, _ := template.ParseFile("view.html") + t, _ := template.ParseFiles("view.html") t.Execute(w, p) } diff --git a/doc/codelab/wiki/final-parsetemplate.go b/doc/articles/wiki/final-parsetemplate.go index f25012eed..6234c08f2 100644 --- a/doc/codelab/wiki/final-parsetemplate.go +++ b/doc/articles/wiki/final-parsetemplate.go @@ -1,11 +1,14 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + package main import ( - "http" + "html/template" "io/ioutil" - "os" + "net/http" "regexp" - "template" ) type Page struct { @@ -13,12 +16,12 @@ type Page struct { Body []byte } -func (p *Page) save() os.Error { +func (p *Page) save() error { filename := p.Title + ".txt" return ioutil.WriteFile(filename, p.Body, 0600) } -func loadPage(title string) (*Page, os.Error) { +func loadPage(title string) (*Page, error) { filename := title + ".txt" body, err := ioutil.ReadFile(filename) if err != nil { @@ -49,21 +52,21 @@ func saveHandler(w http.ResponseWriter, r *http.Request, title string) { p := &Page{Title: title, Body: []byte(body)} err := p.save() if err != nil { - http.Error(w, err.String(), http.StatusInternalServerError) + http.Error(w, err.Error(), http.StatusInternalServerError) return } http.Redirect(w, r, "/view/"+title, http.StatusFound) } func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) { - t, err := template.ParseFile(tmpl+".html", nil) + t, err := template.ParseFiles(tmpl + ".html") if err != nil { - http.Error(w, err.String(), http.StatusInternalServerError) + http.Error(w, err.Error(), http.StatusInternalServerError) return } err = t.Execute(w, p) if err != nil { - http.Error(w, err.String(), http.StatusInternalServerError) + http.Error(w, err.Error(), http.StatusInternalServerError) } } diff --git a/doc/codelab/wiki/final-template.go b/doc/articles/wiki/final-template.go index aab536ee1..f295b9d60 100644 --- a/doc/codelab/wiki/final-template.go +++ b/doc/articles/wiki/final-template.go @@ -1,10 +1,13 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + package main import ( - "http" + "html/template" "io/ioutil" - "os" - "template" + "net/http" ) type Page struct { @@ -12,12 +15,12 @@ type Page struct { Body []byte } -func (p *Page) save() os.Error { +func (p *Page) save() error { filename := p.Title + ".txt" return ioutil.WriteFile(filename, p.Body, 0600) } -func loadPage(title string) (*Page, os.Error) { +func loadPage(title string) (*Page, error) { filename := title + ".txt" body, err := ioutil.ReadFile(filename) if err != nil { @@ -52,7 +55,7 @@ func saveHandler(w http.ResponseWriter, r *http.Request) { } func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) { - t, _ := template.ParseFile(tmpl+".html", nil) + t, _ := template.ParseFiles(tmpl + ".html") t.Execute(w, p) } diff --git a/doc/codelab/wiki/final.go b/doc/articles/wiki/final.go index 47a4c3473..e93cdee47 100644 --- a/doc/codelab/wiki/final.go +++ b/doc/articles/wiki/final.go @@ -1,11 +1,14 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + package main import ( - "http" + "html/template" "io/ioutil" - "os" + "net/http" "regexp" - "template" ) type Page struct { @@ -13,12 +16,12 @@ type Page struct { Body []byte } -func (p *Page) save() os.Error { +func (p *Page) save() error { filename := p.Title + ".txt" return ioutil.WriteFile(filename, p.Body, 0600) } -func loadPage(title string) (*Page, os.Error) { +func loadPage(title string) (*Page, error) { filename := title + ".txt" body, err := ioutil.ReadFile(filename) if err != nil { @@ -49,25 +52,18 @@ func saveHandler(w http.ResponseWriter, r *http.Request, title string) { p := &Page{Title: title, Body: []byte(body)} err := p.save() if err != nil { - http.Error(w, err.String(), http.StatusInternalServerError) + http.Error(w, err.Error(), http.StatusInternalServerError) return } http.Redirect(w, r, "/view/"+title, http.StatusFound) } -var templates = make(map[string]*template.Template) - -func init() { - for _, tmpl := range []string{"edit", "view"} { - t := template.Must(template.ParseFile(tmpl+".html")) - templates[tmpl] = t - } -} +var templates = template.Must(template.ParseFiles("edit.html", "view.html")) func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) { - err := templates[tmpl].Execute(w, p) + err := templates.ExecuteTemplate(w, tmpl+".html", p) if err != nil { - http.Error(w, err.String(), http.StatusInternalServerError) + http.Error(w, err.Error(), http.StatusInternalServerError) } } diff --git a/doc/codelab/wiki/get.go b/doc/articles/wiki/get.go index c36684e3e..c6e9bf28b 100644 --- a/doc/codelab/wiki/get.go +++ b/doc/articles/wiki/get.go @@ -1,12 +1,16 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + package main import ( - "http" "flag" "fmt" "io" "log" "net" + "net/http" "os" "strings" ) @@ -32,7 +36,7 @@ func main() { log.Fatal("no url supplied") } var r *http.Response - var err os.Error + var err error if *post != "" { b := strings.NewReader(*post) r, err = http.Post(url, "application/x-www-form-urlencoded", b) diff --git a/doc/articles/wiki/htmlify.go b/doc/articles/wiki/htmlify.go new file mode 100644 index 000000000..2a845a174 --- /dev/null +++ b/doc/articles/wiki/htmlify.go @@ -0,0 +1,16 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "io/ioutil" + "os" + "text/template" +) + +func main() { + b, _ := ioutil.ReadAll(os.Stdin) + template.HTMLEscape(os.Stdout, b) +} diff --git a/doc/codelab/wiki/http-sample.go b/doc/articles/wiki/http-sample.go index 33379a1b6..ac8cc4f2d 100644 --- a/doc/codelab/wiki/http-sample.go +++ b/doc/articles/wiki/http-sample.go @@ -2,7 +2,7 @@ package main import ( "fmt" - "http" + "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { diff --git a/doc/codelab/wiki/wiki.html b/doc/articles/wiki/index.html index 634babd8b..52bf7e798 100644 --- a/doc/codelab/wiki/wiki.html +++ b/doc/articles/wiki/index.html @@ -1,13 +1,17 @@ -<!-- Codelab: Writing Web Applications --> +<!--{ + "Title": "Writing Web Applications", + "Template": true +}--> + <h2>Introduction</h2> <p> -Covered in this codelab: +Covered in this tutorial: </p> <ul> <li>Creating a data structure with load and save methods</li> -<li>Using the <code>http</code> package to build web applications -<li>Using the <code>template</code> package to process HTML templates</li> +<li>Using the <code>net/http</code> package to build web applications +<li>Using the <code>html/template</code> package to process HTML templates</li> <li>Using the <code>regexp</code> package to validate user input</li> <li>Using closures</li> </ul> @@ -18,30 +22,27 @@ Assumed knowledge: <ul> <li>Programming experience</li> <li>Understanding of basic web technologies (HTTP, HTML)</li> -<li>Some UNIX command-line knowledge</li> +<li>Some UNIX/DOS command-line knowledge</li> </ul> <h2>Getting Started</h2> <p> -At present, you need to have a Linux, OS X, or FreeBSD machine to run Go. If -you don't have access to one, you could set up a Linux Virtual Machine (using -<a href="http://www.virtualbox.org/">VirtualBox</a> or similar) or a -<a href="http://www.google.com/search?q=virtual+private+server">Virtual -Private Server</a>. +At present, you need to have a FreeBSD, Linux, OS X, or Windows machine to run Go. +We will use <code>$</code> to represent the command prompt. </p> <p> -Install Go (see the <a href="http://golang.org/doc/install.html">Installation Instructions</a>). +Install Go (see the <a href="/doc/install">Installation Instructions</a>). </p> <p> -Make a new directory for this codelab and cd to it: +Make a new directory for this tutorial inside your <code>GOPATH</code> and cd to it: </p> <pre> -$ mkdir ~/gowiki -$ cd ~/gowiki +$ mkdir gowiki +$ cd gowiki </pre> <p> @@ -55,15 +56,13 @@ package main import ( "fmt" "io/ioutil" - "os" ) </pre> <p> -We import the <code>fmt</code>, <code>ioutil</code> and <code>os</code> -packages from the Go standard library. Later, as we implement additional -functionality, we will add more packages to this <code>import</code> -declaration. +We import the <code>fmt</code> and <code>ioutil</code> packages from the Go +standard library. Later, as we implement additional functionality, we will +add more packages to this <code>import</code> declaration. </p> <h2>Data Structures</h2> @@ -75,14 +74,12 @@ Here, we define <code>Page</code> as a struct with two fields representing the title and body. </p> -<pre> -!srcextract.bin -src=part1.go -name=Page -</pre> +{{code "doc/articles/wiki/part1.go" `/^type Page/` `/}/`}} <p> The type <code>[]byte</code> means "a <code>byte</code> slice". -(See <a href="http://golang.org/doc/effective_go.html#slices">Effective Go</a> -for more on slices.) +(See <a href="/doc/articles/slices_usage_and_internals.html">Slices: usage and +internals</a> for more on slices.) The <code>Body</code> element is a <code>[]byte</code> rather than <code>string</code> because that is the type expected by the <code>io</code> libraries we will use, as you'll see below. @@ -94,14 +91,12 @@ But what about persistent storage? We can address that by creating a <code>save</code> method on <code>Page</code>: </p> -<pre> -!srcextract.bin -src=part1.go -name=save -</pre> +{{code "doc/articles/wiki/part1.go" `/^func.*Page.*save/` `/}/`}} <p> This method's signature reads: "This is a method named <code>save</code> that takes as its receiver <code>p</code>, a pointer to <code>Page</code> . It takes -no parameters, and returns a value of type <code>os.Error</code>." +no parameters, and returns a value of type <code>error</code>." </p> <p> @@ -110,7 +105,7 @@ file. For simplicity, we will use the <code>Title</code> as the file name. </p> <p> -The <code>save</code> method returns an <code>os.Error</code> value because +The <code>save</code> method returns an <code>error</code> value because that is the return type of <code>WriteFile</code> (a standard library function that writes a byte slice to a file). The <code>save</code> method returns the error value, to let the application handle it should anything go wrong while @@ -130,9 +125,7 @@ read-write permissions for the current user only. (See the Unix man page We will want to load pages, too: </p> -<pre> -!srcextract.bin -src=part1-noerror.go -name=loadPage -</pre> +{{code "doc/articles/wiki/part1-noerror.go" `/^func loadPage/` `/^}/`}} <p> The function <code>loadPage</code> constructs the file name from @@ -142,7 +135,7 @@ The function <code>loadPage</code> constructs the file name from <p> Functions can return multiple values. The standard library function -<code>io.ReadFile</code> returns <code>[]byte</code> and <code>os.Error</code>. +<code>io.ReadFile</code> returns <code>[]byte</code> and <code>error</code>. In <code>loadPage</code>, error isn't being handled yet; the "blank identifier" represented by the underscore (<code>_</code>) symbol is used to throw away the error return value (in essence, assigning the value to nothing). @@ -151,19 +144,16 @@ error return value (in essence, assigning the value to nothing). <p> But what happens if <code>ReadFile</code> encounters an error? For example, the file might not exist. We should not ignore such errors. Let's modify the -function to return <code>*Page</code> and <code>os.Error</code>. +function to return <code>*Page</code> and <code>error</code>. </p> -<pre> -!srcextract.bin -src=part1.go -name=loadPage -</pre> +{{code "doc/articles/wiki/part1.go" `/^func loadPage/` `/^}/`}} <p> Callers of this function can now check the second parameter; if it is <code>nil</code> then it has successfully loaded a Page. If not, it will be an -<code>os.Error</code> that can be handled by the caller (see the <a -href="http://golang.org/pkg/os/#Error">os package documentation</a> for -details). +<code>error</code> that can be handled by the caller (see the +<a href="/ref/spec#Errors">language specification</a> for details). </p> <p> @@ -172,9 +162,7 @@ load from a file. Let's write a <code>main</code> function to test what we've written: </p> -<pre> -!srcextract.bin -src=part1.go -name=main -</pre> +{{code "doc/articles/wiki/part1.go" `/^func main/` `/^}/`}} <p> After compiling and executing this code, a file named <code>TestPage.txt</code> @@ -188,31 +176,27 @@ You can compile and run the program like this: </p> <pre> -$ 8g wiki.go -$ 8l wiki.8 -$ ./8.out +$ go build wiki.go +$ ./wiki This is a sample page. </pre> <p> -(The <code>8g</code> and <code>8l</code> commands are applicable to -<code>GOARCH=386</code>. If you're on an <code>amd64</code> system, -substitute 6's for the 8's.) +(If you're using Windows you must type "<code>wiki</code>" without the +"<code>./</code>" to run the program.) </p> <p> <a href="part1.go">Click here to view the code we've written so far.</a> </p> -<h2>Introducing the <code>http</code> package (an interlude)</h2> +<h2>Introducing the <code>net/http</code> package (an interlude)</h2> <p> Here's a full working example of a simple web server: </p> -<pre> -!htmlify.bin < http-sample.go -</pre> +{{code "doc/articles/wiki/http-sample.go"}} <p> The <code>main</code> function begins with a call to @@ -256,18 +240,17 @@ the program would present a page containing: </p> <pre>Hi there, I love monkeys!</pre> -<h2>Using <code>http</code> to serve wiki pages</h2> +<h2>Using <code>net/http</code> to serve wiki pages</h2> <p> -To use the <code>http</code> package, it must be imported: +To use the <code>net/http</code> package, it must be imported: </p> <pre> import ( "fmt" - <b>"http"</b> + <b>"net/http"</b> "io/ioutil" - "os" ) </pre> @@ -275,11 +258,9 @@ import ( Let's create a handler to view a wiki page: </p> -<pre> -!srcextract.bin -src=part2.go -name=lenPath +{{code "doc/articles/wiki/part2.go" `/^const lenPath/`}} -!srcextract.bin -src=part2.go -name=viewHandler -</pre> +{{code "doc/articles/wiki/part2.go" `/^func viewHandler/` `/^}/`}} <p> First, this function extracts the page title from <code>r.URL.Path</code>, @@ -297,7 +278,7 @@ HTML, and writes it to <code>w</code>, the <code>http.ResponseWriter</code>. </p> <p> -Again, note the use of <code>_</code> to ignore the <code>os.Error</code> +Again, note the use of <code>_</code> to ignore the <code>error</code> return value from <code>loadPage</code>. This is done here for simplicity and generally considered bad practice. We will attend to this later. </p> @@ -308,9 +289,7 @@ initializes <code>http</code> using the <code>viewHandler</code> to handle any requests under the path <code>/view/</code>. </p> -<pre> -!srcextract.bin -src=part2.go -name=main -</pre> +{{code "doc/articles/wiki/part2.go" `/^func main/` `/^}/`}} <p> <a href="part2.go">Click here to view the code we've written so far.</a> @@ -318,14 +297,17 @@ any requests under the path <code>/view/</code>. <p> Let's create some page data (as <code>test.txt</code>), compile our code, and -try serving a wiki page: +try serving a wiki page. +</p> + +<p> +Open <code>test.txt</code> file in your editor, and save the string "Hello world" (without quotes) +in it. </p> <pre> -$ echo "Hello world" > test.txt -$ 8g wiki.go -$ 8l wiki.8 -$ ./8.out +$ go build wiki.go +$ ./wiki </pre> <p> @@ -347,9 +329,7 @@ form. First, we add them to <code>main()</code>: </p> -<pre> -!srcextract.bin -src=final-noclosure.go -name=main -</pre> +{{code "doc/articles/wiki/final-noclosure.go" `/^func main/` `/^}/`}} <p> The function <code>editHandler</code> loads the page @@ -357,28 +337,24 @@ The function <code>editHandler</code> loads the page and displays an HTML form. </p> -<pre> -!srcextract.bin -src=notemplate.go -name=editHandler -</pre> +{{code "doc/articles/wiki/notemplate.go" `/^func editHandler/` `/^}/`}} <p> This function will work fine, but all that hard-coded HTML is ugly. Of course, there is a better way. </p> -<h2>The <code>template</code> package</h2> +<h2>The <code>html/template</code> package</h2> <p> -The <code>template</code> package is part of the Go standard library. -(A new template package is coming; this code lab will be updated soon.) -We can -use <code>template</code> to keep the HTML in a separate file, allowing -us to change the layout of our edit page without modifying the underlying Go -code. +The <code>html/template</code> package is part of the Go standard library. +We can use <code>html/template</code> to keep the HTML in a separate file, +allowing us to change the layout of our edit page without modifying the +underlying Go code. </p> <p> -First, we must add <code>template</code> to the list of imports: +First, we must add <code>html/template</code> to the list of imports: </p> <pre> @@ -386,7 +362,7 @@ import ( "http" "io/ioutil" "os" - <b>"template"</b> + <b>"html/template"</b> ) </pre> @@ -395,21 +371,17 @@ Let's create a template file containing the HTML form. Open a new file named <code>edit.html</code>, and add the following lines: </p> -<pre> -!htmlify.bin < edit.html -</pre> +{{code "doc/articles/wiki/edit.html"}} <p> Modify <code>editHandler</code> to use the template, instead of the hard-coded HTML: </p> -<pre> -!srcextract.bin -src=final-noerror.go -name=editHandler -</pre> +{{code "doc/articles/wiki/final-noerror.go" `/^func editHandler/` `/^}/`}} <p> -The function <code>template.ParseFile</code> will read the contents of +The function <code>template.ParseFiles</code> will read the contents of <code>edit.html</code> and return a <code>*template.Template</code>. </p> @@ -441,17 +413,13 @@ While we're working with templates, let's create a template for our <code>viewHandler</code> called <code>view.html</code>: </p> -<pre> -!htmlify.bin < view.html -</pre> +{{code "doc/articles/wiki/view.html"}} <p> Modify <code>viewHandler</code> accordingly: </p> -<pre> -!srcextract.bin -src=final-noerror.go -name=viewHandler -</pre> +{{code "doc/articles/wiki/final-noerror.go" `/^func viewHandler/` `/^}/`}} <p> Notice that we've used almost exactly the same templating code in both @@ -459,13 +427,9 @@ handlers. Let's remove this duplication by moving the templating code to its own function: </p> -<pre> -!srcextract.bin -src=final-template.go -name=viewHandler - -!srcextract.bin -src=final-template.go -name=editHandler - -!srcextract.bin -src=final-template.go -name=renderTemplate -</pre> +{{code "doc/articles/wiki/final-template.go" `/^func viewHandler/` `/^}/`}} +{{code "doc/articles/wiki/final-template.go" `/^func editHandler/` `/^}/`}} +{{code "doc/articles/wiki/final-template.go" `/^func renderTemplate/` `/^}/`}} <p> The handlers are now shorter and simpler. @@ -474,15 +438,14 @@ The handlers are now shorter and simpler. <h2>Handling non-existent pages</h2> <p> -What if you visit <code>/view/APageThatDoesntExist</code>? The program will -crash. This is because it ignores the error return value from -<code>loadPage</code>. Instead, if the requested Page doesn't exist, it should -redirect the client to the edit Page so the content may be created: +What if you visit <a href="http://localhost:8080/view/APageThatDoesntExist"> +<code>/view/APageThatDoesntExist</code></a>? The program will crash. This is +because it ignores the error return value from <code>loadPage</code>. Instead, +if the requested Page doesn't exist, it should redirect the client to the edit +Page so the content may be created: </p> -<pre> -!srcextract.bin -src=final-noclosure.go -name=viewHandler -</pre> +{{code "doc/articles/wiki/final-noclosure.go" `/^func viewHandler/` `/^}/`}} <p> The <code>http.Redirect</code> function adds an HTTP status code of @@ -496,9 +459,7 @@ header to the HTTP response. The function <code>saveHandler</code> will handle the form submission. </p> -<pre> -!srcextract.bin -src=final-template.go -name=saveHandler -</pre> +{{code "doc/articles/wiki/final-template.go" `/^func saveHandler/` `/^}/`}} <p> The page title (provided in the URL) and the form's only field, @@ -528,9 +489,7 @@ function and the user will be notified. First, let's handle the errors in <code>renderTemplate</code>: </p> -<pre> -!srcextract.bin -src=final-parsetemplate.go -name=renderTemplate -</pre> +{{code "doc/articles/wiki/final-parsetemplate.go" `/^func renderTemplate/` `/^}/`}} <p> The <code>http.Error</code> function sends a specified HTTP response code @@ -542,9 +501,7 @@ Already the decision to put this in a separate function is paying off. Now let's fix up <code>saveHandler</code>: </p> -<pre> -!srcextract.bin -src=final-noclosure.go -name=saveHandler -</pre> +{{code "doc/articles/wiki/final-noclosure.go" `/^func saveHandler/` `/^}/`}} <p> Any errors that occur during <code>p.save()</code> will be reported @@ -555,35 +512,28 @@ to the user. <p> There is an inefficiency in this code: <code>renderTemplate</code> calls -<code>ParseFile</code> every time a page is rendered. -A better approach would be to call <code>ParseFile</code> once for each -template at program initialization, and store the resultant -<code>*Template</code> values in a data structure for later use. +<code>ParseFiles</code> every time a page is rendered. +A better approach would be to call <code>ParseFiles</code> once at program +initialization, parsing all templates into a single <code>*Template</code>. +Then we can use the +<a href="/pkg/html/template/#Template.ExecuteTemplate"><code>ExecuteTemplate</code></a> +method to render a specific template. </p> <p> -First we create a global map named <code>templates</code> in which to store -our <code>*Template</code> values, keyed by <code>string</code> -(the template name): +First we create a global variable named <code>templates</code>, and initialize +it with <code>ParseFiles</code>. </p> -<pre> -!srcextract.bin -src=final.go -name=templates -</pre> +{{code "doc/articles/wiki/final.go" `/var templates/`}} <p> -Then we create an <code>init</code> function, which will be called before -<code>main</code> at program initialization. The function -<code>template.Must</code> is a convenience wrapper that panics when passed a -non-nil <code>os.Error</code> value, and otherwise returns the +The function <code>template.Must</code> is a convenience wrapper that panics +when passed a non-nil <code>error</code> value, and otherwise returns the <code>*Template</code> unaltered. A panic is appropriate here; if the templates can't be loaded the only sensible thing to do is exit the program. </p> -<pre> -!srcextract.bin -src=final.go -name=init -</pre> - <p> A <code>for</code> loop is used with a <code>range</code> statement to iterate over an array constant containing the names of the templates we want parsed. @@ -592,13 +542,17 @@ that array. </p> <p> -We then modify our <code>renderTemplate</code> function to call -the <code>Execute</code> method on the appropriate <code>Template</code> from -<code>templates</code>: +We then modify the <code>renderTemplate</code> function to call the +<code>templates.ExecuteTemplate</code> method with the name of the appropriate +template: +</p> -<pre> -!srcextract.bin -src=final.go -name=renderTemplate -</pre> +{{code "doc/articles/wiki/final.go" `/func renderTemplate/` `/^}/`}} + +<p> +Note that the template name is the template file name, so we must +append <code>".html"</code> to the <code>tmpl</code> argument. +</p> <h2>Validation</h2> @@ -613,16 +567,14 @@ First, add <code>"regexp"</code> to the <code>import</code> list. Then we can create a global variable to store our validation regexp: </p> -<pre> -!srcextract.bin -src=final-noclosure.go -name=titleValidator -</pre> +{{code "doc/articles/wiki/final-noclosure.go" `/^var titleValidator/`}} <p> The function <code>regexp.MustCompile</code> will parse and compile the regular expression, and return a <code>regexp.Regexp</code>. <code>MustCompile</code> is distinct from <code>Compile</code> in that it will panic if the expression compilation fails, while <code>Compile</code> returns -an <code>os.Error</code> as a second parameter. +an <code>error</code> as a second parameter. </p> <p> @@ -630,9 +582,7 @@ Now, let's write a function that extracts the title string from the request URL, and tests it against our <code>TitleValidator</code> expression: </p> -<pre> -!srcextract.bin -src=final-noclosure.go -name=getTitle -</pre> +{{code "doc/articles/wiki/final-noclosure.go" `/func getTitle/` `/^}/`}} <p> If the title is valid, it will be returned along with a <code>nil</code> @@ -645,13 +595,9 @@ handler. Let's put a call to <code>getTitle</code> in each of the handlers: </p> -<pre> -!srcextract.bin -src=final-noclosure.go -name=viewHandler - -!srcextract.bin -src=final-noclosure.go -name=editHandler - -!srcextract.bin -src=final-noclosure.go -name=saveHandler -</pre> +{{code "doc/articles/wiki/final-noclosure.go" `/^func viewHandler/` `/^}/`}} +{{code "doc/articles/wiki/final-noclosure.go" `/^func editHandler/` `/^}/`}} +{{code "doc/articles/wiki/final-noclosure.go" `/^func saveHandler/` `/^}/`}} <h2>Introducing Function Literals and Closures</h2> @@ -659,7 +605,7 @@ Let's put a call to <code>getTitle</code> in each of the handlers: Catching the error condition in each handler introduces a lot of repeated code. What if we could wrap each of the handlers in a function that does this validation and error checking? Go's -<a href="http://golang.org/doc/go_spec.html#Function_declarations">function +<a href="/ref/spec#Function_declarations">function literals</a> provide a powerful means of abstracting functionality that can help us here. </p> @@ -702,9 +648,7 @@ Now we can take the code from <code>getTitle</code> and use it here (with some minor modifications): </p> -<pre> -!srcextract.bin -src=final.go -name=makeHandler -</pre> +{{code "doc/articles/wiki/final.go" `/func makeHandler/` `/^}/`}} <p> The closure returned by <code>makeHandler</code> is a function that takes @@ -725,22 +669,16 @@ Now we can wrap the handler functions with <code>makeHandler</code> in package: </p> -<pre> -!srcextract.bin -src=final.go -name=main -</pre> +{{code "doc/articles/wiki/final.go" `/func main/` `/^}/`}} <p> Finally we remove the calls to <code>getTitle</code> from the handler functions, making them much simpler: </p> -<pre> -!srcextract.bin -src=final.go -name=viewHandler - -!srcextract.bin -src=final.go -name=editHandler - -!srcextract.bin -src=final.go -name=saveHandler -</pre> +{{code "doc/articles/wiki/final.go" `/^func viewHandler/` `/^}/`}} +{{code "doc/articles/wiki/final.go" `/^func editHandler/` `/^}/`}} +{{code "doc/articles/wiki/final.go" `/^func saveHandler/` `/^}/`}} <h2>Try it out!</h2> @@ -753,9 +691,8 @@ Recompile the code, and run the app: </p> <pre> -$ 8g wiki.go -$ 8l wiki.8 -$ ./8.out +$ go build wiki.go +$ ./wiki </pre> <p> diff --git a/doc/codelab/wiki/notemplate.go b/doc/articles/wiki/notemplate.go index 9cbe9ad76..33006ac95 100644 --- a/doc/codelab/wiki/notemplate.go +++ b/doc/articles/wiki/notemplate.go @@ -1,10 +1,13 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + package main import ( "fmt" - "http" "io/ioutil" - "os" + "net/http" ) type Page struct { @@ -12,12 +15,12 @@ type Page struct { Body []byte } -func (p *Page) save() os.Error { +func (p *Page) save() error { filename := p.Title + ".txt" return ioutil.WriteFile(filename, p.Body, 0600) } -func loadPage(title string) (*Page, os.Error) { +func loadPage(title string) (*Page, error) { filename := title + ".txt" body, err := ioutil.ReadFile(filename) if err != nil { diff --git a/doc/codelab/wiki/part1-noerror.go b/doc/articles/wiki/part1-noerror.go index 14cfc321a..7577b7b46 100644 --- a/doc/codelab/wiki/part1-noerror.go +++ b/doc/articles/wiki/part1-noerror.go @@ -1,9 +1,12 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + package main import ( "fmt" "io/ioutil" - "os" ) type Page struct { @@ -11,7 +14,7 @@ type Page struct { Body []byte } -func (p *Page) save() os.Error { +func (p *Page) save() error { filename := p.Title + ".txt" return ioutil.WriteFile(filename, p.Body, 0600) } diff --git a/doc/codelab/wiki/part1.go b/doc/articles/wiki/part1.go index 4b0654f8b..d7bf1be97 100644 --- a/doc/codelab/wiki/part1.go +++ b/doc/articles/wiki/part1.go @@ -1,9 +1,12 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + package main import ( "fmt" "io/ioutil" - "os" ) type Page struct { @@ -11,12 +14,12 @@ type Page struct { Body []byte } -func (p *Page) save() os.Error { +func (p *Page) save() error { filename := p.Title + ".txt" return ioutil.WriteFile(filename, p.Body, 0600) } -func loadPage(title string) (*Page, os.Error) { +func loadPage(title string) (*Page, error) { filename := title + ".txt" body, err := ioutil.ReadFile(filename) if err != nil { diff --git a/doc/codelab/wiki/part2.go b/doc/articles/wiki/part2.go index d57c3a01f..dd4365c82 100644 --- a/doc/codelab/wiki/part2.go +++ b/doc/articles/wiki/part2.go @@ -1,10 +1,13 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + package main import ( "fmt" - "http" "io/ioutil" - "os" + "net/http" ) type Page struct { @@ -12,12 +15,12 @@ type Page struct { Body []byte } -func (p *Page) save() os.Error { +func (p *Page) save() error { filename := p.Title + ".txt" return ioutil.WriteFile(filename, p.Body, 0600) } -func loadPage(title string) (*Page, os.Error) { +func loadPage(title string) (*Page, error) { filename := title + ".txt" body, err := ioutil.ReadFile(filename) if err != nil { diff --git a/doc/codelab/wiki/srcextract.go b/doc/articles/wiki/srcextract.go index 6b5fbcb43..813e25283 100644 --- a/doc/codelab/wiki/srcextract.go +++ b/doc/articles/wiki/srcextract.go @@ -1,15 +1,19 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + package main import ( "bytes" "flag" + "go/ast" "go/parser" "go/printer" - "go/ast" "go/token" "log" - "template" "os" + "text/template" ) var ( diff --git a/doc/codelab/wiki/test.sh b/doc/articles/wiki/test.bash index ed63ff20f..5c2cb60dc 100755 --- a/doc/codelab/wiki/test.sh +++ b/doc/articles/wiki/test.bash @@ -1,4 +1,7 @@ #!/usr/bin/env bash +# Copyright 2010 The Go Authors. All rights reserved. +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file. set -e wiki_pid= @@ -8,10 +11,10 @@ cleanup() { } trap cleanup 0 INT -gomake get.bin +go build -o get.bin get.go addr=$(./get.bin -addr) sed s/:8080/$addr/ < final.go > final-test.go -gomake final-test.bin +go build -o final-test.bin final-test.go (./final-test.bin) & wiki_pid=$! diff --git a/doc/codelab/wiki/test_Test.txt.good b/doc/articles/wiki/test_Test.txt.good index f0eec86f6..f0eec86f6 100644 --- a/doc/codelab/wiki/test_Test.txt.good +++ b/doc/articles/wiki/test_Test.txt.good diff --git a/doc/codelab/wiki/test_edit.good b/doc/articles/wiki/test_edit.good index 36c6dbb73..36c6dbb73 100644 --- a/doc/codelab/wiki/test_edit.good +++ b/doc/articles/wiki/test_edit.good diff --git a/doc/codelab/wiki/test_view.good b/doc/articles/wiki/test_view.good index 07e8edb22..07e8edb22 100644 --- a/doc/codelab/wiki/test_view.good +++ b/doc/articles/wiki/test_view.good diff --git a/doc/codelab/wiki/view.html b/doc/articles/wiki/view.html index 023391577..023391577 100644 --- a/doc/codelab/wiki/view.html +++ b/doc/articles/wiki/view.html diff --git a/doc/button_background.png b/doc/button_background.png Binary files differdeleted file mode 100644 index 86a3b3086..000000000 --- a/doc/button_background.png +++ /dev/null diff --git a/doc/cmd.html b/doc/cmd.html new file mode 100644 index 000000000..ac54923d4 --- /dev/null +++ b/doc/cmd.html @@ -0,0 +1,103 @@ +<!--{ + "Title": "Command Documentation", + "Path": "/doc/cmd" +}--> + +<p> +There is a suite of programs to build and process Go source code. +Instead of being run directly, programs in the suite are usually invoked +by the <a href="/cmd/go/">go</a> program. +</p> + +<p> +The most common way to run these programs is as a subcommand of the go program, +for instance as <code>go fmt</code>. Run like this, the command operates on +complete packages of Go source code, with the go program invoking the +underlying binary with arguments appropriate to package-level processing. +</p> + +<p> +The programs can also be run as stand-alone binaries, with unmodified arguments, +using the go <code>tool</code> subcommand, such as <code>go tool vet</code>. +This style of invocation allows, for instance, checking a single source file +rather than an entire package: <code>go tool vet myprogram.go</code> as +compared to <code>go vet mypackage</code>. +Some of the commands, such as <code>yacc</code>, are accessible only through +the go <code>tool</code> subcommand. +</p> + +<p> +Finally, two of the commands, <code>fmt</code> and <code>doc</code>, are also +installed as regular binaries called <code>gofmt</code> and <code>godoc</code> +because they are so often referenced. +</p> + +<p> +Click on the links for more documentation, invocation methods, and usage details. +</p> + +<table class="dir"> +<tr> +<th>Name</th> +<th> </th> +<th>Synopsis</th> +</tr> + +<tr> +<td><a href="/cmd/go/">go</a></td> +<td> </td> +<td> +The <code>go</code> program manages Go source code and runs the other +commands listed here. +See the command docs for usage +details. +<br><br> +</td> +</tr> + +<tr> +<td><a href="/cmd/cgo/">cgo</a></td> +<td> </td> +<td>Cgo enables the creation of Go packages that call C code.</td> +</tr> + +<tr> +<td><a href="/cmd/fix/">fix</a></td> +<td> </td> +<td>Fix finds Go programs that use old features of the language and libraries +and rewrites them to use newer ones.</td> +</tr> + +<tr> +<td><a href="/cmd/go/">doc</a></td> +<td> </td> +<td>Doc extracts and generates documentation for Go packages, it is also available as +an independent <a href="/cmd/godoc/">godoc</a> command with more general options.</td> +</tr> + +<tr> +<td><a href="/cmd/go/">fmt</a></td> +<td> </td> +<td>Fmt formats Go packages, it is also available as an independent <a href="/cmd/gofmt/"> +gofmt</a> command with more general options.</td> +</tr> + +<tr> +<td><a href="/cmd/vet/">vet</a></td> +<td> </td> +<td>Vet examines Go source code and reports suspicious constructs, such as Printf +calls whose arguments do not align with the format string.</td> +</tr> + +<tr> +<td><a href="/cmd/yacc/">yacc</a></td> +<td> </td> +<td>Yacc is a version of yacc that generates parsers implemented in Go.</td> +</tr> + +</table> + +<p> +This is an abridged list. See the <a href="/cmd/">full command reference</a> +for documentation of the compilers and more. +</p> diff --git a/doc/code.html b/doc/code.html index cdc60b071..238cb0643 100644 --- a/doc/code.html +++ b/doc/code.html @@ -1,164 +1,158 @@ -<!-- How to Write Go Code --> +<!--{ + "Title": "How to Write Go Code" +}--> <h2 id="Introduction">Introduction</h2> <p> -This document explains how to write a new package -and how to test code. -It assumes you have installed Go using the -<a href="install.html">installation instructions</a>. +This document demonstrates the development of a simple Go package and +introduces the <a href="/cmd/go/">go command</a>, the standard way to fetch, +build, and install Go packages and commands. </p> + +<h2 id="GOPATH">Code organization</h2> + +<h3><code>GOPATH</code> and workspaces</h3> + <p> -Before embarking on a change to an existing -package or the creation of a new package, -be sure to send mail to the -<a href="http://groups.google.com/group/golang-nuts">mailing list</a> -to let people know what you are thinking of doing. -Doing so helps avoid duplication of effort and -enables discussions about design before any code -has been written. +One of Go's design goals is to make writing software easier. To that end, the +<code>go</code> command doesn't use Makefiles or other configuration files to +guide program construction. Instead, it uses the source code to find +dependencies and determine build conditions. This means your source code and +build scripts are always in sync; they are one and the same. </p> -<h2 id="Community_resources">Community resources</h2> - <p> -For real-time help, there may be users or developers on -<code>#go-nuts</code> on the <a href="http://freenode.net/">Freenode</a> IRC server. +The one thing you must do is set a <code>GOPATH</code> environment variable. +<code>GOPATH</code> tells the <code>go</code> command (and other related tools) +where to find and install the Go packages on your system. </p> <p> -The official mailing list for discussion of the Go language is -<a href="http://groups.google.com/group/golang-nuts">Go Nuts</a>. +<code>GOPATH</code> is a list of paths. It shares the syntax of your system's +<code>PATH</code> environment variable. A typical <code>GOPATH</code> on +a Unix system might look like this: </p> +<pre> +GOPATH=/home/user/ext:/home/user/mygo +</pre> + <p> -Bugs can be reported using the <a href="http://code.google.com/p/go/issues/list">Go issue tracker</a>. +(On a Windows system use semicolons as the path separator instead of colons.) </p> <p> -For those who wish to keep up with development, -there is another mailing list, <a href="http://groups.google.com/group/golang-checkins">golang-checkins</a>, -that receives a message summarizing each checkin to the Go repository. +Each path in the list (in this case <code>/home/user/ext</code> or +<code>/home/user/mygo</code>) specifies the location of a <i>workspace</i>. +A workspace contains Go source files and their associated package objects, and +command executables. It has a prescribed structure of three subdirectories: </p> +<ul> +<li><code>src</code> contains Go source files, +<li><code>pkg</code> contains compiled package objects, and +<li><code>bin</code> contains executable commands. +</ul> -<h2 id="New_package">Creating a new package</h2> +<p> +Subdirectories of the <code>src</code> directory hold independent packages, and +all source files (<code>.go</code>, <code>.c</code>, <code>.h</code>, and +<code>.s</code>) in each subdirectory are elements of that subdirectory's +package. +</p> <p> -The source code for the package with import path -<code>x/y</code> is, by convention, kept in the -directory <code>$GOROOT/src/pkg/x/y</code>. +When building a program that imports the package "<code>widget</code>" the +<code>go</code> command looks for <code>src/pkg/widget</code> inside the Go root, +and then—if the package source isn't found there—it searches +for <code>src/widget</code> inside each workspace in order. </p> -<h3>Makefile</h3> +<p> +Multiple workspaces can offer some flexibility and convenience, but for now +we'll concern ourselves with only a single workspace. +</p> <p> -It would be nice to have Go-specific tools that -inspect the source files to determine what to build and in -what order, but for now, Go uses GNU <code>make</code>. -Thus, the first file to create in a new package directory is -usually the <code>Makefile</code>. -The basic form used in the Go source tree -is illustrated by <a href="../src/pkg/container/vector/Makefile"><code>src/pkg/container/vector/Makefile</code></a>: +Let's work through a simple example. First, create a <code>$HOME/mygo</code> +directory and its <code>src</code> subdirectory: </p> <pre> -include ../../../Make.inc - -TARG=container/vector -GOFILES=\ - intvector.go\ - stringvector.go\ - vector.go\ - -include ../../../Make.pkg +$ mkdir -p $HOME/mygo/src # create a place to put source code </pre> <p> -Outside the Go source tree (for personal packages), the standard form is +Next, set it as the <code>GOPATH</code>. You should also add the +<code>bin</code> subdirectory to your <code>PATH</code> environment variable so +that you can run the commands therein without specifying their full path. +To do this, add the following lines to <code>$HOME/.profile</code> (or +equivalent): </p> <pre> -include $(GOROOT)/src/Make.inc +export GOPATH=$HOME/mygo +export PATH=$PATH:$HOME/mygo/bin +</pre> -TARG=mypackage -GOFILES=\ - my1.go\ - my2.go\ -include $(GOROOT)/src/Make.pkg -</pre> +<h3>Import paths</h3> <p> -The first and last lines <code>include</code> standard definitions and rules. -Packages maintained in the standard Go tree use a relative path (instead of -<code>$(GOROOT)/src</code>) so that <code>make</code> will work correctly -even if <code>$(GOROOT)</code> contains spaces. -This makes it easy for programmers to try Go. +The standard packages are given short import paths such as <code>"fmt"</code> +and <code>"net/http"</code> for convenience. +For your own projects, it is important to choose a base import path that is +unlikely to collide with future additions to the standard library or other +external libraries. </p> <p> -If you have not set <code>$GOROOT</code> in your environment, -you must run <code>gomake</code> to use this form of makefile. -<code>Gomake</code> also takes care to invoke GNU Make -even on systems where it is installed as <code>gmake</code> -rather than <code>make</code>. +The best way to choose an import path is to use the location of your version +control repository. +For instance, if your source repository is at <code>example.com</code> +or <code>code.google.com/p/example</code>, you should begin your package +paths with that URL, as in "<code>example.com/foo/bar</code>" or +"<code>code.google.com/p/example/foo/bar</code>". +Using this convention, the <code>go</code> command can automatically check out and +build the source code by its import path alone. </p> <p> -<code>TARG</code> is the target install path for the package, -the string that clients will use to import it. -Inside the Go tree, this string should be the same as the directory -in which the <code>Makefile</code> appears, with the -<code>$GOROOT/src/pkg/</code> prefix removed. -Outside the Go tree, you can use any <code>TARG</code> you -want that doesn't conflict with the standard Go package names. -A common convention is to use an identifying top-level name -to group your packages: <code>myname/tree</code>, <code>myname/filter</code>, etc. -Note that even if you keep your package source outside the -Go tree, running <code>make install</code> installs your -package binaries in the standard location—<code>$GOROOT/pkg</code>—to -make it easy to find them. +If you don't intend to install your code in this way, you should at +least use a unique prefix like "<code>widgets/</code>", as in +"<code>widgets/foo/bar</code>". A good rule is to use a prefix such as your +company or project name, since it is unlikely to be used by another group. </p> <p> -<code>GOFILES</code> is a list of source files to compile to -create the package. The trailing <code>\</code> characters -allow the list to be split onto multiple lines -for easy sorting. +We'll use <code>example/</code> as our base import path: </p> -<p> -If you create a new package directory in the Go tree, add it to the list in -<code>$GOROOT/src/pkg/Makefile</code> so that it -is included in the standard build. Then run: <pre> -cd $GOROOT/src/pkg -./deps.bash +$ mkdir -p $GOPATH/src/example </pre> -<p> -to update the dependency file <code>Make.deps</code>. -(This happens automatically each time you run <code>all.bash</code> -or <code>make.bash</code>.) -</p> + + +<h3>Package names</h3> <p> -If you change the imports of an existing package, -you do not need to edit <code>$GOROOT/src/pkg/Makefile</code> -but you will still need to run <code>deps.bash</code> as above. +The first statement in a Go source file should be </p> - -<h3>Go source files</h3> +<pre> +package <i>name</i> +</pre> <p> -The first statement in each of the source files listed in the <code>Makefile</code> -should be <code>package <i>name</i></code>, where <code><i>name</i></code> -is the package's default name for imports. +where <code><i>name</i></code> is the package's default name for imports. (All files in a package must use the same <code><i>name</i></code>.) +</p> + +<p> Go's convention is that the package name is the last element of the -import path: the package imported as <code>"crypto/rot13"</code> +import path: the package imported as "<code>crypto/rot13</code>" should be named <code>rot13</code>. There is no requirement that package names be unique across all packages linked into a single binary, @@ -166,203 +160,344 @@ only that the import paths (their full file names) be unique. </p> <p> -Go compiles all the source files in a package at once, so one file -can refer to constants, variables, types, and functions in another -file without special arrangement or declarations. +Create a new package under <code>example</code> called <code>newmath</code>: </p> +<pre> +$ cd $GOPATH/src/example +$ mkdir newmath +</pre> + <p> -Writing clean, idiomatic Go code is beyond the scope of this document. -<a href="effective_go.html">Effective Go</a> is an introduction to -that topic. +Then create a file named <code>$GOPATH/src/example/newmath/sqrt.go</code> +containing the following Go code: </p> -<h2 id="Building_programs">Building programs</h2> -<p>To build a Go program with gomake, create a Makefile alongside your program's -source files. It should be similar to the example above, but include -<code>Make.cmd</code> instead of <code>Make.pkg</code>: - <pre> -include $(GOROOT)/src/Make.inc +// Package newmath is a trivial example package. +package newmath + +// Sqrt returns an approximation to the square root of x. +func Sqrt(x float64) float64 { + // This is a terrible implementation. + // Real code should import "math" and use math.Sqrt. + z := 0.0 + for i := 0; i < 1000; i++ { + z -= (z*z - x) / (2 * x) + } + return z +} +</pre> -TARG=helloworld -GOFILES=\ - helloworld.go\ +<p> +This package is imported by the path name of the directory it's in, starting +after the <code>src</code> component: +</p> -include $(GOROOT)/src/Make.cmd +<pre> +import "example/newmath" </pre> -<p>Running <code>gomake</code> will compile <code>helloworld.go</code> -and produce an executable named <code>helloworld</code> in the current -directory. +<p> +See <a href="/doc/effective_go.html#names">Effective Go</a> to learn more about +Go's naming conventions. </p> + +<h2>Building and installing</h2> + <p> -Running <code>gomake install</code> will build <code>helloworld</code> if -necessary and copy it to the <code>$GOBIN</code> directory -(<code>$GOROOT/bin/</code> is the default). +The <code>go</code> command comprises several subcommands, the most central being +<code>install</code>. Running <code>go install <i>importpath</i></code> builds +and installs a package and its dependencies. </p> -<h2 id="Testing">Testing</h2> - <p> -Go has a lightweight test framework known as <code>gotest</code>. -You write a test by creating a file with a name ending in <code>_test.go</code> -that contains functions named <code>TestXXX</code> with signature <code>func (t *testing.T)</code>. -The test framework runs each such function; -if the function calls a failure function such as <code>t.Error</code> or <code>t.Fail</code>, the test is considered to have failed. -The <a href="/cmd/gotest/">gotest command documentation</a> -and the <a href="/pkg/testing/">testing package documentation</a> give more detail. +To "install a package" means to write the package object or executable command +to the <code>pkg</code> or <code>bin</code> subdirectory of the workspace in +which the source resides. </p> +<h3>Building a package</h3> + <p> -The <code>*_test.go</code> files should not be listed in the <code>Makefile</code>. +To build and install the <code>newmath</code> package, type </p> +<pre> +$ go install example/newmath +</pre> + <p> -To run the test, run either <code>make test</code> or <code>gotest</code> -(they are equivalent). -To run only the tests in a single test file, for instance <code>one_test.go</code>, -run <code>gotest one_test.go</code>. +This command will produce no output if the package and its dependencies +are built and installed correctly. </p> <p> -If your change affects performance, add a <code>Benchmark</code> function -(see the <a href="/cmd/gotest/">gotest command documentation</a>) -and run it using <code>gotest -test.bench=.</code>. +As a convenience, the <code>go</code> command will assume the current directory +if no import path is specified on the command line. This sequence of commands +has the same affect as the one above: </p> +<pre> +$ cd $GOPATH/src/example/newmath +$ go install +</pre> + <p> -Once your new code is tested and working, -it's time to get it <a href="contribute.html">reviewed and submitted</a>. +The resulting workspace directory tree (assuming we're running Linux on a 64-bit +system) looks like this: </p> -<h2 id="pkg_example">An example package with tests</h2> +<pre> +pkg/ + linux_amd64/ + example/ + newmath.a # package object +src/ + example/ + newmath/ + sqrt.go # package source +</pre> + + +<h3>Building a command</h3> <p> -This example package, <code>numbers</code>, consists of the function -<code>Double</code>, which takes an <code>int</code> and returns that value -multiplied by 2. It consists of three files. +The <code>go</code> command treats code belonging to <code>package main</code> as +an executable command and installs the package binary to the +<code>GOPATH</code>'s <code>bin</code> subdirectory. </p> <p> -First, the package implementation, <code>numbers.go</code>: +Add a command named <code>hello</code> to the source tree. +First create the <code>example/hello</code> directory: </p> <pre> -package numbers - -func Double(i int) int { - return i * 2 -} +$ cd $GOPATH/src/example +$ mkdir hello </pre> <p> -Next, the tests, <code>numbers_test.go</code>: +Then create the file <code>$GOPATH/src/example/hello/hello.go</code> +containing the following Go code. </p> <pre> -package numbers +// Hello is a trivial example of a main package. +package main import ( - "testing" + "example/newmath" + "fmt" ) -type doubleTest struct { - in, out int +func main() { + fmt.Printf("Hello, world. Sqrt(2) = %v\n", newmath.Sqrt(2)) } +</pre> -var doubleTests = []doubleTest{ - doubleTest{1, 2}, - doubleTest{2, 4}, - doubleTest{-5, -10}, -} +<p> +Next, run <code>go install</code>, which builds and installs the binary to +<code>$GOPATH/bin</code>: +</p> -func TestDouble(t *testing.T) { - for _, dt := range doubleTests { - v := Double(dt.in) - if v != dt.out { - t.Errorf("Double(%d) = %d, want %d.", dt.in, v, dt.out) - } - } -} +<pre> +$ go install example/hello </pre> <p> -Finally, the <code>Makefile</code>: +To run the program, invoke it by name as you would any other command: </p> <pre> -include $(GOROOT)/src/Make.inc +$ $GOPATH/bin/hello +Hello, world. Sqrt(2) = 1.414213562373095 +</pre> -TARG=numbers -GOFILES=\ - numbers.go\ +<p> +If you added <code>$HOME/mygo/bin</code> to your <code>PATH</code>, you may omit +the path to the executable: +</p> -include $(GOROOT)/src/Make.pkg +<pre> +$ hello +Hello, world. Sqrt(2) = 1.414213562373095 </pre> <p> -Running <code>gomake install</code> will build and install the package to -the <code>$GOROOT/pkg/</code> directory (it can then be used by any -program on the system). +The workspace directory tree now looks like this: +</p> + +<pre> +bin/ + hello # command executable +pkg/ + linux_amd64/ + example/ + newmath.a # package object +src/ + example/ + hello/ + hello.go # command source + newmath/ + sqrt.go # package source +</pre> + +<p> +The <code>go</code> command also provides a <code>build</code> command, which is +like <code>install</code> except it builds all objects in a temporary directory +and does not install them under <code>pkg</code> or <code>bin</code>. +When building a command an executable named after the last element of the +import path is written to the current directory. When building a package, +<code>go build</code> serves merely to test that the package and its +dependencies can be built. (The resulting package object is thrown away.) +</p> + + +<h2 id="Testing">Testing</h2> + +<p> +Go has a lightweight test framework composed of the <code>go test</code> +command and the <code>testing</code> package. </p> <p> -Running <code>gomake test</code> (or just running the command -<code>gotest</code>) will rebuild the package, including the -<code>numbers_test.go</code> file, and then run the <code>TestDouble</code> -function. The output "<code>PASS</code>" indicates that all tests passed -successfully. Breaking the implementation by changing the multiplier from -<code>2</code> to <code>3</code> will allow you to see how failing tests are -reported. +You write a test by creating a file with a name ending in <code>_test.go</code> +that contains functions named <code>TestXXX</code> with signature +<code>func (t *testing.T)</code>. +The test framework runs each such function; +if the function calls a failure function such as <code>t.Error</code> or +<code>t.Fail</code>, the test is considered to have failed. </p> <p> -See the <a href="/cmd/gotest/">gotest documentation</a> and the -<a href="/pkg/testing/">testing package</a> for more detail. +Add a test to the <code>newmath</code> package by creating the file +<code>$GOPATH/src/example/newmath/sqrt_test.go</code> containing the following +Go code. </p> -<h2 id="arch_os_specific">Architecture- and operating system-specific code</h2> +<pre> +package newmath -<p>First, a disclaimer: very few Go packages should need to know about the -hardware and operating system they run on. In the vast majority of cases the -language and standard library handle most portability issues. This section is -a guide for experienced systems programmers who have a good reason to write -platform-specific code, such as assembly-language support for fast -trigonometric functions or code that implements a common interface above -different operating systems.</p> +import "testing" -<p>To compile such code, use the <code>$GOOS</code> and <code>$GOARCH</code> -<a href="/doc/install.html#environment">environment variables</a> in your -source file names and <code>Makefile</code>.</p> +func TestSqrt(t *testing.T) { + const in, out = 9, 3 + if x := Sqrt(in); x != out { + t.Errorf("Sqrt(%v) = %v, want %v", in, x, out) + } +} +</pre> -<p>For example, this <code>Makefile</code> describes a package that builds on -different operating systems by parameterizing the file name with -<code>$GOOS</code>.</p> +<p> +Now run the test with <code>go test</code>: +</p> <pre> -include $(GOROOT)/src/Make.inc +$ go test example/newmath +ok example/newmath +</pre> + +<p> +Run <code><a href="/cmd/go/#Test_packages">go help test</a></code> and see the +<a href="/pkg/testing/">testing package documentation</a> for more detail. +</p> + -TARG=mypackage -GOFILES=\ - my.go\ - my_$(GOOS).go\ +<h2 id="remote">Remote packages</h2> -include $(GOROOT)/src/Make.pkg +<p> +An import path can describe how to obtain the package source code using a +revision control system such as Git or Mercurial. The <code>go</code> command uses +this property to automatically fetch packages from remote repositories. +For instance, the examples described in this document are also kept in a +Mercurial repository hosted at Google Code, +<code><a href="http://code.google.com/p/go.example">code.google.com/p/go.example</a></code>. +If you include the repository URL in the package's import path, +<code>go get</code> will fetch, build, and install it automatically: +</p> + +<pre> +$ go get code.google.com/p/go.example/hello +$ $GOPATH/bin/hello +Hello, world. Sqrt(2) = 1.414213562373095 </pre> -<p>The OS-specific code goes in <code>my_linux.go</code>, -<code>my_darwin.go</code>, and so on.</p> +<p> +If the specified package is not present in a workspace, <code>go get</code> +will place it inside the first workspace specified by <code>GOPATH</code>. +(If the package does already exist, <code>go get</code> skips the remote +fetch and behaves the same as <code>go install</code>.) +</p> -<p>If you follow these conventional parameterizations, tools such as -<a href="/cmd/goinstall/">goinstall</a> will work seamlessly with your package: +<p> +After issuing the above <code>go get</code> command, the workspace directory +tree should now now look like this: </p> <pre> -my_$(GOOS).go -my_$(GOARCH).go -my_$(GOOS)_$(GOARCH).go +bin/ + hello # command executable +pkg/ + linux_amd64/ + code.google.com/p/go.example/ + newmath.a # package object + example/ + newmath.a # package object +src/ + code.google.com/p/go.example/ + hello/ + hello.go # command source + newmath/ + sqrt.go # package source + sqrt_test.go # test source + example/ + hello/ + hello.go # command source + newmath/ + sqrt.go # package source + sqrt_test.go # test source </pre> -<p>The same holds for <code>.s</code> (assembly) files.</p> +<p> +The <code>hello</code> command hosted at Google Code depends on the +<code>newmath</code> package within the same repository. The imports in +<code>hello.go</code> file use the same import path convention, so the <code>go +get</code> command is able to locate and install the dependent package, too. +</p> + +<pre> +import "code.google.com/p/go.example/newmath" +</pre> + +<p> +This convention is the easiest way to make your Go packages available for +others to use. +The <a href="http://godashboard.appspot.com/package">Go Package Dashboard</a> +displays a list of packages recently installed with the <code>go</code> command. +</p> + +<p> +For more information on using remote repositories with the <code>go</code> command, see +<code><a href="/cmd/go/#Remote_import_path_syntax">go help remote</a></code>. +</p> + + +<h2 id="more">Further reading</h2> + +<p> +See <a href="/doc/effective_go.html">Effective Go</a> for tips on writing +clear, idiomatic Go code. +</p> + +<p> +Take <a href="http://tour.golang.org/">A Tour of Go</a> to learn the language +proper. +</p> + +<p> +Visit the <a href="/doc/#articles">documentation page</a> for a set of in-depth +articles about the Go language and its libraries and tools. +</p> diff --git a/doc/codelab/wiki/htmlify.go b/doc/codelab/wiki/htmlify.go deleted file mode 100644 index 9e7605b92..000000000 --- a/doc/codelab/wiki/htmlify.go +++ /dev/null @@ -1,12 +0,0 @@ -package main - -import ( - "template" - "os" - "io/ioutil" -) - -func main() { - b, _ := ioutil.ReadAll(os.Stdin) - template.HTMLEscape(os.Stdout, b) -} diff --git a/doc/codelab/wiki/index.html b/doc/codelab/wiki/index.html deleted file mode 100644 index 50e9db5e9..000000000 --- a/doc/codelab/wiki/index.html +++ /dev/null @@ -1,1007 +0,0 @@ -<!-- Codelab: Writing Web Applications --> -<h2>Introduction</h2> - -<p> -Covered in this codelab: -</p> -<ul> -<li>Creating a data structure with load and save methods</li> -<li>Using the <code>http</code> package to build web applications -<li>Using the <code>template</code> package to process HTML templates</li> -<li>Using the <code>regexp</code> package to validate user input</li> -<li>Using closures</li> -</ul> - -<p> -Assumed knowledge: -</p> -<ul> -<li>Programming experience</li> -<li>Understanding of basic web technologies (HTTP, HTML)</li> -<li>Some UNIX command-line knowledge</li> -</ul> - -<h2>Getting Started</h2> - -<p> -At present, you need to have a Linux, OS X, or FreeBSD machine to run Go. If -you don't have access to one, you could set up a Linux Virtual Machine (using -<a href="http://www.virtualbox.org/">VirtualBox</a> or similar) or a -<a href="http://www.google.com/search?q=virtual+private+server">Virtual -Private Server</a>. -</p> - -<p> -Install Go (see the <a href="http://golang.org/doc/install.html">Installation Instructions</a>). -</p> - -<p> -Make a new directory for this codelab and cd to it: -</p> - -<pre> -$ mkdir ~/gowiki -$ cd ~/gowiki -</pre> - -<p> -Create a file named <code>wiki.go</code>, open it in your favorite editor, and -add the following lines: -</p> - -<pre> -package main - -import ( - "fmt" - "io/ioutil" - "os" -) -</pre> - -<p> -We import the <code>fmt</code>, <code>ioutil</code> and <code>os</code> -packages from the Go standard library. Later, as we implement additional -functionality, we will add more packages to this <code>import</code> -declaration. -</p> - -<h2>Data Structures</h2> - -<p> -Let's start by defining the data structures. A wiki consists of a series of -interconnected pages, each of which has a title and a body (the page content). -Here, we define <code>Page</code> as a struct with two fields representing -the title and body. -</p> - -<pre> -type Page struct { - Title string - Body []byte -} -</pre> - -<p> -The type <code>[]byte</code> means "a <code>byte</code> slice". -(See <a href="http://golang.org/doc/effective_go.html#slices">Effective Go</a> -for more on slices.) -The <code>Body</code> element is a <code>[]byte</code> rather than -<code>string</code> because that is the type expected by the <code>io</code> -libraries we will use, as you'll see below. -</p> - -<p> -The <code>Page</code> struct describes how page data will be stored in memory. -But what about persistent storage? We can address that by creating a -<code>save</code> method on <code>Page</code>: -</p> - -<pre> -func (p *Page) save() os.Error { - filename := p.Title + ".txt" - return ioutil.WriteFile(filename, p.Body, 0600) -} -</pre> - -<p> -This method's signature reads: "This is a method named <code>save</code> that -takes as its receiver <code>p</code>, a pointer to <code>Page</code> . It takes -no parameters, and returns a value of type <code>os.Error</code>." -</p> - -<p> -This method will save the <code>Page</code>'s <code>Body</code> to a text -file. For simplicity, we will use the <code>Title</code> as the file name. -</p> - -<p> -The <code>save</code> method returns an <code>os.Error</code> value because -that is the return type of <code>WriteFile</code> (a standard library function -that writes a byte slice to a file). The <code>save</code> method returns the -error value, to let the application handle it should anything go wrong while -writing the file. If all goes well, <code>Page.save()</code> will return -<code>nil</code> (the zero-value for pointers, interfaces, and some other -types). -</p> - -<p> -The octal integer constant <code>0600</code>, passed as the third parameter to -<code>WriteFile</code>, indicates that the file should be created with -read-write permissions for the current user only. (See the Unix man page -<code>open(2)</code> for details.) -</p> - -<p> -We will want to load pages, too: -</p> - -<pre> -func loadPage(title string) *Page { - filename := title + ".txt" - body, _ := ioutil.ReadFile(filename) - return &Page{Title: title, Body: body} -} -</pre> - -<p> -The function <code>loadPage</code> constructs the file name from -<code>Title</code>, reads the file's contents into a new -<code>Page</code>, and returns a pointer to that new <code>page</code>. -</p> - -<p> -Functions can return multiple values. The standard library function -<code>io.ReadFile</code> returns <code>[]byte</code> and <code>os.Error</code>. -In <code>loadPage</code>, error isn't being handled yet; the "blank identifier" -represented by the underscore (<code>_</code>) symbol is used to throw away the -error return value (in essence, assigning the value to nothing). -</p> - -<p> -But what happens if <code>ReadFile</code> encounters an error? For example, -the file might not exist. We should not ignore such errors. Let's modify the -function to return <code>*Page</code> and <code>os.Error</code>. -</p> - -<pre> -func loadPage(title string) (*Page, os.Error) { - filename := title + ".txt" - body, err := ioutil.ReadFile(filename) - if err != nil { - return nil, err - } - return &Page{Title: title, Body: body}, nil -} -</pre> - -<p> -Callers of this function can now check the second parameter; if it is -<code>nil</code> then it has successfully loaded a Page. If not, it will be an -<code>os.Error</code> that can be handled by the caller (see the <a -href="http://golang.org/pkg/os/#Error">os package documentation</a> for -details). -</p> - -<p> -At this point we have a simple data structure and the ability to save to and -load from a file. Let's write a <code>main</code> function to test what we've -written: -</p> - -<pre> -func main() { - p1 := &Page{Title: "TestPage", Body: []byte("This is a sample Page.")} - p1.save() - p2, _ := loadPage("TestPage") - fmt.Println(string(p2.Body)) -} -</pre> - -<p> -After compiling and executing this code, a file named <code>TestPage.txt</code> -would be created, containing the contents of <code>p1</code>. The file would -then be read into the struct <code>p2</code>, and its <code>Body</code> element -printed to the screen. -</p> - -<p> -You can compile and run the program like this: -</p> - -<pre> -$ 8g wiki.go -$ 8l wiki.8 -$ ./8.out -This is a sample page. -</pre> - -<p> -(The <code>8g</code> and <code>8l</code> commands are applicable to -<code>GOARCH=386</code>. If you're on an <code>amd64</code> system, -substitute 6's for the 8's.) -</p> - -<p> -<a href="part1.go">Click here to view the code we've written so far.</a> -</p> - -<h2>Introducing the <code>http</code> package (an interlude)</h2> - -<p> -Here's a full working example of a simple web server: -</p> - -<pre> -package main - -import ( - "fmt" - "http" -) - -func handler(w http.ResponseWriter, r *http.Request) { - fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:]) -} - -func main() { - http.HandleFunc("/", handler) - http.ListenAndServe(":8080", nil) -} -</pre> - -<p> -The <code>main</code> function begins with a call to -<code>http.HandleFunc</code>, which tells the <code>http</code> package to -handle all requests to the web root (<code>"/"</code>) with -<code>handler</code>. -</p> - -<p> -It then calls <code>http.ListenAndServe</code>, specifying that it should -listen on port 8080 on any interface (<code>":8080"</code>). (Don't -worry about its second parameter, <code>nil</code>, for now.) -This function will block until the program is terminated. -</p> - -<p> -The function <code>handler</code> is of the type <code>http.HandlerFunc</code>. -It takes an <code>http.ResponseWriter</code> and an <code>http.Request</code> as -its arguments. -</p> - -<p> -An <code>http.ResponseWriter</code> value assembles the HTTP server's response; by writing -to it, we send data to the HTTP client. -</p> - -<p> -An <code>http.Request</code> is a data structure that represents the client -HTTP request. The string <code>r.URL.Path</code> is the path component -of the request URL. The trailing <code>[1:]</code> means -"create a sub-slice of <code>Path</code> from the 1st character to the end." -This drops the leading "/" from the path name. -</p> - -<p> -If you run this program and access the URL: -</p> -<pre>http://localhost:8080/monkeys</pre> -<p> -the program would present a page containing: -</p> -<pre>Hi there, I love monkeys!</pre> - -<h2>Using <code>http</code> to serve wiki pages</h2> - -<p> -To use the <code>http</code> package, it must be imported: -</p> - -<pre> -import ( - "fmt" - <b>"http"</b> - "io/ioutil" - "os" -) -</pre> - -<p> -Let's create a handler to view a wiki page: -</p> - -<pre> -const lenPath = len("/view/") - -func viewHandler(w http.ResponseWriter, r *http.Request) { - title := r.URL.Path[lenPath:] - p, _ := loadPage(title) - fmt.Fprintf(w, "<h1>%s</h1><div>%s</div>", p.Title, p.Body) -} -</pre> - -<p> -First, this function extracts the page title from <code>r.URL.Path</code>, -the path component of the request URL. The global constant -<code>lenPath</code> is the length of the leading <code>"/view/"</code> -component of the request path. -The <code>Path</code> is re-sliced with <code>[lenPath:]</code> to drop the -first 6 characters of the string. This is because the path will invariably -begin with <code>"/view/"</code>, which is not part of the page title. -</p> - -<p> -The function then loads the page data, formats the page with a string of simple -HTML, and writes it to <code>w</code>, the <code>http.ResponseWriter</code>. -</p> - -<p> -Again, note the use of <code>_</code> to ignore the <code>os.Error</code> -return value from <code>loadPage</code>. This is done here for simplicity -and generally considered bad practice. We will attend to this later. -</p> - -<p> -To use this handler, we create a <code>main</code> function that -initializes <code>http</code> using the <code>viewHandler</code> to handle -any requests under the path <code>/view/</code>. -</p> - -<pre> -func main() { - http.HandleFunc("/view/", viewHandler) - http.ListenAndServe(":8080", nil) -} -</pre> - -<p> -<a href="part2.go">Click here to view the code we've written so far.</a> -</p> - -<p> -Let's create some page data (as <code>test.txt</code>), compile our code, and -try serving a wiki page: -</p> - -<pre> -$ echo "Hello world" > test.txt -$ 8g wiki.go -$ 8l wiki.8 -$ ./8.out -</pre> - -<p> -With this web server running, a visit to <code><a -href="http://localhost:8080/view/test">http://localhost:8080/view/test</a></code> -should show a page titled "test" containing the words "Hello world". -</p> - -<h2>Editing Pages</h2> - -<p> -A wiki is not a wiki without the ability to edit pages. Let's create two new -handlers: one named <code>editHandler</code> to display an 'edit page' form, -and the other named <code>saveHandler</code> to save the data entered via the -form. -</p> - -<p> -First, we add them to <code>main()</code>: -</p> - -<pre> -func main() { - http.HandleFunc("/view/", viewHandler) - http.HandleFunc("/edit/", editHandler) - http.HandleFunc("/save/", saveHandler) - http.ListenAndServe(":8080", nil) -} -</pre> - -<p> -The function <code>editHandler</code> loads the page -(or, if it doesn't exist, create an empty <code>Page</code> struct), -and displays an HTML form. -</p> - -<pre> -func editHandler(w http.ResponseWriter, r *http.Request) { - title := r.URL.Path[lenPath:] - p, err := loadPage(title) - if err != nil { - p = &Page{Title: title} - } - fmt.Fprintf(w, "<h1>Editing %s</h1>"+ - "<form action=\"/save/%s\" method=\"POST\">"+ - "<textarea name=\"body\">%s</textarea><br>"+ - "<input type=\"submit\" value=\"Save\">"+ - "</form>", - p.Title, p.Title, p.Body) -} -</pre> - -<p> -This function will work fine, but all that hard-coded HTML is ugly. -Of course, there is a better way. -</p> - -<h2>The <code>template</code> package</h2> - -<p> -The <code>template</code> package is part of the Go standard library. -(A new template package is coming; this code lab will be updated soon.) -We can -use <code>template</code> to keep the HTML in a separate file, allowing -us to change the layout of our edit page without modifying the underlying Go -code. -</p> - -<p> -First, we must add <code>template</code> to the list of imports: -</p> - -<pre> -import ( - "http" - "io/ioutil" - "os" - <b>"template"</b> -) -</pre> - -<p> -Let's create a template file containing the HTML form. -Open a new file named <code>edit.html</code>, and add the following lines: -</p> - -<pre> -<h1>Editing {{.Title |html}}</h1> - -<form action="/save/{{.Title |html}}" method="POST"> -<div><textarea name="body" rows="20" cols="80">{{printf "%s" .Body |html}}</textarea></div> -<div><input type="submit" value="Save"></div> -</form> -</pre> - -<p> -Modify <code>editHandler</code> to use the template, instead of the hard-coded -HTML: -</p> - -<pre> -func editHandler(w http.ResponseWriter, r *http.Request) { - title := r.URL.Path[lenPath:] - p, err := loadPage(title) - if err != nil { - p = &Page{Title: title} - } - t, _ := template.ParseFile("edit.html") - t.Execute(w, p) -} -</pre> - -<p> -The function <code>template.ParseFile</code> will read the contents of -<code>edit.html</code> and return a <code>*template.Template</code>. -</p> - -<p> -The method <code>t.Execute</code> executes the template, writing the -generated HTML to the <code>http.ResponseWriter</code>. -The <code>.Title</code> and <code>.Body</code> dotted identifiers refer to -<code>p.Title</code> and <code>p.Body</code>. -</p> - -<p> -Template directives are enclosed in double curly braces. -The <code>printf "%s" .Body</code> instruction is a function call -that outputs <code>.Body</code> as a string instead of a stream of bytes, -the same as a call to <code>fmt.Printf</code>. -The <code>|html</code> part of each directive pipes the value through the -<code>html</code> formatter before outputting it, which escapes HTML -characters (such as replacing <code>></code> with <code>&gt;</code>), -preventing user data from corrupting the form HTML. -</p> - -<p> -Now that we've removed the <code>fmt.Fprintf</code> statement, we can remove -<code>"fmt"</code> from the <code>import</code> list. -</p> - -<p> -While we're working with templates, let's create a template for our -<code>viewHandler</code> called <code>view.html</code>: -</p> - -<pre> -<h1>{{.Title |html}}</h1> - -<p>[<a href="/edit/{{.Title |html}}">edit</a>]</p> - -<div>{{printf "%s" .Body |html}}</div> -</pre> - -<p> -Modify <code>viewHandler</code> accordingly: -</p> - -<pre> -func viewHandler(w http.ResponseWriter, r *http.Request) { - title := r.URL.Path[lenPath:] - p, _ := loadPage(title) - t, _ := template.ParseFile("view.html") - t.Execute(w, p) -} -</pre> - -<p> -Notice that we've used almost exactly the same templating code in both -handlers. Let's remove this duplication by moving the templating code -to its own function: -</p> - -<pre> -func viewHandler(w http.ResponseWriter, r *http.Request) { - title := r.URL.Path[lenPath:] - p, _ := loadPage(title) - renderTemplate(w, "view", p) -} - -func editHandler(w http.ResponseWriter, r *http.Request) { - title := r.URL.Path[lenPath:] - p, err := loadPage(title) - if err != nil { - p = &Page{Title: title} - } - renderTemplate(w, "edit", p) -} - -func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) { - t, _ := template.ParseFile(tmpl+".html", nil) - t.Execute(w, p) -} -</pre> - -<p> -The handlers are now shorter and simpler. -</p> - -<h2>Handling non-existent pages</h2> - -<p> -What if you visit <code>/view/APageThatDoesntExist</code>? The program will -crash. This is because it ignores the error return value from -<code>loadPage</code>. Instead, if the requested Page doesn't exist, it should -redirect the client to the edit Page so the content may be created: -</p> - -<pre> -func viewHandler(w http.ResponseWriter, r *http.Request) { - title, err := getTitle(w, r) - if err != nil { - return - } - p, err := loadPage(title) - if err != nil { - http.Redirect(w, r, "/edit/"+title, http.StatusFound) - return - } - renderTemplate(w, "view", p) -} -</pre> - -<p> -The <code>http.Redirect</code> function adds an HTTP status code of -<code>http.StatusFound</code> (302) and a <code>Location</code> -header to the HTTP response. -</p> - -<h2>Saving Pages</h2> - -<p> -The function <code>saveHandler</code> will handle the form submission. -</p> - -<pre> -func saveHandler(w http.ResponseWriter, r *http.Request) { - title := r.URL.Path[lenPath:] - body := r.FormValue("body") - p := &Page{Title: title, Body: []byte(body)} - p.save() - http.Redirect(w, r, "/view/"+title, http.StatusFound) -} -</pre> - -<p> -The page title (provided in the URL) and the form's only field, -<code>Body</code>, are stored in a new <code>Page</code>. -The <code>save()</code> method is then called to write the data to a file, -and the client is redirected to the <code>/view/</code> page. -</p> - -<p> -The value returned by <code>FormValue</code> is of type <code>string</code>. -We must convert that value to <code>[]byte</code> before it will fit into -the <code>Page</code> struct. We use <code>[]byte(body)</code> to perform -the conversion. -</p> - -<h2>Error handling</h2> - -<p> -There are several places in our program where errors are being ignored. This -is bad practice, not least because when an error does occur the program will -crash. A better solution is to handle the errors and return an error message -to the user. That way if something does go wrong, the server will continue to -function and the user will be notified. -</p> - -<p> -First, let's handle the errors in <code>renderTemplate</code>: -</p> - -<pre> -func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) { - t, err := template.ParseFile(tmpl+".html", nil) - if err != nil { - http.Error(w, err.String(), http.StatusInternalServerError) - return - } - err = t.Execute(w, p) - if err != nil { - http.Error(w, err.String(), http.StatusInternalServerError) - } -} -</pre> - -<p> -The <code>http.Error</code> function sends a specified HTTP response code -(in this case "Internal Server Error") and error message. -Already the decision to put this in a separate function is paying off. -</p> - -<p> -Now let's fix up <code>saveHandler</code>: -</p> - -<pre> -func saveHandler(w http.ResponseWriter, r *http.Request) { - title, err := getTitle(w, r) - if err != nil { - return - } - body := r.FormValue("body") - p := &Page{Title: title, Body: []byte(body)} - err = p.save() - if err != nil { - http.Error(w, err.String(), http.StatusInternalServerError) - return - } - http.Redirect(w, r, "/view/"+title, http.StatusFound) -} -</pre> - -<p> -Any errors that occur during <code>p.save()</code> will be reported -to the user. -</p> - -<h2>Template caching</h2> - -<p> -There is an inefficiency in this code: <code>renderTemplate</code> calls -<code>ParseFile</code> every time a page is rendered. -A better approach would be to call <code>ParseFile</code> once for each -template at program initialization, and store the resultant -<code>*Template</code> values in a data structure for later use. -</p> - -<p> -First we create a global map named <code>templates</code> in which to store -our <code>*Template</code> values, keyed by <code>string</code> -(the template name): -</p> - -<pre> -var templates = make(map[string]*template.Template) -</pre> - -<p> -Then we create an <code>init</code> function, which will be called before -<code>main</code> at program initialization. The function -<code>template.Must</code> is a convenience wrapper that panics when passed a -non-nil <code>os.Error</code> value, and otherwise returns the -<code>*Template</code> unaltered. A panic is appropriate here; if the templates -can't be loaded the only sensible thing to do is exit the program. -</p> - -<pre> -func init() { - for _, tmpl := range []string{"edit", "view"} { - t := template.Must(template.ParseFile(tmpl + ".html")) - templates[tmpl] = t - } -} -</pre> - -<p> -A <code>for</code> loop is used with a <code>range</code> statement to iterate -over an array constant containing the names of the templates we want parsed. -If we were to add more templates to our program, we would add their names to -that array. -</p> - -<p> -We then modify our <code>renderTemplate</code> function to call -the <code>Execute</code> method on the appropriate <code>Template</code> from -<code>templates</code>: - -<pre> -func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) { - err := templates[tmpl].Execute(w, p) - if err != nil { - http.Error(w, err.String(), http.StatusInternalServerError) - } -} -</pre> - -<h2>Validation</h2> - -<p> -As you may have observed, this program has a serious security flaw: a user -can supply an arbitrary path to be read/written on the server. To mitigate -this, we can write a function to validate the title with a regular expression. -</p> - -<p> -First, add <code>"regexp"</code> to the <code>import</code> list. -Then we can create a global variable to store our validation regexp: -</p> - -<pre> -var titleValidator = regexp.MustCompile("^[a-zA-Z0-9]+$") -</pre> - -<p> -The function <code>regexp.MustCompile</code> will parse and compile the -regular expression, and return a <code>regexp.Regexp</code>. -<code>MustCompile</code> is distinct from <code>Compile</code> in that it will -panic if the expression compilation fails, while <code>Compile</code> returns -an <code>os.Error</code> as a second parameter. -</p> - -<p> -Now, let's write a function that extracts the title string from the request -URL, and tests it against our <code>TitleValidator</code> expression: -</p> - -<pre> -func getTitle(w http.ResponseWriter, r *http.Request) (title string, err os.Error) { - title = r.URL.Path[lenPath:] - if !titleValidator.MatchString(title) { - http.NotFound(w, r) - err = os.NewError("Invalid Page Title") - } - return -} -</pre> - -<p> -If the title is valid, it will be returned along with a <code>nil</code> -error value. If the title is invalid, the function will write a -"404 Not Found" error to the HTTP connection, and return an error to the -handler. -</p> - -<p> -Let's put a call to <code>getTitle</code> in each of the handlers: -</p> - -<pre> -func viewHandler(w http.ResponseWriter, r *http.Request) { - title, err := getTitle(w, r) - if err != nil { - return - } - p, err := loadPage(title) - if err != nil { - http.Redirect(w, r, "/edit/"+title, http.StatusFound) - return - } - renderTemplate(w, "view", p) -} - -func editHandler(w http.ResponseWriter, r *http.Request) { - title, err := getTitle(w, r) - if err != nil { - return - } - p, err := loadPage(title) - if err != nil { - p = &Page{Title: title} - } - renderTemplate(w, "edit", p) -} - -func saveHandler(w http.ResponseWriter, r *http.Request) { - title, err := getTitle(w, r) - if err != nil { - return - } - body := r.FormValue("body") - p := &Page{Title: title, Body: []byte(body)} - err = p.save() - if err != nil { - http.Error(w, err.String(), http.StatusInternalServerError) - return - } - http.Redirect(w, r, "/view/"+title, http.StatusFound) -} -</pre> - -<h2>Introducing Function Literals and Closures</h2> - -<p> -Catching the error condition in each handler introduces a lot of repeated code. -What if we could wrap each of the handlers in a function that does this -validation and error checking? Go's -<a href="http://golang.org/doc/go_spec.html#Function_declarations">function -literals</a> provide a powerful means of abstracting functionality -that can help us here. -</p> - -<p> -First, we re-write the function definition of each of the handlers to accept -a title string: -</p> - -<pre> -func viewHandler(w http.ResponseWriter, r *http.Request, title string) -func editHandler(w http.ResponseWriter, r *http.Request, title string) -func saveHandler(w http.ResponseWriter, r *http.Request, title string) -</pre> - -<p> -Now let's define a wrapper function that <i>takes a function of the above -type</i>, and returns a function of type <code>http.HandlerFunc</code> -(suitable to be passed to the function <code>http.HandleFunc</code>): -</p> - -<pre> -func makeHandler(fn func (http.ResponseWriter, *http.Request, string)) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - // Here we will extract the page title from the Request, - // and call the provided handler 'fn' - } -} -</pre> - -<p> -The returned function is called a closure because it encloses values defined -outside of it. In this case, the variable <code>fn</code> (the single argument -to <code>makeHandler</code>) is enclosed by the closure. The variable -<code>fn</code> will be one of our save, edit, or view handlers. -</p> - -<p> -Now we can take the code from <code>getTitle</code> and use it here -(with some minor modifications): -</p> - -<pre> -func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - title := r.URL.Path[lenPath:] - if !titleValidator.MatchString(title) { - http.NotFound(w, r) - return - } - fn(w, r, title) - } -} -</pre> - -<p> -The closure returned by <code>makeHandler</code> is a function that takes -an <code>http.ResponseWriter</code> and <code>http.Request</code> (in other -words, an <code>http.HandlerFunc</code>). -The closure extracts the <code>title</code> from the request path, and -validates it with the <code>TitleValidator</code> regexp. If the -<code>title</code> is invalid, an error will be written to the -<code>ResponseWriter</code> using the <code>http.NotFound</code> function. -If the <code>title</code> is valid, the enclosed handler function -<code>fn</code> will be called with the <code>ResponseWriter</code>, -<code>Request</code>, and <code>title</code> as arguments. -</p> - -<p> -Now we can wrap the handler functions with <code>makeHandler</code> in -<code>main</code>, before they are registered with the <code>http</code> -package: -</p> - -<pre> -func main() { - http.HandleFunc("/view/", makeHandler(viewHandler)) - http.HandleFunc("/edit/", makeHandler(editHandler)) - http.HandleFunc("/save/", makeHandler(saveHandler)) - http.ListenAndServe(":8080", nil) -} -</pre> - -<p> -Finally we remove the calls to <code>getTitle</code> from the handler functions, -making them much simpler: -</p> - -<pre> -func viewHandler(w http.ResponseWriter, r *http.Request, title string) { - p, err := loadPage(title) - if err != nil { - http.Redirect(w, r, "/edit/"+title, http.StatusFound) - return - } - renderTemplate(w, "view", p) -} - -func editHandler(w http.ResponseWriter, r *http.Request, title string) { - p, err := loadPage(title) - if err != nil { - p = &Page{Title: title} - } - renderTemplate(w, "edit", p) -} - -func saveHandler(w http.ResponseWriter, r *http.Request, title string) { - body := r.FormValue("body") - p := &Page{Title: title, Body: []byte(body)} - err := p.save() - if err != nil { - http.Error(w, err.String(), http.StatusInternalServerError) - return - } - http.Redirect(w, r, "/view/"+title, http.StatusFound) -} -</pre> - -<h2>Try it out!</h2> - -<p> -<a href="final.go">Click here to view the final code listing.</a> -</p> - -<p> -Recompile the code, and run the app: -</p> - -<pre> -$ 8g wiki.go -$ 8l wiki.8 -$ ./8.out -</pre> - -<p> -Visiting <a href="http://localhost:8080/view/ANewPage">http://localhost:8080/view/ANewPage</a> -should present you with the page edit form. You should then be able to -enter some text, click 'Save', and be redirected to the newly created page. -</p> - -<h2>Other tasks</h2> - -<p> -Here are some simple tasks you might want to tackle on your own: -</p> - -<ul> -<li>Store templates in <code>tmpl/</code> and page data in <code>data/</code>. -<li>Add a handler to make the web root redirect to - <code>/view/FrontPage</code>.</li> -<li>Spruce up the page templates by making them valid HTML and adding some - CSS rules.</li> -<li>Implement inter-page linking by converting instances of - <code>[PageName]</code> to <br> - <code><a href="/view/PageName">PageName</a></code>. - (hint: you could use <code>regexp.ReplaceAllFunc</code> to do this) - </li> -</ul> diff --git a/doc/codereview_with_mq.html b/doc/codereview_with_mq.html index 33f415f13..38ecbda6e 100644 --- a/doc/codereview_with_mq.html +++ b/doc/codereview_with_mq.html @@ -1,4 +1,6 @@ -<!-- Using Mercurial Queues with Codereview --> +<!--{ + "Title": "Using Mercurial Queues with Codereview" +}--> <h2 id="Introduction">Introduction</h2> diff --git a/doc/codewalk/functions.xml b/doc/codewalk/functions.xml index 986a017e1..db518dcc0 100644 --- a/doc/codewalk/functions.xml +++ b/doc/codewalk/functions.xml @@ -45,7 +45,7 @@ turn. </step> -<step title="Multiple return values" src="doc/codewalk/pig.go:/\/\/ roll returns/,/stay.*true\n}/"> +<step title="Multiple return values" src="doc/codewalk/pig.go:/\/\/ roll returns/,/true\n}/"> Go functions can return multiple values. <br/><br/> @@ -82,16 +82,6 @@ associated with the current player. </step> -<step title="Comparing functions" src="doc/codewalk/pig.go:/if action/,/currentPlayer\)\)\n\t\t}/"> - Functions can be compared for equality in Go. From the - <a href="http://golang.org/doc/go_spec.html#Comparison_operators">language specification</a>: - Function values are equal if they refer to the same function or if both are <code>nil</code>. - <br/><br/> - - We enforce that a <code>strategy</code> function can only return a legal - <code>action</code>: either <code>roll</code> or <code>stay</code>. -</step> - <step title="Simulating a tournament" src="doc/codewalk/pig.go:/\/\/ roundRobin/,/gamesPerStrategy\n}/"> The <code>roundRobin</code> function simulates a tournament and tallies wins. Each strategy plays each other strategy <code>gamesPerSeries</code> times. diff --git a/doc/codewalk/markov.go b/doc/codewalk/markov.go index 959c2b158..a8f322eb6 100644 --- a/doc/codewalk/markov.go +++ b/doc/codewalk/markov.go @@ -50,8 +50,8 @@ import ( "flag" "fmt" "io" + "math/rand" "os" - "rand" "strings" "time" ) @@ -120,8 +120,8 @@ func main() { numWords := flag.Int("words", 100, "maximum number of words to print") prefixLen := flag.Int("prefix", 2, "prefix length in words") - flag.Parse() // Parse command-line flags. - rand.Seed(time.Nanoseconds()) // Seed the random number generator. + flag.Parse() // Parse command-line flags. + rand.Seed(time.Now().UnixNano()) // Seed the random number generator. c := NewChain(*prefixLen) // Initialize a new Chain. c.Build(os.Stdin) // Build chains from standard input. diff --git a/doc/codewalk/markov.xml b/doc/codewalk/markov.xml index a89b4d0ce..085ead7bc 100644 --- a/doc/codewalk/markov.xml +++ b/doc/codewalk/markov.xml @@ -105,7 +105,7 @@ Prefix Map key reads space-separated values from an <code>io.Reader</code>. <br/><br/> The <code>Build</code> method returns once the <code>Reader</code>'s - <code>Read</code> method returns <code>os.EOF</code> (end of file) + <code>Read</code> method returns <code>io.EOF</code> (end of file) or some other read error occurs. </step> @@ -133,7 +133,7 @@ Prefix Map key (including punctuation), which is exactly what we need. <br/><br/> <code>Fscan</code> returns an error if it encounters a read error - (<code>os.EOF</code>, for example) or if it can't scan the requested + (<code>io.EOF</code>, for example) or if it can't scan the requested value (in our case, a single string). In either case we just want to stop scanning, so we <code>break</code> out of the loop. </step> @@ -155,7 +155,7 @@ Prefix Map key <br/><br/> For more information about the <code>append</code> function and slices in general see the - <a href="http://blog.golang.org/2011/01/go-slices-usage-and-internals.html">Slices: usage and internals</a> article. + <a href="/doc/articles/slices_usage_and_internals.html">Slices: usage and internals</a> article. </step> <step title="Pushing the suffix onto the prefix" src="doc/codewalk/markov.go:/p\.Shift/"> @@ -275,16 +275,15 @@ p[len(p)-1] = suffix </step> <step title="Using this program" src="doc/codewalk/markov.go"> - To use this program, first compile and link it. - If you are using <code>6g</code> as your compiler, the command - would look something like this: + To use this program, first build it with the + <a href="/cmd/go/">go</a> command: <pre> -$ 6g markov.go && 6l -o markov markov.6</pre> +$ go build markov.go</pre> And then execute it while piping in some input text: <pre> -$ echo "a man a plan a canal panama" | ./markov -prefix=1 -a plan a man a plan a canal panama - </pre> +$ echo "a man a plan a canal panama" \ + | ./markov -prefix=1 +a plan a man a plan a canal panama</pre> Here's a transcript of generating some text using the Go distribution's README file as source material: <pre> diff --git a/doc/codewalk/pig.go b/doc/codewalk/pig.go index 9e415f589..10963b4e4 100644 --- a/doc/codewalk/pig.go +++ b/doc/codewalk/pig.go @@ -6,7 +6,7 @@ package main import ( "fmt" - "rand" + "math/rand" ) const ( @@ -61,9 +61,6 @@ func play(strategy0, strategy1 strategy) int { currentPlayer := rand.Intn(2) // Randomly decide who plays first for s.player+s.thisTurn < win { action := strategies[currentPlayer](s) - if action != roll && action != stay { - panic(fmt.Sprintf("Player %d is cheating", currentPlayer)) - } s, turnIsOver = action(s) if turnIsOver { currentPlayer = (currentPlayer + 1) % 2 diff --git a/doc/codewalk/sharemem.xml b/doc/codewalk/sharemem.xml index 1a669f7b5..d443e176e 100644 --- a/doc/codewalk/sharemem.xml +++ b/doc/codewalk/sharemem.xml @@ -65,7 +65,7 @@ and then loops passing completed Resources back to the pending channel after appropriate delays. </step> -<step title="Creating channels" src="doc/codewalk/urlpoll.go:/create our/,/complete/"> +<step title="Creating channels" src="doc/codewalk/urlpoll.go:/Create our/,/complete/"> First, main makes two channels of *Resource, pending and complete. <br/><br/> Inside main, a new goroutine sends one Resource per URL to pending @@ -75,7 +75,7 @@ The pending and complete channels are passed to each of the Poller goroutines, within which they are known as in and out. </step> -<step title="Initializing StateMonitor" src="doc/codewalk/urlpoll.go:/launch the StateMonitor/,/statusInterval/"> +<step title="Initializing StateMonitor" src="doc/codewalk/urlpoll.go:/Launch the StateMonitor/,/statusInterval/"> StateMonitor will initialize and launch a goroutine that stores the state of each Resource. We will look at this function in detail later. <br/><br/> @@ -83,14 +83,14 @@ For now, the important thing to note is that it returns a channel of State, which is saved as status and passed to the Poller goroutines. </step> -<step title="Launching Poller goroutines" src="doc/codewalk/urlpoll.go:/launch some Poller/,/}/"> +<step title="Launching Poller goroutines" src="doc/codewalk/urlpoll.go:/Launch some Poller/,/}/"> Now that it has the necessary channels, main launches a number of Poller goroutines, passing the channels as arguments. The channels provide the means of communication between the main, Poller, and StateMonitor goroutines. </step> -<step title="Send Resources to pending" src="doc/codewalk/urlpoll.go:/send some Resources/,/}\(\)/"> +<step title="Send Resources to pending" src="doc/codewalk/urlpoll.go:/Send some Resources/,/}\(\)/"> To add the initial work to the system, main starts a new goroutine that allocates and sends one Resource per URL to pending. <br/><br/> diff --git a/doc/codewalk/urlpoll.go b/doc/codewalk/urlpoll.go index b51be9502..e716c7e6c 100644 --- a/doc/codewalk/urlpoll.go +++ b/doc/codewalk/urlpoll.go @@ -5,17 +5,16 @@ package main import ( - "http" "log" + "net/http" "time" ) const ( - numPollers = 2 // number of Poller goroutines to launch - second = 1e9 // one second is 1e9 nanoseconds - pollInterval = 60 * second // how often to poll each URL - statusInterval = 10 * second // how often to log status to stdout - errTimeout = 10 * second // back-off timeout on error + numPollers = 2 // number of Poller goroutines to launch + pollInterval = 60 * time.Second // how often to poll each URL + statusInterval = 10 * time.Second // how often to log status to stdout + errTimeout = 10 * time.Second // back-off timeout on error ) var urls = []string{ @@ -33,7 +32,7 @@ type State struct { // StateMonitor maintains a map that stores the state of the URLs being // polled, and prints the current state every updateInterval nanoseconds. // It returns a chan State to which resource state should be sent. -func StateMonitor(updateInterval int64) chan<- State { +func StateMonitor(updateInterval time.Duration) chan<- State { updates := make(chan State) urlStatus := make(map[string]string) ticker := time.NewTicker(updateInterval) @@ -61,7 +60,7 @@ func logState(s map[string]string) { // Resource represents an HTTP URL to be polled by this program. type Resource struct { url string - errCount int64 + errCount int } // Poll executes an HTTP HEAD request for url @@ -71,7 +70,7 @@ func (r *Resource) Poll() string { if err != nil { log.Println("Error", r.url, err) r.errCount++ - return err.String() + return err.Error() } r.errCount = 0 return resp.Status @@ -79,8 +78,8 @@ func (r *Resource) Poll() string { // Sleep sleeps for an appropriate interval (dependant on error state) // before sending the Resource to done. -func (r *Resource) Sleep(done chan *Resource) { - time.Sleep(pollInterval + errTimeout*r.errCount) +func (r *Resource) Sleep(done chan<- *Resource) { + time.Sleep(pollInterval + errTimeout*time.Duration(r.errCount)) done <- r } @@ -93,18 +92,18 @@ func Poller(in <-chan *Resource, out chan<- *Resource, status chan<- State) { } func main() { - // create our input and output channels + // Create our input and output channels. pending, complete := make(chan *Resource), make(chan *Resource) - // launch the StateMonitor + // Launch the StateMonitor. status := StateMonitor(statusInterval) - // launch some Poller goroutines + // Launch some Poller goroutines. for i := 0; i < numPollers; i++ { go Poller(pending, complete, status) } - // send some Resources to the pending queue + // Send some Resources to the pending queue. go func() { for _, url := range urls { pending <- &Resource{url: url} diff --git a/doc/community.html b/doc/community.html deleted file mode 100644 index c3b16cacb..000000000 --- a/doc/community.html +++ /dev/null @@ -1,53 +0,0 @@ -<!-- title Community --> - -<div class="left-column"> - -<h2 id="developer_info">The Go Community</h2> - -<h3 id="mailinglist"><a href="http://groups.google.com/group/golang-nuts">Go Nuts Mailing List</a></h3> -<p>The <a href="http://groups.google.com/group/golang-nuts">golang-nuts</a> -mailing list is for general Go discussion.</p> - -<h3 id=""><a href="http://godashboard.appspot.com/package">Go Packages Dashboard</a></h3> -<p>A list of the most popular <a href="/cmd/goinstall/">goinstall</a>'d -Go libraries.</p> - -<h3 id=""><a href="http://godashboard.appspot.com/project">Go Project Dashboard</a></h3> -<p>A list of external Go projects including programs and libraries.</p> - -<h3 id="irc"><a href="irc:irc.freenode.net/go-nuts">Go IRC Channel</a></h3> -<p><b>#go-nuts</b> on <b>irc.freenode.net</b> is the official Go IRC channel.</p> - -<h3 id="twitter"><a href="http://twitter.com/go_nuts">@go_nuts at Twitter</a></h3> -<p>The Go project's official Twitter account.</p> - -</div> - -<div class="right-column"> - -<h2 id="blogs">Blogs</h2> - -<h3 id="blog_go"><a href="http://blog.golang.org/">The Go Blog</a></h3> -<p> -The Go project's official blog, maintained by the core Go developers. -</p> - -<h3 id="blog_rsc"><a href="http://research.swtch.com/search/label/Go">research!rsc</a></h3> -<p> -Posts labelled 'Go' by Russ Cox, one of the core Go developers. -</p> - -<h3 id="blog_iant"><a href="http://www.airs.com/blog/archives/category/programming">Airs</a></h3> -<p> -Posts labelled 'Programming' by Ian Lance Taylor, one of the core Go developers. -</p> - -<h3 id="blog_adg"><a href="http://nf.id.au/tag/go">nf.id.au</a></h3> -<p> -Posts labelled 'Go' by Andrew Gerrand, one of the core Go developers. -</p> - -</div> - -<div class="end-columns"></div> - diff --git a/doc/contrib.html b/doc/contrib.html index 84d2cda6a..b4bd47e96 100644 --- a/doc/contrib.html +++ b/doc/contrib.html @@ -1,6 +1,55 @@ -<!-- title Contributing --> +<!--{ + "Title": "The Go Project", + "Path": "/project/" +}--> + +<img class="gopher" src="/doc/gopher/project.png" /> + +<div id="manual-nav"></div> + +<p> +Go is an open source project developed by a team at +<a href="http://google.com/">Google</a> and many +<a href="/CONTRIBUTORS">contributors</a> from the open source community. +</p> + +<p> +Go is distributed under a <a href="/LICENSE">BSD-style license</a>. +</p> + +<h3 id="announce"><a href="http://groups.google.com/group/golang-announce">Announcements Mailing List</a></h3> +<p> +A low traffic mailing list for important announcements, such as new releases. +</p> +<p> +We encourage all Go users to subscribe to +<a href="http://groups.google.com/group/golang-announce">golang-announce</a>. +</p> + +<h2 id="resources">Developer Resources</h2> + +<h3 id="source"><a href="https://code.google.com/p/go/source">Source Code</a></h3> +<p>Check out the Go source code.</p> + +<h3 id="release"><a href="/doc/devel/release.html">Release History</a></h3> +<p>A summary of the changes between Go releases.</p> + +<h3 id="weekly"><a href="/doc/devel/weekly.html">Weekly Snapshot History</a></h3> +<p>A summary of the changes between weekly snapshots of Go.</p> + +<h3 id="golang-dev"><a href="http://groups.google.com/group/golang-dev">Developer Mailing List</a></h3> +<p>The <a href="http://groups.google.com/group/golang-dev">golang-dev</a> +mailing list is for discussing and reviewing code for the Go project.</p> +<p>For general discussion of Go programming, see <a +href="http://groups.google.com/group/golang-nuts">golang-nuts</a>.</p> + +<h3 id="golang-checkins"><a href="http://groups.google.com/group/golang-checkins">Checkins Mailing List</a></h3> +<p>A mailing list that receives a message summarizing each checkin to the Go repository.</p> + +<h3 id="build_status"><a href="http://build.golang.org/">Build Status</a></h3> +<p>View the status of Go builds across the supported operating +systems and architectures.</p> -<div class="left-column"> <h2 id="howto">How you can help</h2> @@ -19,13 +68,13 @@ a new one.) We pride ourselves on being meticulous; no issue is too small. </p> -<h3><a href="contribute.html">Contributing code</a></h3> +<h3><a href="/doc/contribute.html">Contributing code</a></h3> <p> Go is an open source project and we welcome contributions from the community. </p> <p> -To get started, read these <a href="contribute.html">contribution +To get started, read these <a href="/doc/contribute.html">contribution guidelines</a> for information on design, testing, and our code review process. </p> <p> @@ -35,35 +84,25 @@ open issues that interest you. Those labeled are particularly in need of outside help. </p> -</div> - -<div class="right-column"> -<h2 id="the_go_project">The Go Project</h2> +<h2 id="community">The Go Community</h2> -<h3 id="build_status"><a href="http://godashboard.appspot.com/">Build Status</a></h3> -<p>View the status of Go builds across the supported operating -systems and architectures.</p> +<h3 id="mailinglist"><a href="http://groups.google.com/group/golang-nuts">Go Nuts Mailing List</a></h3> +<p>The <a href="http://groups.google.com/group/golang-nuts">golang-nuts</a> +mailing list is for general Go discussion.</p> -<h3 id="roadmap"><a href="devel/roadmap.html">Roadmap</a></h3> -<p>Features and ideas being developed or discussed by the Go team.</p> +<h3 id="projects"><a href="http://godashboard.appspot.com/project">Go Project Dashboard</a></h3> +<p>A list of external Go projects including programs and libraries.</p> -<h3 id="release"><a href="devel/release.html">Release History</a></h3> -<p>A summary of the changes between Go releases.</p> - -<h3 id="release"><a href="devel/weekly.html">Weekly Snapshot History</a></h3> -<p>A summary of the changes between weekly snapshots of Go.</p> - -<h3 id="golang-dev"><a href="http://groups.google.com/group/golang-dev">Developer Mailing List</a></h3> -<p>The <a href="http://groups.google.com/group/golang-dev">golang-dev</a> -mailing list is for discussing and reviewing code for the Go project.</p> -<p>For general discussion of Go programming, see <a -href="http://groups.google.com/group/golang-nuts">golang-nuts</a>.</p> - -<h3 id="golang-checkins"><a href="http://groups.google.com/group/golang-checkins">Checkins Mailing List</a></h3> -<p>A mailing list that receives a message summarizing each checkin to the Go repository.</p> +<h3 id="irc"><a href="irc:irc.freenode.net/go-nuts">Go IRC Channel</a></h3> +<p><b>#go-nuts</b> on <b>irc.freenode.net</b> is the official Go IRC channel.</p> -</div> +<h3 id="plus"><a href="https://plus.google.com/101406623878176903605/posts">The Go Programming Language at Google+</a></h3> +<p>The Go project's Google+ page.</p> -<div class="end-columns"></div> +<h3 id="twitter"><a href="http://twitter.com/go_nuts">@go_nuts at Twitter</a></h3> +<p>The Go project's official Twitter account.</p> +<h3 id="blog"><a href="http://blog.golang.org/">The Go Blog</a></h3> +<p>The official blog of the Go project, featuring news and in-depth articles by +the Go team and guests.</p> diff --git a/doc/contribute.html b/doc/contribute.html index c4b1ce2b5..e1f39ae7e 100644 --- a/doc/contribute.html +++ b/doc/contribute.html @@ -1,11 +1,13 @@ -<!-- Contribution Guidelines --> +<!--{ + "Title": "Contribution Guidelines" +}--> <h2 id="Introduction">Introduction</h2> <p> This document explains how to contribute changes to the Go project. It assumes you have installed Go using the -<a href="install.html">installation instructions</a> and +<a href="/doc/install">installation instructions</a> and have <a href="code.html">written and tested your code</a>. (Note that the <code>gccgo</code> frontend lives elsewhere; see <a href="gccgo_contribute.html">Contributing to gccgo</a>.) @@ -210,10 +212,10 @@ to this change, and the <code>CC</code> line lists people to notify about the change. These can be code review nicknames or arbitrary email addresses. Unless explicitly told otherwise, such as in the discussion leading -up to sending in the change list, set the -reviewer field to the +up to sending in the change list, leave the reviewer field blank. +This means that the <a href="http://groups.google.com/group/golang-dev">golang-dev@googlegroups.com</a> -mailing list. +mailing list will be used as the reviewer. </p> <p> @@ -402,7 +404,7 @@ $ hg mail -r golang-dev@googlegroups.com --cc math-nuts@swtch.com 99999 <p> Running <code>hg mail</code> will send an email to you and the reviewers -asking them to visit the issue's URL and make coments on the change. +asking them to visit the issue's URL and make comments on the change. When done, the reviewer clicks “Publish and Mail comments” to send comments back. </p> @@ -523,7 +525,7 @@ This rigmarole needs to be done only for your first submission. <p>Code that you contribute should use the standard copyright header:</p> <pre> -// Copyright 2011 The Go Authors. All rights reserved. +// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. </pre> diff --git a/doc/debugging_with_gdb.html b/doc/debugging_with_gdb.html index 04850c026..b2683913f 100644 --- a/doc/debugging_with_gdb.html +++ b/doc/debugging_with_gdb.html @@ -1,22 +1,26 @@ -<!-- title Debugging Go Code with GDB --> +<!--{ + "Title": "Debugging Go Code with GDB", + "Path": "/doc/gdb" +}--> <p><i> -This applies to the 6g toolchain. Gccgo has native gdb support. Besides this -overview you might want to consult the +This applies to the <code>gc</code> toolchain. Gccgo has native gdb support. +Besides this overview you might want to consult the <a href="http://sourceware.org/gdb/current/onlinedocs/gdb/">GDB manual</a>. </i></p> <h2 id="Introduction">Introduction</h2> <p> -When you compile and link your Go programs with the 6g/6l or 8g/8l toolchains -on Linux, Mac OSX or FreeBSD, the resulting binaries contain DWARFv3 -debugging information that recent versions (>7.1) of the GDB debugger can +When you compile and link your Go programs with the <code>gc</code> toolchain +on Linux, Mac OS X or FreeBSD, the resulting binaries contain DWARFv3 +debugging information that recent versions (>7.1) of the GDB debugger can use to inspect a live process or a core dump. </p> <p> -Pass the <code>'-s'</code> flag to the linker to omit the debug information. +Pass the <code>'-s'</code> flag to the linker to omit the debug information +(for example, <code>go build -ldflags "-s" prog.go</code>). </p> @@ -25,7 +29,7 @@ Pass the <code>'-s'</code> flag to the linker to omit the debug information. <ul> <li> Show file and line number for code -and set breakpoints: +, set breakpoints and disassemble: <pre>(gdb) <b>list</b> (gdb) <b>list <i>line</i></b> (gdb) <b>list <i>file.go</i>:<i>line</i></b> @@ -34,7 +38,7 @@ and set breakpoints: (gdb) <b>disas</b></pre> </li> <li> -Unwind stack frames: +Show backtraces and unwind stack frames: <pre>(gdb) <b>bt</b> (gdb) <b>frame <i>n</i></b></pre> </li> @@ -98,7 +102,7 @@ the Go source distribution. It depends on some special magic types <code>runtime.g</code>) that the linker (<a href="/src/cmd/ld/dwarf.c">src/cmd/ld/dwarf.c</a>) ensures are described in the DWARF code. -</ines +</p> <p> If you're interested in what the debugging information looks like, run @@ -125,26 +129,26 @@ the form <code>pkg.(*MyType).Meth</code>. <p> In this tutorial we will inspect the binary of the <a href="/pkg/regexp/">regexp</a> package's unit tests. To build the binary, -change to <code>$GOROOT/src/pkg/regexp</code> and run <code>gotest</code>. -This should produce an executable file named <code>6.out</code>. +change to <code>$GOROOT/src/pkg/regexp</code> and run <code>go test -c</code>. +This should produce an executable file named <code>regexp.test</code>. </p> <h3 id="Getting_Started">Getting Started</h3> <p> -Launch GDB, debugging <code>6.out</code>: +Launch GDB, debugging <code>regexp.test</code>: </p> <pre> -$ <b>gdb 6.out</b> +$ <b>gdb regexp.test</b> GNU gdb (GDB) 7.2-gg8 Copyright (C) 2010 Free Software Foundation, Inc. License GPLv 3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> Type "show copying" and "show warranty" for licensing/warranty details. This GDB was configured as "x86_64-linux". -Reading symbols from /home/user/go/src/pkg/regexp/6.out... +Reading symbols from /home/user/go/src/pkg/regexp/regexp.test... done. Loading Go Runtime support. (gdb) @@ -161,7 +165,7 @@ pass your <code>$GOROOT</code> with the <code>'-d'</code> flag: </p> <pre> -$ <b>gdb 6.out -d $GOROOT</b> +$ <b>gdb regexp.test -d $GOROOT</b> </pre> <p> @@ -214,14 +218,13 @@ package is known to GDB as <code>'regexp.Compile'</code>. <p> Methods must be qualified with the name of their receiver types. For example, -the <code>*Regexp</code> type’s <code>doParse</code> method is known as -<code>'regexp.*Regexp.doParse'</code>. (Note that the second dot is a "middot," -an artifact of Go’s internal representation of methods.) +the <code>*Regexp</code> type’s <code>String</code> method is known as +<code>'regexp.(*Regexp).String'</code>. </p> <p> Variables that shadow other variables are magically suffixed with a number in the debug info. -Variables referenced by closures will appear as pointers magically prefixed with '&'. +Variables referenced by closures will appear as pointers magically prefixed with '&'. </p> <h3 id="Setting_breakpoints">Setting breakpoints</h3> @@ -241,7 +244,7 @@ Run the program: <pre> (gdb) <b>run</b> -Starting program: /home/lvd/g/src/pkg/regexp/6.out +Starting program: /home/user/go/src/pkg/regexp/regexp.test Breakpoint 1, regexp.TestFind (t=0xf8404a89c0) at /home/user/go/src/pkg/regexp/find_test.go:148 148 func TestFind(t *testing.T) { @@ -284,16 +287,18 @@ The other goroutine, number 1, is stuck in <code>runtime.gosched</code>, blocked <pre> (gdb) <b>goroutine 1 bt</b> -#0 0x000000000040facb in runtime.gosched () at /home/lvd/g/src/pkg/runtime/proc.c:873 +#0 0x000000000040facb in runtime.gosched () at /home/user/go/src/pkg/runtime/proc.c:873 #1 0x00000000004031c9 in runtime.chanrecv (c=void, ep=void, selected=void, received=void) - at /home/lvd/g/src/pkg/runtime/chan.c:342 -#2 0x0000000000403299 in runtime.chanrecv1 (t=void, c=void) at/home/lvd/g/src/pkg/runtime/chan.c:423 -#3 0x000000000043075b in testing.RunTests (matchString={void (struct string, struct string, bool *, os.Error *)} 0x7ffff7f9ef60, tests= []testing.InternalTest = {...}) at /home/lvd/g/src/pkg/testing/testing.go:201 -#4 0x00000000004302b1 in testing.Main (matchString={void (struct string, struct string, bool *, os.Error *)} 0x7ffff7f9ef80, tests= []testing.InternalTest = {...}, benchmarks= []testing.InternalBenchmark = {...}) - at /home/lvd/g/src/pkg/testing/testing.go:168 -#5 0x0000000000400dc1 in main.main () at /home/lvd/g/src/pkg/regexp/_testmain.go:98 -#6 0x00000000004022e7 in runtime.mainstart () at /home/lvd/g/src/pkg/runtime/amd64/asm.s:78 -#7 0x000000000040ea6f in runtime.initdone () at /home/lvd/g/src/pkg/runtime/proc.c:243 + at /home/user/go/src/pkg/runtime/chan.c:342 +#2 0x0000000000403299 in runtime.chanrecv1 (t=void, c=void) at/home/user/go/src/pkg/runtime/chan.c:423 +#3 0x000000000043075b in testing.RunTests (matchString={void (struct string, struct string, bool *, error *)} + 0x7ffff7f9ef60, tests= []testing.InternalTest = {...}) at /home/user/go/src/pkg/testing/testing.go:201 +#4 0x00000000004302b1 in testing.Main (matchString={void (struct string, struct string, bool *, error *)} + 0x7ffff7f9ef80, tests= []testing.InternalTest = {...}, benchmarks= []testing.InternalBenchmark = {...}) +at /home/user/go/src/pkg/testing/testing.go:168 +#5 0x0000000000400dc1 in main.main () at /home/user/go/src/pkg/regexp/_testmain.go:98 +#6 0x00000000004022e7 in runtime.mainstart () at /home/user/go/src/pkg/runtime/amd64/asm.s:78 +#7 0x000000000040ea6f in runtime.initdone () at /home/user/go/src/pkg/runtime/proc.c:243 #8 0x0000000000000000 in ?? () </pre> @@ -304,7 +309,7 @@ The stack frame shows we’re currently executing the <code>regexp.TestFind</cod <pre> (gdb) <b>info frame</b> Stack level 0, frame at 0x7ffff7f9ff88: - rip = 0x425530 in regexp.TestFind (/home/lvd/g/src/pkg/regexp/find_test.go:148); + rip = 0x425530 in regexp.TestFind (/home/user/go/src/pkg/regexp/find_test.go:148); saved rip 0x430233 called by frame at 0x7ffff7f9ffa8 source language minimal. @@ -343,12 +348,12 @@ $1 = (struct testing.T *) 0xf840688b60 $1 = (struct testing.T *) 0xf840688b60 (gdb) p *t $2 = {errors = "", failed = false, ch = 0xf8406f5690} -(gdb) p *t->ch -$3 = struct hchan<*testing.T> +(gdb) p *t->ch +$3 = struct hchan<*testing.T> </pre> <p> -That <code>struct hchan<*testing.T></code> is the runtime-internal represntation of a channel. It is currently empty, or gdb would have pretty-printed it's contents. +That <code>struct hchan<*testing.T></code> is the runtime-internal representation of a channel. It is currently empty, or gdb would have pretty-printed it's contents. </p> <p> @@ -381,7 +386,7 @@ We can step into the <code>String</code>function call with <code>"s"</code>: <pre> (gdb) <b>s</b> -regexp.(*Regexp).String (re=0xf84068d070, noname=void) at /home/lvd/g/src/pkg/regexp/regexp.go:97 +regexp.(*Regexp).String (re=0xf84068d070, noname=void) at /home/user/go/src/pkg/regexp/regexp.go:97 97 func (re *Regexp) String() string { </pre> @@ -391,14 +396,13 @@ Get a stack trace to see where we are: <pre> (gdb) <b>bt</b> -(gdb) bt #0 regexp.(*Regexp).String (re=0xf84068d070, noname=void) - at /home/lvd/g/src/pkg/regexp/regexp.go:97 + at /home/user/go/src/pkg/regexp/regexp.go:97 #1 0x0000000000425615 in regexp.TestFind (t=0xf840688b60) - at /home/lvd/g/src/pkg/regexp/find_test.go:151 + at /home/user/go/src/pkg/regexp/find_test.go:151 #2 0x0000000000430233 in testing.tRunner (t=0xf840688b60, test=0x5747b8) - at /home/lvd/g/src/pkg/testing/testing.go:156 -#3 0x000000000040ea6f in runtime.initdone () at /home/lvd/g/src/pkg/runtime/proc.c:243 + at /home/user/go/src/pkg/testing/testing.go:156 +#3 0x000000000040ea6f in runtime.initdone () at /home/user/go/src/pkg/runtime/proc.c:243 .... </pre> @@ -439,7 +443,7 @@ you can look inside the runtime representation to do that (tab completion helps (gdb) <b>p slc</b> $11 = []int = {0, 0} -(gdb) <b>p slc-></b><i><TAB></i> +(gdb) <b>p slc-></b><i><TAB></i> array slc len (gdb) <b>p slc->array</b> $12 = (int *) 0xf84057af00 @@ -460,7 +464,7 @@ $24 = 4 </pre> <p> -Channels and maps are 'reference' types, which gdb shows as pointers to C++-like types <code>hash<int,string>*</code>. Dereferencing will trigger prettyprinting +Channels and maps are 'reference' types, which gdb shows as pointers to C++-like types <code>hash<int,string>*</code>. Dereferencing will trigger prettyprinting </p> <p> diff --git a/doc/devel/index.html b/doc/devel/index.html deleted file mode 100644 index ae405bf52..000000000 --- a/doc/devel/index.html +++ /dev/null @@ -1,11 +0,0 @@ -<!-- The Go project --> - -<ul> -<li><a href="roadmap.html">Roadmap</a></li> -<li><a href="release.html">Release history</a></li> -<li><a href="weekly.html">Weekly snapshot history</a></li> -<li><a href="http://godashboard.appspot.com">Build and benchmark status</a></li> -</ul> -<ul> -<li><a href="../contribute.html">Contributing code</a></li> -</ul> diff --git a/doc/devel/release.html b/doc/devel/release.html index 984e67493..65946e31f 100644 --- a/doc/devel/release.html +++ b/doc/devel/release.html @@ -1,4 +1,6 @@ -<!-- Release History --> +<!--{ + "Title": "Release History" +}--> <p>This page summarizes the changes between official stable releases of Go. Between releases we issue less stable @@ -11,9 +13,28 @@ has full details.</p> <pre> hg pull -hg update release.r<i>NN</i> +hg update <i>tag</i> </pre> +<h2 id="go1">go1 (released 2012/03/28)</h2> + +<p> +Go 1 is a major release of Go that will be stable in the long term. +Read the <a href="/doc/go1.html">Go 1 Release Notes</a> for more information. +</p> + +<p> +It is intended that programs written for Go 1 will continue to compile and run +correctly, unchanged, under future versions of Go 1. +Read the <a href="/doc/go1compat.html">Go 1 compatibility document</a> for more +about the future of Go 1. +</p> + +<p> +The go1 release corresponds to +<code><a href="weekly.html#2012-03-27">weekly.2012-03-27</a></code>. +</p> + <h2 id="r60">r60 (released 2011/09/07)</h2> <p> diff --git a/doc/devel/roadmap.html b/doc/devel/roadmap.html deleted file mode 100644 index d3c494715..000000000 --- a/doc/devel/roadmap.html +++ /dev/null @@ -1,135 +0,0 @@ -<!-- Roadmap --> - -<h2 id="Roadmap">Go Roadmap</h2> - -<p> -This page lists features and ideas being developed or discussed by the -Go team. This list will be updated as work continues. - -<p> -The roadmap should be discussed on -the <a href="http://groups.google.com/group/golang-nuts">golang-nuts -mailing list</a>. - -<h3 id="Language_roadmap"> -Language roadmap</h3> - -<p> -This is a list of language changes that are being considered. -Appearance on this list is no guarantee that the change will be -accepted. - -<ul> -<li> -Possibly rewrite restriction on goto across variable declarations. -<li> -Variant types. A way to define a type as being the union of some set -of types. -<li> -Generics. An active topic of discussion. -<li> -Methods for operators, to allow a type to use arithmetic notation for -expressions. -<li> -Possibly allow top-level packages to be given names other than main. -</ul> - -<h3 id="Implementation_roadmap"> -Implementation roadmap</h3> - -<ul> -<li> -Improved garbage collector. -<li> -Debugger. -<li> -Improved implementation documentation. -</ul> - -<h4 id="Gc_roadmap"> -Gc compiler roadmap</h4> - -<ul> -<li> -Implement goto restrictions. -<li> -Improved optimization. -<li> -Use escape analysis to keep more data on stack. -</ul> - -<h4 id="Gccgo_roadmap"> -Gccgo compiler roadmap</h4> - -<ul> -<li> -Implement goto restrictions. -<li> -Use goroutines rather than threads. -<li> -Separate gcc interface from frontend proper. -<li> -Use escape analysis to keep more data on stack. -</ul> - -<h4 id="Tools_roadmap"> -Tools roadmap</h4> - -<ul> -<li> -Strengthen goinstall until it can displace make for most builds. -</ul> - -<h4 id="Packages_roadmap"> -Packages roadmap</h4> - -<ul> -<li> -Faster, RE2-like regular expressions. -<li> -Comprehensive support for international text. -<li> -Support for international dates, times, etc. -<li> -Support for multilingual messages. -</ul> - - -<h3 id="done">Done</h3> - -<ul> -<li> -gc: Generate DWARF debug info. -<li> -gc: Provide gdb support for runtime facilities. -<li> -Safe compilation mode: generate code that is guaranteed not to obtain an invalid memory address other than via <code>import "unsafe"</code>. -<li> -Gccgo: garbage collection. -<li> -SWIG support. -<li> -Simpler semicolon rules. -<li> -A more general definition of <code>...</code> in parameter lists. -<li> -Explicit conversions from <code>string</code> -to <code>[]byte</code> and <code>[]int</code>. -<li> -A function that will be run by the garbage collector when an item is freed -(runtime.SetFinalizer). -<li> -Public continuous build and benchmark infrastructure (gobuilder). -<li> -Package manager (goinstall). -<li> -A means of recovering from a panic (recover). -<li> -5g: Better floating point support. -<li> -Improved CGO including some mechanism for calling back from C to Go. -<li> -Faster, allocation-light reflection. -<li> -App Engine support. -</ul> diff --git a/doc/devel/weekly.html b/doc/devel/weekly.html index d984d3b1b..46efe41ed 100644 --- a/doc/devel/weekly.html +++ b/doc/devel/weekly.html @@ -1,4 +1,6 @@ -<!-- Weekly Snapshot History --> +<!--{ + "Title": "Weekly Snapshot History" +}--> <p>This page summarizes the changes between tagged weekly snapshots of Go. For full details, see the <a href="http://code.google.com/p/go/source/list">Mercurial change log</a>.</p> @@ -14,6 +16,2243 @@ hg pull hg update weekly.<i>YYYY-MM-DD</i> </pre> +<h2 id="2012-03-27">2012-03-27 (<a href="release.html#go1">Go 1</a>)</h2> + +<pre> +* cmd/dist: fix detection of go1 version. +* cmd/go: add missing error check (thanks Evan Shaw), + allow underscores in tool name (thanks Shenghou Ma), + bug fixes, + copy tag_test.go from goinstall, + explain versions better, + respect $GOBIN always, + update for go1 tag format. +* cmd/godoc: canonicalize custom path redirects, + fix app engine version, + use virtual filesystem to implement -templates flag. +* codewalk/sharemem.xml: fix references to files. +* crypto/tls: don't select ECC ciphersuites with no mutual curve. +* doc: add JSON-RPC: a tale of interfaces article (thanks Francisco Souza), + describe the Windows MSI installer as experimental, + link to Go Project Dashboard from package list, + update wiki tutorial templates and template discussion, + and many minor fixes. +* exp/types: generalized GCImporter API. +* go/build: cgoEnabled is not known to cmd/dist anymore (thanks Shenghou Ma), + fix import check. +* godoc: make 'Overview' section collapsible. +* misc/dist: many fixes and tweaks. +* misc/emacs: fix indentation bug. +* misc/goplay: fix error on IE8 (thanks Yasuhiro Matsumoto). +* net: ignore ECONNABORTED from syscall.Accept (thanks Devon H. O'Dell). +* os: add missing byte to FileMode buffer (thanks Stefan Nilsson). +* path/filepath: convert drive letter to upper case in windows EvalSymlinks (thanks Alex Brainman), + correct comment in EvalSymlinks (thanks Alex Brainman), + use windows GetShortPathName api to force GetLongPathName to do its work (thanks Alex Brainman), + windows drive letter cannot be a digit (thanks Alex Brainman). +* run.bash: compile the codewalks. +* runtime: restore deadlock detection in the simplest case (thanks Rémy Oudompheng), + work around false negative in deadlock detection. +* text/template: fix typo in package comment. +* windows: installer fixes (thanks Joe Poirier). +</pre> + +<h2 id="2012-03-22">2012-03-22 (Go 1 Release Candidate 2)</h2> + +<pre> +As with last week's snapshot, this snapshot is another Go 1 release candidate. +A notable change in this snapshot are Windows installer fixes. + +Changes in this snapshot: +* 5l, 6l, 8l: fix stack split logic for stacks near default segment size. +* archive/zip: move r.zip off disk, into reader_test.go. +* build: catch API changes during build, + do more during windows build (thanks Alex Brainman), + lengthen timeout for the lengthy runtime test (thanks Shenghou Ma), + unset GOPATH before tests (thanks Shenghou Ma). +* cmd/cgo: add support for function export for gccgo (thanks Rémy Oudompheng), + fix handling of errno for gccgo. +* cmd/go: add -fno-common by default on Darwin (thanks Shenghou Ma), + don't add detail to errPrintedOutput, + fix directory->import path conversion, + make build errors more visible, + use .o, not .{5,6,8}, for gccgo created object files, + work around occasional ETXTBSY running cgo. +* cmd/godoc: add toys, tour button to playground, + inform users that the playground doesn't work via local godoc, + style example headings like links, + use *goroot as base path in zip file, + use FormatText for formating code in html template, + use shorter titles for tabs. +* cmd/gofmt: show ascii in usage (thanks Yasuhiro Matsumoto). +* cmd/pack: also recognize '\\' as path separator in filenames (thanks Shenghou Ma). +* crypto/tls: always send a Certificate message if one was requested. +* doc/install: remove reference to "Go Tutorial" (thanks Shenghou Ma). +* doc/play: use []rune instead of []int (thanks Yasuhiro Matsumoto). +* doc: add Go Concurrency Patterns: Timing out, moving on article (thanks Francisco Souza), + add Go image/draw package article and convert code snippets to Go1, + add Gobs of data article (thanks Francisco Souza), + add Godoc: documenting Go code article (thanks Francisco Souza), + add JSON and Go article (thanks Francisco Souza), + general update of gccgo installation instructions, + minor updates to most docs. +* flag: add examples. +* gc: fix struct and array comparisons for new bool rules (thanks Anthony Martin), + use quoted string format in import error, + when expanding append inline, preserve arguments. +* go/build: clarify why we exclude files starting with '_' or '.' (thanks Shenghou Ma), + clearer argument name for Import (src -> srcDir), + do not report Target for local imports, + fix match. +* go/printer, gofmt: fix multi-line logic. +* html/template: add Templates and XXXEscape functions, + fix nil pointer bug, + fix panic on Clone. +* io/ioutil: fix crash when Stat fails. +* make.bat: fix for old files (thanks Christopher Redden), + don't show error message if old generated files do not exist (thanks Shenghou Ma), + properly handle directories with spaces (thanks Alex Brainman). +* misc/cgo/gmp: update for Go 1 (thanks Shenghou Ma). +* misc/dashboard: remove old python package dashboard. +* misc/dist: don't ship cmd/cov or cmd/prof, + force modes to 0755 or 0644 in tarballs, + remove exp and old before building. +* misc/vim: restore fileencodings (thanks Yasuhiro Matsumoto). +* net/http: couple more triv.go modernizations, + ensure triv.go compiles and runs (thanks Robert Hencke). +* net: drop unnecessary type assertions and fix leak in test (thanks Mikio Hara). +* os: IsNotExist() should also consider ERROR_PATH_NOT_FOUND on Windows (thanks Shenghou Ma), + do not assume syscall.Write will write everything, + remove document duplication in error predicate functions (thanks Shenghou Ma), + return some invented data from Stat(DevNull) on windows (thanks Alex Brainman). +* path/filepath: implement Match and Glob on windows (thanks Alex Brainman). +* reflect: document PkgPath, Method, StructField, + panic if MakeSlice is given bad len/cap arguments. +* run.bat: disable test in test\bench\go1 to fix build (thanks Alex Brainman). +* runtime/cgo: darwin signal masking (thanks Mikio Hara), + linux signal masking (thanks Mikio Hara). +* runtime: do not handle signals before configuring handler, + manage stack by ourselves for badcallback on windows/amd64 (thanks Shenghou Ma), + remove unused goc2c.c (thanks Shenghou Ma). +* sort: add time complexity to doc (thanks Stefan Nilsson), + fix computation of maxDepth to avoid infinite loop (thanks Stefan Nilsson). +* spec: delete references to unsafe.Reflect,Typeof,Unreflect. +* syscall: Test SCM_CREDENTIALS, SO_PASSCRED on Linux (thanks Albert Strasheim), + add a test for passing an fd over a unix socket, + delete passfd_test.go. +* test: use testlib in a few more cases (thanks Shenghou Ma). +* text/template: fix a couple of parse bugs around identifiers, + variables do not take arguments. +</pre> + +<h2 id="2012-03-13">2012-03-13 (Go 1 Release Candidate 1)</h2> + +<pre> +This weekly snapshot is very close to what we expect will be the contents of +the Go 1 release. There are still a few minor documentation issues to resolve, +and a handful of bugs that should be addressed before the release, but the vast +majority of Go programs should be completely unaffected by any changes we make +between now and the full release. + +If you're interested in helping us test, eager to try out Go 1, or just +curious, this weekly snapshot is the one to try. We'll issue a new App Engine +Go 1 beta SDK very soon, so if you're an App Engine user you can try it there +too. + +To help us focus on any remaining bugs and avoid introducing new ones, we will +restrict our attention to critical fixes and issues marked Go1-Must in the +issue tracker. Everything non-essential will be held until after the Go 1 +release is cut and in the field for a while. + +Changes in this snapshot: +* archive/zip: verify CRC32s in non-streamed files, + write data descriptor signature for OS X; fix bugs reading it. +* build: build correct cmd/dist matching GOHOSTARCH (thanks Shenghou Ma), + re-enable some broken tests in run.bash (thanks Shenghou Ma), + remove some references to Make.inc etc. + use run.go for running tests. +* builder: use short test for subrepos (thanks Shenghou Ma). +* cgo, runtime: diagnose callback on non-Go thread. +* cmd/api: set compiler for all build contexts, + work on Windows again, and make gccgo files work a bit more. +* cmd/cgo: document CGO_LDFLAGS and CGO_CFLAGS, + silence const warnings. +* cmd/dist, cmd/go: move CGO_ENABLED from 'go tool dist env' to 'go env' (thanks Shenghou Ma). +* cmd/dist: fix build for Linux/ARM (thanks Shenghou Ma), + use correct hg tag for go version (thanks Alex Brainman). +* cmd/fix: add rules for net/http -> net/http/httputil renames. +* cmd/gc: allow ~ in import paths, + delete old map delete in walk, + do not confuse unexported methods of same name, + if $GOROOT_FINAL is set, rewrite file names in object files, + implement len(array) / cap(array) rule, + import path cannot start with slash on Windows (thanks Shenghou Ma), + must not inline panic, recover, + show duplicate key in error, + unnamed struct types can have methods. +* cmd/go: add -compiler, + add env command, use to fix misc/cgo/testso, + allow go get with arbitrary URLs, + allow ssh tunnelled bzr, git and svn (thanks Ingo Oeser), + always provide .exe suffix on windows (thanks Shenghou Ma), + document import path meta tag discovery in go help remote, + honor buildflags in run, test (thanks Rémy Oudompheng), + local import fixes, + make go get new.code/... work, + rebuild external test package dependencies, + respect $GOBIN always, + support -compiler for go list, fix isStale for gccgo (thanks Rémy Oudompheng). +* cmd/godoc: add support for serving templates. + fix codewalk handler (thanks Francisco Souza). + remove extra / in paths (thanks Ugorji Nwoke), + support $GOPATH, simplify file system code, + switch on +1 buttons. +* cmd/gofmt: fix race in long test (thanks Mikio Hara). +* codereview: fix for Mercurial 2.1. +* crypto/x509: allow server gated crypto in windows systemVerify (thanks Mikkel Krautz), + do not forget to free cert context (thanks Alex Brainman), + don't include empty additional primes in PKCS#1 private key, + enforce path length constraint, + new home for root fetchers; build chains using Windows API (thanks Mikkel Krautz). +* csv: clarify what a negative FieldsPerRecord means. +* database/sql: add docs about connection state, pooling, + ensure Stmts are correctly closed (thanks Gwenael Treguier), + fix double connection free on Stmt.Query error, + fix typo bug resulting in double-Prepare. +* database/sql: add ErrBadConn. +* doc/go1: template packages have changed since r60. +* doc/go_mem: init-created goroutine behavior changes for Go 1 (thanks Shenghou Ma). +* doc/gopher: flip frontpage gopher's eyes. +* doc: add "About the go command" article, + add C? Go? Cgo! article (thanks Francisco Souza), + add Go's declaration syntax article (thanks Francisco Souza), + add more gophers, + add note about import . to Go 1 compatibility notes, + several doc fixes and improvements, + update Effective Go init section, + update progs/run (thanks Shenghou Ma), + update reference gopher, + web site tweaks. +* encoding/asn1: handle UTCTime before the year 2000. +* encoding/binary: improve package comment (thanks Stefan Nilsson). +* encoding/gob: fix memory corruption. +* encoding/json: document that nil slice encodes as `null`. +* exp/wingui: moved to code.google.com/p/gowingui. +* expvar: add locking to String, and use RWMutex properly throughout, + add missing locking in String methods. +* fmt, log: stop using unicode. +* fmt: minor tweak of package doc to show headings in godoc (thanks Volker Dobler). +* go/build, cmd/go: add support for .syso files. +* go/build: add NoGoError, + add dependency test, + do not parse .syso files (thanks Alex Brainman). +* go/parser: avoid endless loop in case of internal error, + better error synchronization. +* go/printer, gofmt: nicer formatting of multi-line returns. +* go/printer: example for Fprint. +* go/scanner: better panic diagnostic. +* go spec: no known implementation differences anymore, + fix inaccuracy in type identity definition. +* io: better document WriterAt. +* misc/dashboard: remove obsolete package builder code. +* misc/dist: add source archive support, + add windows installer and zip support, + minimum target requirement is 10.6 for Darwin (thanks Shenghou Ma). +* misc/emacs: fix extra indentation after comments that end with a period. +* misc/xcode: example install of language spec for Xcode 4.x (thanks Emil Hessman). +* net, net/rpc, reflect, time: document concurrency guarantees. +* net/http: fix crash with Transport.CloseIdleConnections, + return appropriate errors from ReadRequest. +* net: add skip message to test (thanks Mikio Hara), + disable use of external listen along with other external network uses, + do not use reflect for DNS messages (thanks Rémy Oudompheng), + document ReadMsgUnix, WriteMsgUnix, + fix TestDialTimeout on windows builder, + improve server and file tests (thanks Mikio Hara), + make Dial and Listen behavior consistent across over platforms (thanks Mikio Hara), + remove dependence on bytes, fmt, strconv, + silence another epoll print, + use IANA reserved port to test dial timeout (thanks Mikio Hara). +* os: document FileInfo.Size as system-dependent for irregular files, + fix SameFile to work for directories on windows (thanks Alex Brainman). +* path/filepath/path_test.go: repair and enable TestAbs. +* path/filepath: disable AbsTest on windows, + retrieve real file name in windows EvalSymlinks (thanks Alex Brainman). +* runtime/pprof: disable test on Leopard 64-bit. +* runtime: add Compiler, + fix windows/amd64 exception handler (thanks Alex Brainman), + inline calls to notok, + move runtime.write back to C, + print error on receipt of signal on non-Go thread, + remove unused runtime·signame and runtime·newError, + try extending arena size in 32-bit allocator (thanks Rémy Oudompheng), + wait for main goroutine before setting GOMAXPROCS (thanks Rémy Oudompheng). +* strconv: add table-based isPrint, remove dependence on bytes, unicode, and strings. +* sync/atomic: disable store and load test on a single processor machine (thanks Mikio Hara). +* syscall: fix mkall.sh, mksyscall_linux.pl, and regen for Linux/ARM (thanks Shenghou Ma). +* test/run: use all available cores on ARM system (thanks Shenghou Ma). +* test: actually run them on windows (thanks Alex Brainman), + add inherited interface test to ddd.go, + enable method expression tests in ddd.go, + invoke go command in run.go, + match gccgo error messages for bug388.go, + skip . files in directory. +* testing: do not print 'no tests' when there are examples. +* time: during short test, do not bother tickers take longer than expected (thanks Shenghou Ma), + mention receiver in Unix, UnixNano docs. +* unicode/utf16: remove dependence on package unicode. +* unicode/utf8: remove dependence on unicode. +* windows: make background of gopher icon transparent (thanks Volker Dobler). +</pre> + +<h2 id="2012-03-04">2012-03-04</h2> + +<pre> +This snapshot includes a major re-design of the go/build package. +Its FindTree, ScanDir, Tree, and DirInfo types have been replaced with the +Import and Package types. There is no gofix. Code that uses go/build will need +to be updated manually to use the package's new interface. + +Other changes: +* 6a/6l: add IMUL3Q and SHLDL. +* all: remove unused unexported functions and constants (thanks Rémy Oudompheng). +* build: add GO_ prefix to LDFLAGS and GCFLAGS (thanks Gustavo Niemeyer). +* cmd/cc: fix an out of bounds array access (thanks Anthony Martin), + grow some global arrays. +* cmd/dist: force line-buffering stdout/stderr on Unix (thanks Shenghou Ma), + recognize CC="ccache clang" as clang. +* cmd/go: avoid repeated include dirs (thanks Rémy Oudompheng), + fix -I flag for gc command (thanks Gustavo Niemeyer), + fix verbose command displaying (thanks Gustavo Niemeyer), + fixes for gccgo (thanks Rémy Oudompheng), + many fixes, + test -i should not disable -c (thanks Shenghou Ma). +* cmd/vet: don't give error for Printf("%+5.2e", x) (thanks Shenghou Ma). +* cmd/yacc/units.y: update comment, give better error messages when $GOROOT not set (thanks Shenghou Ma). +* crypto/tls: force OS X target version to 10.6 for API compatibility (thanks Mikkel Krautz). +* crypto/x509: fix typo in Verify documentation (thanks Mikkel Krautz). +* dist: treat CC as one unit (thanks Scott Lawrence). +* doc/go1: add justification discussions to major changes, + minor corrections and updates. +* doc: describe API changes to go/build, + elaborate available checks for cmd/vet (thanks Shenghou Ma), + expand code.html to discuss the go tool in more depth, + instruct FreeBSD/Linux users to rm the old version first, + remove Go for C++ Programmers, + remove roadmap document, + remove tutorial, + update codelab/wiki to Go 1 (thanks Shenghou Ma), +* encoding/gob: fix "// +build" comment for debug.go (thanks Shenghou Ma), + more hardening for lengths of input strings. +* encoding/json: drop MarshalForHTML; gofix calls to Marshal, + escape output from Marshalers. +* encoding/xml: fix anonymous field Unmarshal example (thanks Gustavo Niemeyer), + fix xml test tag usage (thanks Gustavo Niemeyer). +* gc: disallow absolute import paths, + fix escape analysis + inlining + closure bug, + fix string comparisons for new bool rules (thanks Anthony Martin), + reject import paths containing special characters (thanks Anthony Martin). +* go/ast: examples for ast.Print, ast.Inspect. +* go/doc, godoc: fix range of type declarations. +* go/parser: check import path restrictions, + expand test cases for bad import. +* go/printer, gofmt: improved comment placement. +* go/printer: fix printing of variadic function calls (thanks Anthony Martin), + fix test for new import path restrictions (thanks Anthony Martin), + replace multiline logic, + simpler exprList code, more tests. +* godoc: add Examples link to top-level index, + bring back highlighting, selections, and alerts, + consistent placement of documentation sections, + don't show directories w/o packages in flat dir mode, + don't show testdata directories, + fix codewalks. +* gotype: provide -comments flag. +* html/template: make doctype check case-insensitive (thanks Scott Lawrence), + use correct method signature in introduction example (thanks Mike Rosset). +* io: document that I/O is not necessarily safe for parallel access. +* ld: allow more -L options (thanks Shenghou Ma), + fix alignment of rodata section. +* misc: add zsh completion for go tool (thanks Rémy Oudompheng). +* misc/bash: Completion for go tool (thanks Yissakhar Z. Beck). +* misc/dashboard: fix bug in UI template, + record install counts for external packages. +* misc/dist: implement binary distribution scripts in go. +* misc/gobuilder: send commit time in RFC3339 format. +* misc/xcode: move Xcode3 specific files into sub directory. +* net/http/cgi: add an empty response test, + fix empty response. +* net/http/httptest: make Server.Close wait for outstanding requests to finish. +* net/http/httputil: fix DumpRequestOut on https URLs, + make https DumpRequestOut less racy. +* net/http: add overlooked 418 status code, per RFC 2324, + fix ProxyFromEnvironment bug, docs, add tests, + make a test more paranoid & reliable on Windows. +* net/rpc: silence read error on closing connection. +* net: add stubs for NetBSD (thanks Benny Siegert), + make -external flag for tests default to true (thanks Mikio Hara), + reorganize test files (thanks Mikio Hara). +* os: diagnose chdir error during StartProcess, + implement UserTime/SystemTime on windows (thanks Alex Brainman), + implement sameFile on windows (thanks Alex Brainman), + release process handle at the end of windows (*Process).Wait (thanks Alex Brainman), + sleep 5ms after process has exited on windows (thanks Alex Brainman). +* path/filepath: note that SplitList is different from strings.Split, + steer people away from HasPrefix. +* reflect: don't panic comparing functions in DeepEqual. + make Value.Interface return immutable data. +* runtime/pprof: support OS X CPU profiling. +* runtime: add sanity checks to the runtime-gdb.py prettyprinters, + check for ARM syscall failures (thanks Shenghou Ma), + darwin and linux signal masking, + run init on main thread, + size arena to fit in virtual address space limit. +* spec: allow disallow of \uFFFD in import path, + apply method sets, embedding to all types, not just named types, + clarifications around exports, uniqueness of identifiers, + import path implementation restriction, + inside functions, variables must be evaluated, + use the term "lexical token" (rather then "lexical symbol"). +* sync: add Once example, remove old WaitGroup example. +* test/bench/shootout: update post-Makefile. +* test: add documentation, misc fixes. +* testing: add -test.example flag to control execution of examples. +* text/template: add example showing use of custom function, + add examples that use multiple templates, + fix redefinition bugs. +* time: add a comment about how to use the Duration constants. +</pre> + +<h2 id="2012-02-22">2012-02-22</h2> + +<pre> +This weekly snapshot includes changes to the os and runtime packages. + +This should be the last of the significant incompatible changes before Go 1. + +There are no longer error constants such as EINVAL in the os package, since the +set of values varied with the underlying operating system. There are new +portable functions like IsPermission to test common error properties, plus a +few new error values with more Go-like names, such as ErrPermission and +ErrNoEnv. + +The os.Getenverror function has been removed. To distinguish between a +non-existent environment variable and an empty string, use os.Environ or +syscall.Getenv. + +The Process.Wait method has dropped its option argument and the associated +constants are gone from the package. Also, the function Wait is gone; only the +method of the Process type persists. + +The non-portable Waitmsg type has been replaced with the portable ProcessState. + +Much of the API exported by package runtime has been removed in favor of +functionality provided by other packages. Code using the runtime.Type +interface or its specific concrete type implementations should now use package +reflect. Code using runtime.Semacquire or runtime.Semrelease should use +channels or the abstractions in package sync. + +The runtime.Alloc, runtime.Free, and runtime.Lookup functions, an unsafe API +created for debugging the memory allocator, have no replacement. + +The runtime.Cgocalls and runtime.Goroutines functions have been renamed to +runtime.NumCgoCall and runtime.NumGoroutine. + +The "go fix" command will update code to accommodate most of these changes. + +Other changes: +* 5c, 6c, 8c, 6g, 8g: correct boundary checking (thanks Shenghou Ma). +* 5g, 6g, 8g: flush modified globals aggressively. +* 8a, 8l: add EMMS instruction (thanks Evan Shaw). +* bufio: don't return errors from good Peeks. +* build: add make.bash --no-clean option, + improve Windows support. +* builder: reuse existing workspace if possible (thanks Shenghou Ma), + update for os.Wait changes. +* bytes: document Compare/Equal semantics for nil arguments, and add tests. +* cgo: fix definition of opaque types (thanks Gustavo Niemeyer). +* cmd/api: record return type of functions for variable typecheck (thanks Rémy Oudompheng). +* cmd/cgo: bug fixes. +* cmd/dist: add clang specific -Wno options (thanks Bobby Powers), + fix install cmd/5g on non-arm system, + fix pprof permissions (thanks Bobby Powers), + make dir check in defaulttarg() more robust (thanks Shenghou Ma), + use correct package target when cross-compiling (thanks Alex Brainman). +* cmd/gc: correctly typecheck expression lists in returns (thanks Rémy Oudompheng), + don't believe that variables mentioned 256 times are unused (thanks Rémy Oudompheng), + error on constant shift overflows (thanks Rémy Oudompheng), + fix comparison of struct with _ field. + fix error for floating-point constant %, + new, less strict bool rules. +* cmd/go: add tool -n flag, + go test -i correctly handle cgo packages (thanks Shenghou Ma). +* codereview: fix submit message for new clone URL (thanks Shenghou Ma). +* database/sql/driver: API cleanups. +* doc: many fixes and adjustments. +* encoding/gob: cache engine for user type, not base type, + catch internal error when it happens, + fix mutually recursive slices of structs. +* encoding/json: ignore anonymous fields. +* go/doc: return Examples in name order. +* go/parser: imaginary constants and ! may start an expression. +* go/printer, gofmt: improved comma placement. +* go/printer: don't lose relevant parentheses when rewriting selector expressions. +* godoc: adjust line height in pre blocks, + don't print spurious suggestion when running "go doc foo", + fix absolute->relative mapping, + fix tag mismatch validation errors (thanks Scott Lawrence), + import example code support, + support flat directory view again. +* html/template: add Clone and AddParseTree, + don't indirect past a Stringer, + minor tweak to docs to improve HTML typography. +* image: add Decode example. +* ld: add NOPTRBSS for large, pointer-free uninitialized data. +* math/rand: Intn etc. should panic if their argument is <= 0. +* misc/dist/windows: distro builder updates (thanks Joe Poirier). +* misc/goplay: remain in work directory, build in temp directory. +* net, os, syscall: delete os.EPLAN9 (thanks Mikio Hara). +* net/http: add optional Server.TLSConfig field. +* net/smtp: use EHLO then HELO. +* net/textproto: accept bad MIME headers as browsers do. +* net/url: regularise receiver names. +* net: make LocalAddr on multicast return group address (thanks Mikio Hara), + make parseProcNetIGMP more robust (thanks Mikio Hara), + more selfConnect debugging: panic if ra == nil in internetSocket, + panic if sockaddrToTCP returns nil incorrectly, + other miscellaneous fixes. +* path, path/filepath: polish documentation (thanks Rémy Oudompheng). +* pprof: add Profile type. +* runtime: avoid malloc during malloc, + define NSIG to fix plan 9 build (thanks David du Colombier), + fix FreeBSD signal handling around thread creation (thanks Devon H. O'Dell), + goroutine profile, stack dumps, + implement runtime.osyield on FreeBSD 386, amd64 (thanks Devon H. O'Dell), + permit default behaviour of SIGTSTP, SIGTTIN, SIGTTOU, + release unused memory to the OS (thanks Sébastien Paolacci), + remove an obsolete file (thanks Mikio Hara). +* spec: make all comparison results untyped bool, + refine the wording about variables in type switches, + struct comparison only compares non-blank fields. +* syscall: Make Pdeathsig type Signal in SysProcAttr on Linux (thanks Albert Strasheim), + fix bounds check in Error, + force Windows to always use US English error messages (thanks Shenghou Ma). +* test: migrated to new go-based testing framework. +* text/template: evaluate function fields. +* time: use Go distribution zoneinfo if system copy not found. +</pre> + +<h2 id="2012-02-14">2012-02-14</h2> + +<pre> +This release includes some package changes that require changes to client code. + +The flate, gzip and zlib's NewWriterXxx functions no longer return an error. +The compiler will flag all affected code which must then be updated by hand. + +The os package's Exec and Time functions were removed. Callers should use +syscall.Exec and time.Now instead. The ShellExpand function was renamed to +ExpandEnv. The NewFile function now takes a uintptr and the *File.Fd method +returns a uintptr. + +The runtime package's Type type and its methods have been removed. +Use the reflect package instead. + +Other changes: +* 8a, 8l: add LFENCE, MFENCE, SFENCE (thanks Darren Elwood). +* all.bat: report error code back to the gobuilder (thanks Alex Brainman). +* archive/zip: hide Write method from *Writer type. +* build: create the correct $GOTOOLDIR, + get rid of deps.bash (thanks Anthony Martin), + reject make.bash on Windows. +* builder: set $GOBUILDEXIT for Windows (thanks Alex Brainman), +* bytes: add Reader, + return error in WriteTo if buffer is not drained. +* cgo: add support for returning errno with gccgo (thanks Rémy Oudompheng). +* cmd/api: follow constant references. +* cmd/cgo: omit //line in -godefs, -cdefs output. +* cmd/dist: fixes (thanks Alex Brainman, Gustavo Niemeyer, Mikio Hara, Shenghou Ma). +* cmd/fix: warn about exp, old, deleted packages. +* cmd/gc: suspend safemode during typecheck of inlined bodies. +* cmd/go: a raft of fixes, + connect os.Stdin for go run and go tool, + go get scheme detection (thanks Daniel Krech), + respect test -timeout flag. +* cmd/vet: warn for construct 'Println(os.Stderr, ...)' (thanks Shenghou Ma). +* compress/gzip: remove dead code (thanks Alex Brainman). +* container/heap: add example. +* dashboard: add gobuilder -fail mode. +* database/sql: more tests, + remove Into from ScannerInto/ScanInto, + rename ErrTransactionFinished to ErrTxDone, + support ErrSkip in Tx.Exec (thanks Andrew Balholm), + treat pointers as nullable types as with encoding/json (thanks Andrew Pritchard). +* debug/macho: drop terrifyingly monstrous URL from package comment. +* dist: prevent recusive loop on windows when fatal() is called (thanks Daniel Theophanes). +* doc: add App Engine docs to 'learn' and 'reference' pages, + add playground.js, + new document about compatibility of releases, + update install.html for binary distros, add install-source.html. +* effective_go: use new map deletion syntax. +* encoding/binary: add Size, to replace the functionality of the old TotalSize, + another attempt to describe the type of Read and Write's data, + slices are allowed; say so. +* encoding/json: document buffering. +* encoding/xml: add support for the omitempty flag (thanks Gustavo Niemeyer). +* exp/norm: merged charinfo and decomposition tables. +* exp/types: use build.FindTree in GcImporter (thanks James Whitehead). +* flate: delete WrongValueError type. +* fmt: diagnose invalid verb applied to pointer, + scan FALSE correctly. +* gc: bug fixes, better error messages. +* go/doc: handle recursive embedded types (thanks Gary Burd), + don't lose exported consts/vars with unexported type, + treat predeclared error interface like an exported type. +* go/printer: implement SourcePos mode. +* godoc: list examples in index, + new design, + regard lone examples as "whole file" examples. +* html/template: added more words about examples and doc (thanks Bjorn Tipling). +* log/syslog: return length of data provided by the user, not length of header. +* make.bat: remove double quotes (thanks Alex Brainman). +* math: fix gamma doc, link to OEIS. +* mime: unexport some internal details. +* misc/dist: add binary distribution packaging script for linux, + new hierarchy for binary distribution packaging scripts. +* net/http: add ServeContent, + don't spin on temporary accept failure, + fix client goroutine leak with persistent connections, + fix reference to URL.RawPath in docs (thanks Bjorn Tipling), + panic on duplicate registrations, + use mtime < t+1s to check for unmodified (thanks Hong Ruiqi). +* net: avoid Shutdown during Close, + avoid TCP self-connect, + disable TestDialTimeout on Windows, + disable multicast test on Alpha GNU/Linux, + disable wild use of SO_REUSEPORT on BSD variants (thanks Mikio Hara), + enable flags on stream for multicast listeners (thanks Mikio Hara), + make use of listenerBacklog (thanks Mikio Hara), + prefer an IPv4 listen if no address given (thanks Mikio Hara). +* os/exec: add Cmd.Waitmsg. +* os/signal: revive this package. +* regexp/syntax: add package and Parse commentary. +* regexp: allow substitutions in Replace, ReplaceString. +* runtime, pprof: add profiling of thread creation. +* runtime, time: accelerate tests in short mode (thanks Rémy Oudompheng). +* runtime: exit early on OABI systems (thanks Shenghou Ma), + drop to 32 bit malloc if 64 bit will not work, + fix "SysReserve returned unaligned address" bug on 32-bit systems (thanks Shenghou Ma), + fix grsec support (thanks Gustavo Niemeyer), + on 386, fix FP control word on all threads, not just initial thread, + put lockorder before pollorder in Select memory block, + use startpanic so that only one thread handles an incoming SIGQUIT. +* spec: add forward links from 'method set' to where it gets used, + clarify implementation restrictions on untyped floats, + disallow recursive embedded interfaces, + method names must be unique, + send on closed channel counts as "proceeding", + strings are more slices than arrays. +* strconv: handle very large inputs. +* strings: add Seek and ReadAt methods to Reader. +* sync/atomic: disable hammer pointer tests on wrong size system. +* testing: let runtime catch the panic. +* text/template: refer HTML users to html/template. +* text/template/parse: deep Copy method for nodes. +* time: clean up MarshalJSON, add RFC3339 method, + use "2006-01-02 15:04:05.999999999 -0700 MST" as String format. +</pre> + +<h2 id="2012-02-07">2012-02-07</h2> + +<pre> +This weekly snapshot includes a re-organization of the Go tools. + +Only the go, godoc, and gofmt tools are installed to $GOROOT/bin (or $GOBIN). +The remainder are installed to $GOROOT/bin/tool. +This puts the lesser-used tools (6g, cgo, govet, etc.) outside the user PATH. +Instead these tools may be called through the go tool with 'go tool command'. +For example, to vet hello.go you would type 'go tool vet hello.go'. +Type 'go tool' see the list of available tools. + +With the move, some tools were given simpler names: + 6cov -> cov + 6nm -> nm + goapi -> api + gofix -> fix + gopack -> pack + gopprof -> pprof + govet -> vet + goyacc -> yacc + +The os/signal package has been moved to exp/signal. + +A new tool named 'dist' has been introduced to handle building the gc tool +chain and to bootstrap the go tool. The old build scripts and make files +have been removed. + +Other changes: +* 5a, 6a, 8a, cc: check in y.tab.[ch]. +* 5l, 6l, 8l, ld: remove memory leaks (thanks Shenghou Ma). +* 5l, 6l, 8l: implement -X flag. +* 5l: make -v option output less nonessential clutter (thanks Shenghou Ma), + optimize the common case in patch() (thanks Shenghou Ma). +* 8a, 8l: implement support for RDTSC instruction (thanks Shenghou Ma). +* 8g: use uintptr for local pc. +* archive/zip: support full range of FileMode flags (thanks Gustavo Niemeyer). +* bufio: remove special error type, update docs. +* build: move the "-c" flag into HOST_CFLAGS (thanks Anthony Martin), + remove unnecessary pragmas (thanks Anthony Martin). +* builder: drop recover blocks. +* bytes: API tweaks. +* cgo: accept null pointers in gccgo flavour of C.GoString (thanks Rémy Oudompheng), + print line numbers in fatal errors when relevant (thanks Rémy Oudompheng). +* cmd/dist: add GOBIN to env's output (thanks Gustavo Niemeyer), + fix bug in bsubst (thanks Alex Brainman), + fix build on openbsd (thanks Mikio Hara), + generate files for package runtime, + ignore file names beginning with . or _, + prevent race on VERSION creation (thanks Gustavo Niemeyer). +* cmd/gc: another special (%hhS) case for method names, + describe debugging flags (thanks Anthony Martin), + diagnose \ in import path, + disallow switch _ := v.(type), + don't print implicit type on struct literal in export, + fix codegen reordering for expressions involving && and ||, + use octal escapes in mkopnames (thanks Anthony Martin). + use original constant expression in error messages (thanks Rémy Oudompheng). +* cmd/go: add support for release tags via git branches (thanks Gustavo Niemeyer), + build: print import errors when invoked on files (thanks Kyle Lemons), + clean test directories as they complete, + fix error message on non-existing tools (thanks Rémy Oudompheng), + fix handling of gccgo standard library (thanks Rémy Oudompheng), + fixed panic on `go clean -n` and `go clean -x` (thanks Sanjay Menakuru), + introduce support for "go build" with gccgo (thanks Rémy Oudompheng), + make vcs command actually gather output (thanks Roger Peppe), + pass env CGO_CFLAGS to cgo (thanks Jeff Hodges), + record location of failed imports for error reporting (thanks Rémy Oudompheng). +* cmd/goapi: expand embedded interfaces. +* cmd/goinstall: remove now that 'go get' works (thanks Gustavo Niemeyer). +* cmd/ld: fix gdbscript (thanks Wei Guangjing). +* cmd/pack: change gopack to pack in error messages. +* codereview: miscellaneous fixes and improvements. +* crypto/elliptic: p224Contract could produce a non-minimal representation. +* crypto/tls: better error message when connecting to SSLv3 servers. +* crypto/x509: use case-insensitive hostname matching. +* dashboard: support for sub-repositories, update to go1beta. +* database/sql: permit scanning into interface{}. +* doc: update go1.html for recent changes. +* encoding/base32: add DecodeString and EncodeToString helper methods, + ignore new line characters during decode. +* encoding/base64: ignore new line characters during decode. +* encoding/gob: document CommonType. +* encoding/hex: canonicalize error type names. +* encoding/json: call (*T).MarshalJSON for addressable T values. +* encoding/xml: fix decoding of xml.Name with sub-elements (thanks Gustavo Niemeyer), + fix documentation for Decoder.Skip. +* exp/norm: Added some benchmarks for form-specific performance measurements, + a few minor changes in prepration for a table format change. +* expvar: revise API. +* fix: add image/{bmp,tiff} to go1pkgrename. +* flag: allow a FlagSet to not write to os.Stderr, + describe valid input for Duration flags. +* fmt: add test of NaN map keys, + fix caching bug in Scan. +* go/build: put a space between 'generated by make' and package statement, + update syslist.go package comment. +* go/doc: fix URL linking in ToHTML (thanks Gary Burd), + added error, rune to list of predeclared types, + don't lose factory functions of non-exported types, + don't show methods of exported anonymous fields, + enable AllMethods flag (and fix logic). +* go/printer: don't print incorrect programs. +* go/scanner: idiomatic receiver names. +* go/spec: update language on map types. +* go/token: remove dependency on encoding/gob. +* gob: fuzz testing, plus a fix for very large type names. +* gobuilder: use go tool to build and test sub-repositories. +* godoc: add URL mode m=methods, + diagnostic for empty FS tree, + fix identifier search, + fix redirect loop for URL "/", + provide link to subdirectories, if any, + sort list of "other packages", + update metadata in appinit.go. +* gophertool: fix link to the build status dashboard (thanks Jongmin Kim). +* hgignore: add VERSION.cache (thanks Gustavo Niemeyer), + delete dregs, ignore tmpltohtml. +* html: add package doc. +* image: add package docs, rename s/UnknownFormatError/ErrFormat/ and, + delete the image.Repeated type, + remove image/bmp and image/tiff from std. +* io/ioutil: document EOF behavior in ReadFile and ReadAll. +* io: API tweaks. +* libmach: add stubs for Plan 9 (thanks Anthony Martin). +* make.bash: don't remove hgpatch. +* math/big: add raw access to Int bits, + API and documentation cleanup. +* misc/goplay: use go tool "run" (thanks Olivier Duperray). +* misc/osx: don't set GOROOT or modify profile files, + update for dist tool, drop image.bash, update readme. +* net, syscall: add IPv4 multicast helpers for windows (thanks Mikio Hara). +* net/http/httputil: fix race in DumpRequestOut, + preserve query params in reverse proxy. +* net/http: don't set Content-Type header for HEAD requests by default (thanks Patrick Mylund Nielsen), + fix nil pointer dereference in error case (thanks Volker Dobler), + close client fd sooner on response read error, + set cookies in client jar on POST requests (thanks Volker Dobler). +* net/rpc: fix data race on Call.Error. +* net: ListenMulticastUDP to listen concurrently across multiple listeners (thanks Mikio Hara), + disable normal multicast testing on linux/arm (thanks Mikio Hara), + fix Plan 9 build (thanks Anthony Martin), + fix windows build (thanks Alex Brainman), + move DNSConfigError to a portable file, + remove types InvalidConnError and UnknownSocketError, + replace error variable name e, errno with err (thanks Mikio Hara), + run TestDialTimeout on windows (thanks Alex Brainman), + update comments to remove redundant "net" prefix (thanks Mikio Hara). +* os/exec: TestExtraFiles - close any leaked file descriptors, + make sure file is not closed early in leaked fd test. +* os/signal: move to exp/signal. +* os/user: windows implementation (thanks Alex Brainman). +* os: Process.handle use syscall.Handle (thanks Wei Guangjing), + file windows use syscall.InvalidHandle instead of -1 (thanks Wei Guangjing), + remove SIGXXX signals variables, + turn FileStat.Sys into a method on FileInfo (thanks Gustavo Niemeyer). +* path/filepath: repair and simplify the symlink test. +* reflect: add comment about Type.Field allocation, + test that PtrTo returns types that match program types. +* runtime: add runtime.cputicks() and seed fastrand with it (thanks Damian Gryski), + delete UpdateMemStats, replace with ReadMemStats(&stats) (thanks Rémy Oudompheng), + fix float64 hash, + use GOTRACEBACK to decide whether to show runtime frames, + use per-map hash seeds (thanks Damian Gryski). +* spec: add number to the fibonacci sequence. +* std: add struct field tags to untagged literals. +* strings: add Fields example. +* syscall: add Timeval.Nano, Timespec.Nano, for conversion to Duration, + cache environment variables on Plan 9 (thanks Anthony Martin), + fix // +build comments in types_*.go, + fix build directive in types_linux.go, + update bootstrap scripts to sync with new go command (thanks Mikio Hara). +* test: add import test that caused an incorrect gccgo error, + add test for receiver named _, + add test of NaN in map, + add test which crashed gccgo compiler, + don't use package main for files without a main function, + fix bug headers, + float to integer test case, + make map nan timing test more robust, + match gccgo error messages, + test append with two different named types with same element type, + test method expressions with parameters, and with import, + test slice beyond len, + test that x := <-c accepts a general expression. +* testing: capture panics, present them, and mark the test as a failure. +* unicode: document large var blocks and the SpecialCase vars. +* vet: add a check for untagged struct literals. +</pre> + +<h2 id="2012-01-27">2012-01-27</h2> + +<pre> +This weekly snapshot renamed the html package to exp/html. The package will not +be present in the Go 1 distribution, but will be installable from source. + +Error variables in the archive/tar, archive/zip, compress/gzip, compress/zlib, +and crypto/bcrypt packages have been renamed from FooError to ErrFoo. +There is no gofix, but the compiler will flag code that needs updating. + +This weekly snapshot relocates many packages to sub-repositories of the main +Go repository. These are the old and new import paths: + + crypto/bcrypt code.google.com/p/go.crypto/bcrypt + crypto/blowfish code.google.com/p/go.crypto/blowfish + crypto/cast5 code.google.com/p/go.crypto/cast5 + crypto/md4 code.google.com/p/go.crypto/md4 + crypto/ocsp code.google.com/p/go.crypto/ocsp + crypto/openpgp code.google.com/p/go.crypto/openpgp + crypto/openpgp/armor code.google.com/p/go.crypto/openpgp/armor + crypto/openpgp/elgamal code.google.com/p/go.crypto/openpgp/elgamal + crypto/openpgp/errors code.google.com/p/go.crypto/openpgp/errors + crypto/openpgp/packet code.google.com/p/go.crypto/openpgp/packet + crypto/openpgp/s2k code.google.com/p/go.crypto/openpgp/s2k + crypto/ripemd160 code.google.com/p/go.crypto/ripemd160 + crypto/twofish code.google.com/p/go.crypto/twofish + crypto/xtea code.google.com/p/go.crypto/xtea + exp/ssh code.google.com/p/go.crypto/ssh + net/dict code.google.com/p/go.net/dict + net/websocket code.google.com/p/go.net/websocket + exp/spdy code.google.com/p/go.net/spdy + encoding/git85 code.google.com/p/go.codereview/git85 + patch code.google.com/p/go.codereview/patch + +Gofix will update imports of these packages to use the new import paths. +Installations that depend on these packages will need to install them using a +'go get' command. + +Other changes: +* 6c, 8c: make floating point code NaN-safe. +* 6l, 8l: remove unused macro definition (thanks Shenghou Ma). +* archive/tar: fix race in TestNonSeekable. +* archive/zip: add functions to convert between os.FileInfo & FileHeader. +* build: do not build all C compilers (thanks Shenghou Ma), + remove code now in subrepositories. +* bytes: remove dead code, complete documentation, + restore panic on out-of-memory, + turn buffer size overflows into errors. +* cgo: -cdefs should translate unsafe.Pointer to void * (thanks Shenghou Ma). +* cmd/gc: forgotten recursion on ninit itself in order.c. +* cmd/go: bug fixes, implement go get, + correctly handle -n and -x flags for 'go run' (thanks Shenghou Ma), + solve ambiguity of get lp.net/project/foo (thanks Gustavo Niemeyer), + update doc.go with text generated from the usage strings. +* cmd/goapi: new tool for tracking exported API over time. +* codereview: support for subrepositories. +* compress/flate: fix a typo, improve compression rate by 3-4%, + increase the length of hash table from 1<<15 to 1<<17. 0%-16% speedup, + make lazy matching work, + reduce memory pressure at cost of additional arithmetic operation, + use append instead of slice+counter. +* crypto: rename some FooError to ErrFoo. +* dashboard: fix -commit for new xml package. +* database/sql: add NullInt64, NullFloat64, NullBool (thanks James P. Cooper), + convert SQL null values to []byte as nil (thanks James P. Cooper), + fix Tx.Query (thanks Blake Mizerany). +* doc: expand FAQ on GOMAXPROCS, update to Go 1. +* doc/go1: add encoding/xml and net/url changes (thanks Gustavo Niemeyer), + add more info about hash and net changes, delete reference to html, + add flag, runtime, testing, image , mime, filepath.Walk, + document sub-repositories. +* encoding/binary: document that PutVarint, PutUvarint may panic. +* encoding/varint: deleted WriteXvarint. +* encoding/xml: add docs for ignoring tag (thanks Gustavo Niemeyer), + bring API closer to other packages (thanks Gustavo Niemeyer), + improve []byte handling (thanks Gustavo Niemeyer), + remove Marshaler support (thanks Gustavo Niemeyer), + support ignoring fields with "-" (thanks Gustavo Niemeyer). +* exp/ebnflint: test spec during 'go test'. +* exp/norm: fixes a subtle bug introduced by change 10087: random offset. +* gc, runtime: handle floating point map keys. +* gc: avoid DOT in error messages, + do not try to add a key with incorrect type to a hash (thanks Jeff R. Allen), + fix order of evaluation, + fix recursion loop in interface comparison, + handle function calls in arguments to builtin complex operations, + missed typecheck in subscripting a const string, + permit unsafe.Pointer for inlined functions, + softer criteria for inlinability, + static implements check on typeswitches only applies to concrete case types, + test case for recursive interface bug. +* go/ast: respect ImportSpec.EndPos (thanks Scott Lawrence). +* go/build: add BuildTags to Context, allow !tag. +* go/doc: rewrite and add lots of tests. +* go/parser: use explicit parser.Mode type. +* go/printer, gofmt: respect line breaks in signatures. +* go/scanner: use explicit scanner.Mode type. +* gob: annotate debug.go so it's not normally built, + reduce the maximum message size. +* godoc: log node printing error, + move overview before API TOC, + update metadata upon launch. +* gofix: add -debug flag for quicker diagnosis of internal errors, + handle xml.Unmarshal in xmlapi fix (thanks Gustavo Niemeyer), + update go1pkgrename for subrepositories. +* goyacc: fix indexing bug when yydebug >= 2. +* ld: fix Mach-O code signing for non-cgo binaries (thanks Mikkel Krautz). +* libmach: cross compiling support (thanks Shenghou Ma). +* math/big: assembly versions of bitLen for x86-64, 386, and ARM (thanks David G. Andersen), + return type of bitLen is an int; use MOVL on amd64 (thanks David G. Andersen), + add examples for Rat and Int's SetString and Scan methods, + slight improvement to algorithm used for internal bitLen function (thanks David G. Andersen), + test both bitLen and bitLen_g. +* net/http: add Request.RequestURI field, + disabled test for Transport race / deadlock bug, + fix Transport deadlock (thanks Yoshiyuki Kanno), + make ParseForm ignore unknown content types (thanks Roger Peppe), + parse CONNECT requests (thanks Andrew Balholm). +* net/rpc: fix data race in benchmark, + fix race in TestClientWriteError test, + log Call reply discard. +* net: Dial, ListenPacket with "ip:protocol" network for raw IP sockets (thanks Mikio Hara), + actually reset deadline when time is zero, + consistent OpError message (thanks Mikio Hara), + fix dialing google test (thanks Mikio Hara), + make WriteTo fail when UDPConn is already connected (thanks Mikio Hara). +* regexp: remove vestigial Error type. +* runtime: add type algorithms for zero-sized types, + move NumCPU declaration into debug.go. +* spec: function invocation, panic on *nil. +* syscall: add NOTE_* constants on OS X (thanks Robert Figueiredo). +* test: explicitly use variables to avoid gccgo "not used" error. +* text/template: add example for Template. +</pre> + +<h2 id="2012-01-20">2012-01-20</h2> + +<pre> +This weekly snapshot renamed the exp/sql package to database/sql, and moved +utf8.String from unicode/utf8 to exp/utf8string. + +Package net's SetTimeout methods were changed to SetDeadline. + +Many functions in package os now take a os.FileMode argument instead of a +plain uint32. An os.ModeSticky constant is also now defined. + +The meaning of the first buffer element for image.YCbCr has changed to match +the semantics of the other image types like image.RGBA. + +The NewMD5, NewSHA1 and NewSHA256 functions in crypto/hmac have been +deprecated. Use New instead, explicitly passing the hash function. + +Other changes: +* buildscripts: move to buildscript directory (thanks Shenghou Ma). +* bytes: add the usual copyright notice to example_test.go (thanks Olivier Duperray). +* cmd/go: remove mentions of 'gotest' from the documentation, + skip _obj directories in package scans. +* container/heap: better package documentation. +* crypto/elliptic: add constant-time P224. +* crypto/hmac: Add HMAC-SHA224 and HMAC-SHA384/512 (thanks Luit van Drongelen), +* crypto/tls: add FreeBSD root certificate location (thanks Shenghou Ma). +* crypto/x509: remove explicit uses of rsa. +* doc: various updates (thanks Jongmin Kim, Scott Lawrence, Shenghou Ma, Stefan Nilsson). +* encoding/json: allow / and % in tag names, + document angle bracket escaping, + fix comments, tweak tests for tag names (thanks Mikio Hara). +* encoding/xml: marshal/unmarshal xml.Name in field (thanks Gustavo Niemeyer). +* exp/inotify: fix data race in linux tests. +* exp/proxy: fix build after URL changes (thanks Gustavo Niemeyer). +* exp/sql: copy when scanning into []byte by default, + rename NullableString to NullString and allow its use as a parameter. +* exp/ssh: add marshal functions for uint32 and uint64 types, + handle versions with just '\n', + rename (some) fields (thanks Christopher Wedgwood). +* exp/terminal: fix build on non-Linux using Makefiles. +* fmt: enable and fix malloc test, +* gc: don't emit pkgpath for error type, + don't fault on return outside function (thanks Scott Lawrence), + fieldnames in structliterals in exported inlines should not be qualified if they're embedded builtin types, + fix infinite recursion for embedded interfaces, + give esc.c's sink an orig so -mm diagnostics work again, + handle printing of string/arrayrune conversions. + remove redundant code (thanks Shenghou Ma). +* go/build: no back slash in FindTree returned pkg name (thanks Alex Brainman). +* go/doc: collect imports, + don't shadow receiver. + rewrote and completed test framework. + print only one newline between paragraphs +* go/parser: expressions may have comments. +* go/scanner: fix example (thanks Olivier Duperray). +* go/token: replaced Files() with Iterate(). +* godoc: add anchors to cmd documentation headings, + remove "need more packages?" link, + specify HTML page metadata with a JSON blob, + support canonical Paths in HTML metadata. +* html/template: fix docs after API changes (thanks Gustavo Niemeyer). +* html: in foreign content, check for HTML integration points in breakout. +* image/color: rename modelYCbCr to yCbCrModel (thanks Benny Siegert), + simplify documentation (thanks David Crawshaw). +* image: add PixOffset methods. +* math/rand: decrease test duration in short mode, + document default initial seed for global generator (thanks Scott Lawrence). +* mime: make FormatMediaType take full type for consistency. +* misc/cgo/test: make tests run on windows (thanks Alex Brainman). +* net/http/cgi: increase a flaky test timeout. +* net/http: change test to use override param instead of chan, + log handler panic before closing HTTP connection, + send cookies in jar on redirect (thanks Jeff Hodges), + the documentation should call NewRequest with the right signature (thanks Christoph Hack), + update the Client docs a bit. +* net/url: cleaned up URL interface (v2) (thanks Gustavo Niemeyer). +* net: consistent log format in test (thanks Mikio Hara), + various build fixes (thanks Mikio Hara), + use NewTimer, not NewTicker, in fd_windows.go. +* old/netchan: fix data race on client hashmap. +* os/exec: trivial allocation removal in LookPath (thanks Gustavo Niemeyer). +* os: remove old note about NewSyscallError being special (thanks Alex Brainman), +* path: added examples (thanks Sanjay Menakuru). +* pkg: Add and fix Copyright of "hand generated" files (thanks Olivier Duperray), + add missing godoc comments to windows versions (thanks Alex Brainman). +* regexp: add SubexpNames. +* runtime: implement runtime.usleep for FreeBSD/386 and amd64 (thanks Shenghou Ma), + madvise and SysUnused for Darwin (thanks Dave Cheney). +* sync/atomic: fix data race in tests. +* syscall: add Unix method to TimeSpec, TimeVal, + fix plan9 build (thanks Mikio Hara). +* test: change several tests to not print, + fix bug364 to actually run, + match gccgo error messages for bug345, + split golden.out into expected output per test. +* testing: do not recover example's panic (thanks Shenghou Ma), + document examples. +* text/template/parse: use human error prints. +* text/template: fix nil error on redefinition. +* time: add Since, which returns the time elapsed since some past time t. +</pre> + +<h2 id="2012-01-15">2012-01-15</h2> + +<pre> +This weekly snapshot includes two package changes that may require changes to +client code. + +The image package's Tiled type has been renamed to Repeated. + +The encoding/xml package has been changed to make more idiomatic use of struct +tags, among other things. If you use the xml package please read the change +description to see if your code is affected: + http://code.google.com/p/go/source/detail?r=70e914beb409 + +Function inlining is now enabled by default in the gc compiler. + +Other changes: +* bytes: Buffer read of 0 bytes at EOF shouldn't be an EOF. +* cgo: if value for constant did not parse, get it from DWARF info, + write _cgo_export.h to object directory, not source dir. +* cmd/go: add -p flag for parallelism (like make -j), + add -v flag to build and install, + add ... patterns in import path arguments, + fix data race during build, + fix import directory list for compilation, + fix linker arguments, + handle cgo pkg-config pragmas, + handle path to cmd directory, + include test files in fmt, vet, and fix (thanks Sanjay Menakuru), + kill test processes after 10 minutes, + pass arguments to command for run (thanks Eric Eisner), + rely on exit code to tell if test passed, + use relative paths in go fix, go fmt, go vet output. +* cmd/gofmt: fix simplify.go by running gofmt on cmd/gofmt (thanks Olivier Duperray). +* crypto/openpgp: assorted cleanups, + truncate hashes before checking DSA signatures. +* crypto/tls: improve TLS Client Authentication (thanks Jeff R. Allen), + update generate_cert.go for new time package. +* dashboard: better caching, bug fixes. +* doc: update "How to Write Go Code" to use the go tool. + fix broken function codewalk examples. +* encoding/asn1: document support for *big.Int (thanks Florian Weimer). +* encoding/gob: fix panic when decoding []byte to incompatible slice types (thanks Alexey Borzenkov). +* encoding/json: don't marshal special float values (thanks Evan Shaw). +* encoding/xml: major Go 1 fixup (thanks Gustavo Niemeyer). +* exp/proxy: new package. +* exp/sql: add time.Time support, + close Rows on EOF, + fix potential corruption in QueryRow.Scan into a *[]byte. +* exp/ssh: various small fixes (thanks Dave Cheney). +* exp/terminal: add SetPrompt and handle large pastes, + add to level Makefile for the (non-Linux?) systems that need it. +* flag: add Duration flag type, + change Set method Value interface to return error instead of bool. +* gc: better errors messages, + avoid false positives when using scalar struct fields (thanks Rémy Oudompheng), + closure code gen improvements, + disallow declaration of variables outside package, + fix switch on interface values (thanks Rémy Oudompheng), + inlining bug fixes, + improve unsafe.Pointer type-check error messages (thanks Ryan Hitchman), + put limit on size of exported recursive interface (thanks Lorenzo Stoakes), +* go-mode.el: fix syntax highlighting of backticks (thanks Florian Weimer). +* go/ast: remove unnecessary result value from ast.Fprint/Print. +* go/build: allow colon in #cgo flags, + pass CgoLDFLAGS at end of link command. +* go/doc: new API, don't ignore anonymous non-exported fields, initial testing support. +* go/parser: remove unused Parse* functions. Simplified ParseExpr signature. +* go/printer: don't crash if AST contains BadXXX nodes. +* go/scanner: 17% faster scanning, remove InsertSemis mode. +* goinstall: use correct checkout URL for Google Code svn repos. +* gotest: make _testmain.go conform to gofmt rules (thanks Benny Siegert). +* goyacc: fix units.y build breakage (thanks Shenghou Ma). +* html/template: reenable testcases and fix mis-escaped sequences (thanks Mike Samuel). +* html: "in select in table" insertion mode (thanks Andrew Balholm), + adjust foreign attributes, + foreign element HTML integration points, tag name adjustment, + parse <frameset> inside body (thanks Andrew Balholm), + propagate foreign namespaces only when adding foreign content. +* json: better error messages when the ,string option is misused. +* ld: parse but do not implement -X flag. +* log/syslog: add Alert method (thanks Vadim Vygonets). +* make.bash: remove old dregs (thanks Alex Brainman). +* math/big: simplify fast string conversion. +* math: fix typo in all_test.go (thanks Charles L. Dorian). +* misc/windows: add src/pkg/runtime/z* files to installation script (thanks Alex Brainman). +* net/http: don't ignore Request.Write's Flush error, + allow cookies with negative Max-Age attribute as these are (thanks Volker Dobler). +* net/textproto: avoid corruption when reading a single header. +* net: add IP-level socket option helpers for Unix variants (thanks Mikio Hara), + fix incorrect mode on ListenIP, ListenUDP (thanks Mikio Hara), + make use of the kernel state to listen on TCP, Unix (thanks Mikio Hara), + platform-dependent default socket options (thanks Mikio Hara). +* os: add ModeCharDevice. +* runtime: add NumCPU, + delete duplicate implementation of pcln walker, + distinct panic message for call of nil func value, + enable runtime.ncpu on FreeBSD (thanks Devon H. O'Dell), + make garbage collector faster by deleting code, + regenerate defs_darwin_{386,amd64}.h (thanks Dave Cheney), + runtime.usleep() bugfix on darwin/amd64 and linux/arm (thanks Shenghou Ma). +* spec: pointer comparison for pointers to 0-sized variables, + change the wording regarding select statement choice. +* strconv: fix round up corner case, + faster FormatFloat(x, *, -1, 64) using Grisu3 algorithm (thanks Rémy Oudompheng), + implement fast path for rounding already short numbers (thanks Rémy Oudompheng), + return ErrSyntax when unquoting illegal octal sequences. +* syscall: linux-only support for parent death signal (thanks Albert Strasheim), + make Environ return original order. +* testing: fix defer race, + use flag.Duration for -timeout flag. +* text/template: handle panic values that are not errors (thanks Rémy Oudompheng), + for range on a map, sort the keys if feasible. +* time: add ParseDuration, + fix docs for After and NewTicker. +* windows: use ArbitraryUserPointer as TLS slot (thanks Wei Guangjing). +</pre> + +<h2 id="2011-12-22">2011-12-22</h2> + +<pre> +This snapshot includes changes to the images/ycbcr and testing packages, and +changes to the build system. + +The types for managing Y'CbCr images in the image/ycbcr have been moved to the +image and image/color packages. A gofix module will rewrite affected code. + +The testing package's B type (used when running benchmarks) now has the same +methods as T (used in tests), such as Print, Error, and Fatal. + +This weekly adds a new command named 'go' for building and testing go programs. +For Go 1, the go command will replace the makefile-based approach that we have +been using. It is not yet ready for general use, but all.bash does use it to +build the tree. If you have problems building the weekly, you can 'export +USE_GO_TOOL=false' before running all.bash to fall back to the makefiles. + +Other changes: +* archive/zip: add SetModTime method to FileHeader. +* build: make use of env (thanks Mikio Hara), + fixes to make "go install" work on windows (thanks Alex Brainman). +* bytes: add two Buffer examples. +* cgo: support export for built-in types (thanks Maxim Pimenov). +* cmd/go: avoid infinite loop with package specific flags (thanks Mikio Hara), + fixes to build standard library, + implement test command, + make sure use of pthread for gcc-4.5 and beyond (thanks Mikio Hara), + respect $GCFLAGS, + use spaces consistently in help message (thanks Roger Peppe), + many other improvements. +* codereview: initialize "found" in codereview.py (thanks Miki Tebeka). +* crypto/mime/net/time: add netbsd to +build tags (thanks Joel Sing). +* crypto/tls: don't assume an RSA private key in the API. +* crypto/x509: don't crash with nil receiver in accessor method. +* doc/effective_go: discuss redeclaration. +* doc: delete go course notes, + refer to http://build.golang.org/ where applicable (thanks Robert Hencke), + suggest code.google.com/p/go instead of go.googlecode.com/hg. +* encoding/binary: add Write and Read examples, + add more benchmarks (thanks Roger Peppe). +* encoding/gob: arrays are zero only if their elements are zero. +* encoding/json: cleanup leftover variables in array decoding (thanks Rémy Oudompheng), + examples for Marshal and Unmarshal. +* exp/ssh: rename ClientAuthPublicKey helper ClientAuthKeyring (thanks Dave Cheney), + simplify Stdin/out/errPipe methods (thanks Dave Cheney). +* fmt: speed up floating point print, clean up some code, + make the malloc test check its counts. +* gc: allow use of unsafe.Pointer in generated code, + avoid unsafe in defn of package runtime, + better linenumbers for inlined functions, + better loopdepth analysis for labels, + implement and test \r in raw strings, + inlining, allow empty bodies, fix _ arguments, + omit argument names from function types in error messages. +* go/ast, parser: remember short variable decls. w/ correspoding ident objects. +* go/build: add new +build tags 'cgo' and 'nocgo'. +* go/doc, godoc: move export filtering into go/doc +* go/printer, gofmt: fine tuning of line spacing. +* go/scanner: strip CRs from raw literals. +* gob: isZero for struct values. +* godoc: allow examples for methods (thanks Volker Dobler), + show methods of anonymous fields. +* goinstall: only suggest -fix for bad imports when appropriate. +* govet: add checking for printf verbs, + divide the program into one file per vetting suite. +* html: more parser improvements (thanks Andrew Balholm). +* json: some tests to demonstrate bad error messages, + use strconv.Append variants to avoid allocations in encoding. +* ld: add support for netbsd signature note section (thanks Joel Sing), + allow for IMAGE_REL_AMD64_ADDR32NB relocation type (thanks Alex Brainman). +* math/big: Rand shouldn't hang if argument is also receiver. +* misc/builder: set default builder host to build.golang.org. +* misc/dashboard: delete old build dashboard code , + improvements and fixes for the go implementation. +* misc/vim: fix go filetype detection (thanks Paul Sbarra). +* net, syscall, os: set CLOEXEC flag on epoll/kqueue descriptor. +* net, syscall: interface address and mask (thanks Mikio Hara). +* net/http: added interface for a cookie jar (thanks Volker Dobler), + test fixes (thanks Alex Brainman). +* net: add DialTimeout, + sort Makefile entries (thanks Mikio Hara). +* os, syscall: beginnings of NetBSD support (thanks Christopher Nielsen). +* os/exec: add test to verify net package's epoll fd doesn't go to child, + disable the ExtraFiles test on darwin. +* os: don't trust O_CLOEXEC on OS X, + make sure Remove returns correct error on windows (thanks Alex Brainman). +* path, path/filepath: add Dir to complement Base. +* path/filepath.Rel: document that the returned path is always relative. +* runtime: don't panic on SIGILL, just crash. +* spec: be precise about newlines. +* sql: add Rows.Columns. +* strconv: fix bug in extended-float based conversion, + implement faster parsing of decimal numbers, and + reduce buffer size for multi-precision decimals (thanks Rémy Oudompheng). +* syscall: regenerate z-files for linux/arm (thanks Mikio Hara), + sort Makefile, mkall.sh and mkerrors.sh entries (thanks Mikio Hara). +* test/bench/go1: first draft of Go 1 benchmark suite. +* testing: compare Log to Println (thanks Robert Hencke), + make signalling safer for parallel tests. +* text/template: better error message for empty templates, + fix handing of nil arguments to functions (thanks Gustavo Niemeyer). +* time: add JSON marshaler for Time (thanks Robert Hencke), + new AddDate method (thanks Roger Peppe). +* various: use $GCFLAGS and $GCIMPORTS like Make does (thanks Maxim Pimenov). +</pre> + +<h2 id="2011-12-14">2011-12-14</h2> + +<pre> +This snapshot includes language changes and changes to goinstall and gofmt. + +Equality and inequality (== and !=) are now defined for struct and array +values, respectively, provided the elements of the data structures can +themselves be compared. See the Go 1 release notes for the details: + http://weekly.golang.org/doc/go1.html#equality + +The rune type is now an alias for int32 and character literals have the default +type of rune. Code that uses int where it should use rune will break. +See the Go 1 release notes for the details: + http://weekly.golang.org/doc/go1.html#rune + +Goinstall now expects Google Code import paths to be of the form: + "code.google.com/p/go-tour/tree" +It will reject imports in the old style "go-tour.googlecode.com/hg/tree". +There is a gofix module to rename such imports. +Use goinstall -fix to update broken packages. + +Gofmt's flags have been modified slightly. +The -tabintent flag has been renamed -tabs. +The -spaces flag has been removed. + +Other changes: +* 5c, 6c, 8c: support 64-bit switch value (thanks Anthony Martin). +* 8c: handle 64-bit switch value. +* archive/tar: use struct comparison not DeepEqual (thanks Christopher Wedgwood). +* archive/zip: make zip understand os.FileMode (thanks Roger Peppe). +* bufio: make the minimum read buffer size 16 bytes. +* build: disable cgo on Windows/amd64, + regularize packages so they may be built without Makefiles. +* bytes: faster Count, Index, Equal. +* cgo: add basic gccgo support (thanks Rémy Oudompheng). +* codereview: fix path slash issue (thanks Yasuhiro Matsumoto). +* compress/flate: fix out of bounds error. +* contribute.html: do not fill in the reviewer field (thanks Florian Weimer). +* crypto/aes: made faster by eliminating some indirection (thanks Taru Karttunen). +* crypto/dsa: don't truncate input hashes. +* doc/go_tutorial: make clear the file example is Unix-specific. +* doc: add Defer, Panic, and Recover article, + add Error Handling article, + add Go 1 release notes document. +* encoding/gob: better error messages when types mismatch. +* env.bash: export CGO_ENABLED so cgo tests run (thanks Alex Brainman). +* exp/sql: simplify some string conversions. +* exp/ssh: Wait returns an *ExitError (thanks Gustav Paul). +* exp/ssh: improve client channel close behavior (thanks Dave Cheney). +* fmt: don't recur if String method (etc.) misbehaves. +* gc: better error messages, + inlining (disabled without -l), + many bug fixes (thanks Lucio De Re and Rémy Oudompheng). +* go/printer, godoc: print comments in example code. +* go: implement doc, fmt, fix, list, vet, build, and install. +* gobuilder: goinstall packages after building go tree. +* godoc: <pre> must not occur inside <p> (thanks Olivier Duperray), + added an opensearch description document (thanks Christoph Hack), + text wrapping. +* gofix: add httputil fix (thanks Yasuhiro Matsumoto). +* gotest: use go/build more (thanks Robert Hencke). +* gzip: convert between Latin-1 and Unicode (thanks Vadim Vygonets). +* html/template: define the FuncMap type locally. +* html: a first step at parsing foreign content (MathML, SVG), + more parser improvements (thanks Andrew Balholm). +* http: close connection after printing panic stack trace (thanks Roger Peppe), + fix failing Transport HEAD request with gzip-looking response. +* json: treat renamed byte slices the same as []byte. +* ld: first pass at linker support for NetBSD binaries (thanks Christopher Nielsen), + fix memory leaks (thanks Scott Lawrence), + increase default stack size on Windows for cgo. +* math: delete non-Sqrt-based Hypot, + implement, document, and fix special cases (thanks Charles L. Dorian), +* misc/benchcmp: don't require "Benchmark" at beginning of line. +* misc/osx: rename profile.go to profile_go (thanks Scott Lawrence). +* net/http: fix trivial example server (thanks Olivier Duperray), + net/http: make test remove temporary file and directory. +* net/smtp: add CRAM-MD5 authentication (thanks Vadim Vygonets). +* reflect: fix Slice cap (thanks Gustavo Niemeyer). +* regexp: performance improvements; avoid allocation of input interface. +* runtime: bump gc 'extra bytes' check (thanks Christopher Wedgwood), + madvise and SysUnused for Linux (thanks Sébastien Paolacci), + make gc_test test extra allocated space, not total space, + support for NetBSD (thanks Christopher Nielsen). +* spec: adjust complex constant example (thanks Robert Hencke), + values of underlying type uintptr can be converted to unsafe.Pointer, + var x = 'a' defaults to type rune. +* strconv: include package and function name in error strings, + make QuoteRune etc. take a rune argument, + some performance improvements. +* syscall: add constants for flock() system call under Linux, + regenerate z-files for darwin, freebsd (thanks Mikio Hara), + regenerate z-files for openbsd, + return error, not uintptr, when function returns error (thanks Alex Brainman). +* test/bench: move to test/bench/shootout. +* test/garbage: move to test/bench/garbage. +* test: make array smaller in nilptr test. +* time: allow sleep tests to run for 200% too long, + fix Time.Add (thanks Hector Chu), + fix daysIn for December (thanks Peter Mundy), + gob marshaler for Time (thanks Robert Hencke), + use Duration for AfterFunc. +* various: a grab-bag of time.Duration cleanups. +</pre> + +<h2 id="2011-12-06">2011-12-06</h2> + +<pre> +This snapshot includes a language change and changes to the strconv and go/doc +packages. The package changes require changes to client code. +The language change is backwards-compatible. + +Type elision in arrays, slices, or maps of composite literals has been +extended to include pointers to composite literals. Code like this + var t = []*T{&T{}, &T{}} +may now be written as + var t = []*T{{}, {}} +You can use gofmt -s to simplify such code. + +The strconv package has been given a more idiomatic and efficient interface. +Client code can be updated with gofix. See the docs for the details: + http://weekly.golang.org/pkg/strconv/ + +The go/doc package's ToHTML function now takes a []byte argument instead of a +string. + +Other changes: +* crypto/aes: eliminate some bounds checking and truncation (thanks Rémy Oudompheng). +* crypto/x509: if a parent cert has a raw subject, use it. +* encoding/gob: don't send type info for unexported fields. +* exp/ssh: allow for msgUserAuthBanner during authentication (thanks Gustav Paul). +* fmt: benchmark floating point, + only use Stringer or Error for strings. +* gc: changes in export format in preparation of inlining, + disallow map/func equality via interface comparison, + use gofmt spacing when printing map type. +* go/doc: exclude lines ending in ':' from possible headings. +* gobuilder: -commit mode for packages, + cripple -package mode temporarily, + use new dashboard protocol. +* godoc: improved output of examples in html (thanks Volker Dobler). +* gofmt: handle &T in composite literal simplify. +* goinstall: honour -install=false flag when -make=true. +* hash: rewrite comment on Hash.Sum method. +* html: more parser improvements (thanks Andrew Balholm). +* image: avoid func comparison during ColorModel comparison. +* math: add special-cases comments to Sinh and Tanh (thanks Charles L. Dorian). +* misc/dashboard: further implementation work. +* net, syscall: remove BindToDevice from UDPConn, IPConn (thanks Mikio Hara). +* net/mail: correctly compare parsed times in the test. +* os/exec: make LookPath always search CWD under Windows (thanks Benny Siegert). +* runtime: prep for type-specific algorithms. +* strconv: 34% to 63% faster conversions. +</pre> + +<h2 id="2011-12-02">2011-12-02</h2> + +<pre> +This weekly snapshot includes changes to the hash package and a gofix for the +time and os.FileInfo changes in the last snapshot. + +The hash.Hash's Sum method has been given a []byte argument, +permitting the user to append the hash to an existing byte slice. +Existing code that uses Sum can pass nil as the argument. +Gofix will make this change automatically. + +Other changes: +* crypto/tls: cleanup certificate load on windows (thanks Alex Brainman). +* exp/ssh: add Std{in,out,err}Pipe methods to Session (thanks Dave Cheney). +* dashboard: don't choke on weird builder names. +* exp/ssh: export type signal, now Signal (thanks Gustav Paul). +* os: add ModeType constant to mask file type bits (thanks Gustavo Niemeyer). +* text/template: replace Add with AddParseTree. +* go/doc: detect headings and format them in html (thanks Volker Dobler). +</pre> + +<h2 id="2011-12-01">2011-12-01</h2> + +<pre> +This weekly snapshot includes changes to the time, os, and text/template +packages. The changes to the time and os packages are significant and related. +Code that uses package time, package text/template, or package os's FileInfo +type will require changes. + +In package time, there is now one type - time.Time - to represent times. +Note that time.Time should be used as a value, in contrast to old code +which typically used a *time.Time, a pointer to a large struct. (Drop the *.) +Any function that previously accepted a *time.Time, an int64 +number of seconds since 1970, or an int64 number of nanoseconds +since 1970 should now accept a time.Time. Especially as a replacement +for the int64s, the type is good documentation about the meaning of +its value. + +Whether you were previously calling time.Seconds, time.Nanoseconds, +time.LocalTime, or time.UTC, the replacement is the new function +time.Now. + +If you previously wrote code like: + + t0 := time.Nanoseconds() + myFunction() + t1 := time.Nanoseconds() + delta := t1 - t0 + fmt.Printf("That took %.2f seconds\n", float64(t1-t0)/1e9) + +you can now write: + + t0 := time.Now() + myFunction() + t1 := time.Now() + delta := t1.Sub(t0) + fmt.Printf("That took %s\n", delta) + +In this snippet, the variable delta is of the new type time.Duration, the +replacement for the many int64 parameters that were nanosecond +counts (but not since 1970). + +Gofix can do the above conversions and some others, but it does not +rewrite explicit int64 types as time.Time. It is very likely that you will +need to edit your program to change these types after running gofix. +As always, be sure to read the changes that gofix makes using your +version control system's diff feature. + +See http://weekly.golang.org/pkg/time/ for details. + +In package os, the FileInfo struct is replaced by a FileInfo interface, +admitting implementations by code beyond the operating system. +Code that refers to *os.FileInfo (a pointer to the old struct) should +instead refer to os.FileInfo (the new interface). +The interface has just a few methods: + + type FileInfo interface { + Name() string // base name of the file + Size() int64 // length in bytes + Mode() FileMode // file mode bits + ModTime() time.Time // modification time + IsDir() bool // abbreviation for Mode().IsDir() + } + +If you need access to the underlying stat_t provided by the operating +system kernel, you can access it by assuming that the FileInfo you are +holding is actually an *os.FileStat, and that it's Sys field is actually a +*syscall.Stat_t, as in: + + dev := fi.(*os.FileStat).Sys.(*syscall.Stat_t).Dev + +Of course, this is not necessarily portable across different operating +systems. + +Gofix will take care of rewriting *os.FileInfo to os.FileInfo for you, +and it will also rewrite expressions like fi.Name into calls like fi.Name(). + +See http://weekly.golang.org/pkg/os/#FileInfo for details. + +The template package has been changed to export a new, simpler API. +The Set type is gone. Instead, templates are automatically associated by +being parsed together; nested definitions implicitly create associations. +Only associated templates can invoke one another. +This approach dramatically reduces the breadth of the construction API. +The html/template package has been updated also. +There's a gofix for the simplest and most common uses of the old API. +Code that doesn't mention the Set type is likely to work after running gofix; +code that uses Set will need to be updated by hand. +The template definition language itself is unchanged. + +See http://weekly.golang.org/pkg/text/template/ for details. + + +Other changes: +* cgo: add support for callbacks from dynamic libraries. +* codereview: gofmt check for non-src/ files (thanks David Crawshaw). +* crypto/openpgp/packet: fix private key checksum. +* crypto/tls: add openbsd root certificate location, + don't rely on map iteration order. +* crypto/x509, crypto/tls: support PKCS#8 private keys. +* dashboard: start of reimplementation in Go for App Engine. +* encoding/xml: fix copy bug. +* exp/gui: move exp/gui and exp/gui/x11 to http://code.google.com/p/x-go-binding +* exp/ssh: various improvements (thanks Dave Cheney and Gustav Paul). +* filepath/path: fix Rel buffer sizing (thanks Gustavo Niemeyer). +* gc: fix Nconv bug (thanks Rémy Oudompheng) and other fixes. +* go/printer, gofmt: performance improvements. +* gofix: test and fix missorted renames. +* goinstall: add -fix flag to run gofix on packages on build failure, + better error reporting, + don't hit network unless a checkout or update is required, + support Google Code sub-repositories. +* html: parser improvements (thanks Andrew Balholm). +* http: fix sniffing bug causing short writes. +* json: speed up encoding, caching reflect calls. +* ld: align ELF data sections. +* math/big: fix destination leak into result value (thanks Roger Peppe), + use recursive subdivision for significant speedup. +* math: faster Cbrt and Sincos (thanks Charles L. Dorian). +* misc/osx: scripts to make OS X package and disk image (thanks Scott Lawrence). +* os: fail if Open("") is called on windows (thanks Alex Brainman). +* runtime: make sure stack is 16-byte aligned on syscall (thanks Alex Brainman). +* spec, gc: allow direct conversion between string and named []byte, []rune. +* sql: add Tx.Stmt to use an existing prepared stmt in a transaction, + more driver docs & tests; no functional changes. +* strings: add ContainsAny and ContainsRune (thanks Scott Lawrence). +* syscall: add SUSv3 RLIMIT/RUSAGE constants (thanks Sébastien Paolacci), + fix openbsd sysctl hostname/domainname workaround, + implement Syscall15 (thanks Alex Brainman). +* time: fix Timer stop. +</pre> + +<h2 id="2011-11-18">2011-11-18</h2> + +<pre> +This snapshot includes some language changes. + +Map and function value comparisons are now disallowed (except for comparison +with nil) as per the Go 1 plan. Function equality was problematic in some +contexts and map equality compares pointers, not the maps' content. + +As an experiment, structs are now allowed to be copied even if they contain +unexported fields. This gives packages the ability to return opaque values in +their APIs. + +Other changes: +* 6a, 8a: allow $(-1) for consistency with $1, $(1), $-1. +* 6l: code generation fixes (thanks Michał Derkacz). +* build: fix check for selinux allow_execstack on Fedora (thanks Bobby Powers). +* builtin: document delete. +* cgo: don't panic on undeclared enums/structs (thanks Rémy Oudompheng), + fix g0 stack guard. +* crypto/tls: fix handshake message test. +* crypto: update incorrect references to Cipher interface; should be Block. +* doc: clean ups, additions, and fixes to several documents. +* doc/install: add openbsd (thanks Joel Sing!). +* doc: link to Chinese translation of A Tour of Go. +* encoding/json: add marshal/unmarshal benchmark, + decode [] as empty slice, not nil slice, + make BenchmarkSkipValue more consistent. +* env.bash: check for presence of make/gmake (thanks Scott Lawrence). +* exp/sql: NumInput() allow -1 to ignore checking (thanks Yasuhiro Matsumoto), + add DB.Close, fix bugs, remove Execer on Driver (only Conn), + document that for drivers, io.EOF means no more rows, + add client side support for publickey auth (thanks Dave Cheney), + add direct-tcpip client support (thanks Dave Cheney), + change test listen address, also exit test if fails, + other fixes and improvements (thanks Dave Cheney). +* exp/terminal: rename shell to terminal and add SetSize. +* fcgi: fix server capability discovery. +* fmt: distinguish empty vs nil slice/map in %#v. +* gc: better error, type checks, and many fixes, + remove m[k] = x, false syntax (use delete(m, k) instead), + support for building with Plan 9 yacc (thanks Anthony Martin). +* go/printer: make //line formatting idempotent. +* godefs: delete, replaced by cgo -godefs. +* godoc: document -templates flag, fix remote search, + provide mode for flat (non-indented) directory listings. +* gofmt: leave nil nodes of the AST unchanged (thanks Rémy Oudompheng). +* html/template: indirect top-level values before printing. +* html: more parser improvements (thanks Andrew Balholm). +* http: fix serving from CWD with http.ServeFile, + make Dir("") equivalent to Dir("."). +* ld: fix .bss for ldpe (thanks Wei Guangjing). +* math/big: replace nat{} -> nat(nil). +* math: faster Lgamma (thanks Charles L. Dorian). +* mime: implement TypeByExtension for windows. +* misc/bbedit: error and rune support (thanks Anthony Starks). +* misc/benchcmp: benchmark comparison script. +* misc/emacs: add delete builtin (thanks Bobby Powers). +* misc/kate: add error and rune (thanks Evan Shaw). +* misc/notepadplus: error and rune support (thanks Anthony Starks). +* misc/windows: Windows installer in MSI format (thanks Joe Poirier). +* net, io/ioutil: remove use of os.Time (thanks Anthony Martin). +* net/http: fix EOF handling on response body (thanks Gustavo Niemeyer), + fix sniffing when using ReadFrom, + use t.Errorf from alternate goroutine in test. +* os: remove undocumented Envs (use os.Environ instead). +* reflect: empty slice/map is not DeepEqual to nil, + make Value an opaque struct. +* runtime, syscall: convert from godefs to cgo. +* runtime: add nanotime for Plan 9 (thanks Anthony Martin), + add timer support, use for package time, + avoid allocation for make([]T, 0). +* strconv: add Ftoa benchmarks, make Ftoa faster. +* syscall: delete syscall.Sleep, take over env implementation, use error. +* testing: add file:line stamps to messages, print results to standard output. +* text/template: refactor set parsing. +* time: add ISOWeek method to Time (thanks Volker Dobler). +* various: avoid func compare, reduce overuse of os.EINVAL + others. +</pre> + +<h2 id="2011-11-09">2011-11-09</h2> + +<pre> +This weekly snapshot renames various Go packages as described in the Go 1 plan. +Import statements in client code can be updated automatically with gofix. + +The changes are: + asn1 -> encoding/asn1 + big -> math/big + cmath -> math/cmplx + csv -> encoding/csv + exec -> os/exec + exp/template/html -> html/template + gob -> encoding/gob + http -> net/http + http/cgi -> net/http/cgi + http/fcgi -> net/http/fcgi + http/httptest -> net/http/httptest + http/pprof -> net/http/pprof + json -> encoding/json + mail -> net/mail + rpc -> net/rpc + rpc/jsonrpc -> net/rpc/jsonrpc + scanner -> text/scanner + smtp -> net/smtp + syslog -> log/syslog + tabwriter -> text/tabwriter + template -> text/template + template/parse -> text/template/parse + rand -> math/rand + url -> net/url + utf16 -> unicode/utf16 + utf8 -> unicode/utf8 + xml -> encoding/xml +</pre> + +<h2 id="2011-11-08">2011-11-08</h2> + +<pre> +This weekly snapshot includes some package changes. + +In preparation for the Go 1 package reorganziation the sources for various +packages have been moved, but the import paths remain unchanged. This +inconsistency breaks goinstall at this snapshot. If you use goinstall, please +stay synced to the previous weekly snapshot until the next one is tagged. + +The Error methods in the html, bzip2, and sql packages that return error values +have been renamed to Err. + +Some non-core parts of the http package have been moved to net/http/httputil. +The Dump* and NewChunked* functions and ClientConn, ServerConn, and +ReverseProxy types have been moved from http to httputil. + +The API for html/template is now a direct copy of the template API, instead of +exposing a single Escape function. For HTML templates, use the +html/template package as you would the template package. + +Other changes: +* all: rename os.EOF to io.EOF in non-code contexts (thanks Vincent Vanackere), + sort imports with gofix. +* archive/zip: close file opened with OpenReader (thanks Dmitry Chestnykh). +* bufio: return nil line from ReadLine on error, as documented. +* builtin: document basic types and the built-in error type. +* bytes: add Contains function. +* exp/sql: finish implementation of transactions, flesh out types, docs. +* exp/ssh: improved client authentication support (thanks Dave Cheney). +* gc: better error message for range over non-receive channel, + bug fixes and clean-ups, + detect type switch variable not used cases, + fix escaping of package paths in symbol names, + helpful error message on method call on pointer to pointer, + portably read archive headers (thanks Ron Minnich). +* gob: fix bug when registering the same type multiple times. +* gofix: avoid panic on body-less functions in netudpgroup, + make fix order implicit by date. +* gofmt, gofix: sort imports. +* goinstall: support launchpad.net/~user branches (thanks Jani Monoses). +* gopack: do not look for Go metadata in non-Go objects. +* gotest: don't run examples that have no expected output. +* html: the parser bug fixing campaign continues (thanks Andrew Balholm). +* http: fix whitespace handling in sniffer, + only recognize application/x-www-form-urlencoded in ParseForm, + support Trailers in ReadRequest. +* lib9: add ctime. +* math: faster Gamma (thanks Charles L. Dorian), + improved accuracy for Tan (thanks Charles L. Dorian), + improved high-angle test for Cos, Sin and Tan (thanks Charles L. Dorian). +* net: implement LookupTXT for windows (thanks Alex Brainman). +* os,text,unicode: renamings. +* runtime/cgo: fix data declaration to be extern. +* runtime: add timespec definition for freebsd, + add windows callback tests (thanks Alex Brainman), + fix prototype for openbsd thrsleep, + fix set and not used, + unify mutex code across OSes, + windows_386 sighandler to use correct g (thanks Alex Brainman). +* template: format error with pointer receiver, + make redefinition of a template in a set more consistent. +* test: clear execute bit from source file (thanks Mikio Hara), + make closedchan.go exit with failure if something fails. +* time: faster Nanoseconds call. +* websocket: return an error HTTP response for bad websocket request. +* xml: allow parsing of <_> </_>. (thanks David Crawshaw). +</pre> + +<h2 id="2011-11-02">2011-11-02 (new error type)</h2> + +<pre> +This snapshot introduces the built-in error type, defined as + + type error interface { + Error() string + } + +The error type replaces os.Error. Notice that the method name has changed from +String to Error. Package fmt's Print formats both Stringers and errors: +in general there is no need to implement both String and Error methods. + +Gofix can update most code. If you have split your package across many files, +it may help to use the -force=error command-line option, which forces gofix to +apply the error fix even if it is not obvious that a particular file needs it. +As always, it is a good idea to read and test the changes that gofix made +before committing them to your version control system. +</pre> + +<h2 id="2011-11-01">2011-11-01</h2> + +<pre> +* 6l: remove mention of -e flag - it does nothing. +* cc: change cas to newcase (thanks Ron Minnich). +* crypto/openpgp/error: use Error in names of error impl types. +* crypto/rsa: change public exponent from 3 to 65537. +* crypto/tls: add Error method to alert. +* doc: add link to A Tour of Go in Japanese, + add 'all' make rule to build all docs, + refer to tour.golang.org instead of go-tour.appspot.com. +* exp/norm: fixed bug that crept in with moving to the new regexp. +* exp/ssh: fix length header leaking into channel data (thanks Dave Cheney). +* fmt: handle os.Error values explicity (as distinct from Stringer). +* gc: clean up printing, + fix [568]g -V crash (thanks Mikio Hara), + test + fix escape analysis bug. +* go/build: avoid os.Error in tests. +* go/doc: remove os.NewError anti-heuristic. +* go/parser: test and fix := scoping bug. +* gob: split uses of gobError, remove unnecessary embedding. +* gofix: test import insertion, deletion. +* goinstall: intelligent vcs selection for common sites (thanks Julian Phillips). +* gopack: change archive file name length back to 16. +* html: fix print argument in test, + more parser improvements (thanks Andrew Balholm). +* json: properly handle nil slices (thanks Alexander Reece). +* math: improved accuracy for Sin and Cos (thanks Charles L. Dorian). +* misc/emacs: fix restoration of windows after gofmt (thanks Jan Newmarch). +* misc/vim: add rune keyword (thanks Jongmin Kim). +* misc/windows: can be used for amd64 (thanks Alex Brainman). +* net: document why we do not use SO_REUSEADDR on windows (thanks Alex Brainman). +* os: do not interpret 0-length read as EOF. +* pkg: remove .String() from some print arguments. +* rpc: avoid infinite loop on input error. +* runtime/pprof: document OS X being broken. +* runtime: lock the main goroutine to the main OS thread during init. +* spec: define that initialization is sequential. +* strconv: use better errors than os.EINVAL, os.ERANGE. +* syscall: fix Await msg on Plan 9 (thanks Andrey Mirtchovski). +* template: do not use error as stringer, + fix error checking on execute without parse (thanks Scott Lawrence). +* test/alias.go: additional tests. +* test: error-related fixes. +* textproto: prevent long lines in HTTP headers from causing HTTP 400 responses. +* time: add RFC1123 with numeric timezone format (thanks Scott Lawrence). +</pre> + +<h2 id="2011-10-26">2011-10-26 (new rune type)</h2> + +<pre> +This snapshot introduces the rune type, an alias for int that +should be used for Unicode code points. + +A future release of Go (after Go 1) will change rune to be an +alias for int32 instead of int. Using rune consistently is the way +to make your code build both before and after this change. + +To test your code for rune safety, you can rebuild the Go tree with + + GOEXPERIMENT=rune32 ./all.bash + +which builds a compiler in which rune is an alias for int32 instead of int. + +Also, run govet on your code to identify methods that might need to have their +signatures updated. +</pre> + +<h2 id="2011-10-25">2011-10-25</h2> + +<pre> +* big: make SetString return nil if an error occurs, + new Rat.Inv method, + usable zero Rat values without need for explicit initialization. +* codereview: show LGTMs in hg p. +* crypto/x509: fix names in certificate generation. +* exp/ssh: add experimental ssh client, + introduce Session to replace Cmd for interactive commands, + server cleanups (thanks Dave Cheney). +* exp/types: fix crash in parseBasicType on unknown type. +* fmt: don't panic formatting nil interfaces (thanks Gustavo Niemeyer). +* go/ast, go/token: actually run tests; fix go/ast test. +* gotest: explicit -help flag, use $GCFLAGS like make does. +* govet: check canonical dynamic method signatures. +* html: improved parsing (thanks Andrew Balholm), + parse <select> tags, parse and render comment nodes, + remove the Tokenizer.ReturnComments option. +* http: Transport: with TLS InsecureSkipVerify, skip hostname check. +* misc/vim: add highlighting for delete (thanks Dave Cheney). +* net: do not set SO_REUSEADDR for windows (thanks Alex Brainman). +* os/inotify: move to exp/inotify (thanks Mikio Hara). +* runtime: include bootstrap m in mcpu accounting (thanks Hector Chu). +* syscall: use uintptr for Mount flags. +</pre> + +<h2 id="2011-10-18">2011-10-18</h2> + +<pre> +This weekly snapshot includes some language and package changes that may +require code changes. Please read these notes carefully, as there are many +changes and your code will likely be affected. + +The syntax for map deletion has been changed. Code that looks like: + m[x] = 0, false +should be written as: + delete(m, x) +The compiler still accepts m[x] = 0, false for now; even so, you can use gofix +to rewrite such assignments into delete(m, x). + +The Go compiler will reject a return statement without arguments when any of +the result variables has been shadowed. Code rejected as a result of this +change is likely to be buggy. + +Receive-only channels (<-chan T) cannot be closed. +The compiler will diagnose such attempts. + +The first element of a map iteration is chosen at random. Code that depends on +iteration order will need to be updated. + +Goroutines may be run during program initialization. + +A string may be appended to a byte slice. This code is now legal: + var b []byte + var s string + b = append(b, s...) + +The gotry command and its associated try package have been deleted. +It was a fun experiment that - in the end - didn't carry its weight. + +The gotype tool has been moved to exp/gotype and its associated go/types +package has been moved to exp/types. The deprecated go/typechecker package has +been deleted. + +The enbflint tool has been moved to pkg/exp/ebnflint and its associated ebnf +package has been moved to pkg/exp/ebnf. + +The netchan package has been moved to old/netchan. + +The http/spdy package has been moved to exp/spdy. + +The exp/datafmt package has been deleted. + +The container/vector package has been deleted. Slices are better: + http://code.google.com/p/go-wiki/wiki/SliceTricks + +Other changes: +* 5l/6l/8l: correct ELFRESERVE diagnostic (thanks Anthony Martin). +* 6l/8l: support OS X code signing (thanks Mikkel Krautz). +* asn1: accept UTF8 strings as ASN.1 ANY values. +* big: handle aliasing correctly for Rat.SetFrac. +* build: add missing nuke target (thanks Anthony Martin), + catch future accidental dependencies to exp or old packages, + more robustly detect gold 2.20 (thanks Christopher Wedgwood), + pass $GCFLAGS to compiler, + stop on failed deps.bash. +* crypto/tls: add 3DES ciphersuites, + add server side SNI support, + fetch root CA from Windows store (thanks Mikkel Krautz), + fetch root certificates using Mac OS API (thanks Mikkel Krautz), + fix broken looping code in windows root CA fetcher (thanks Mikkel Krautz), + more Unix root certificate locations. +* crypto/x509: add code for dealing with PKIX public keys, + keep the raw Subject and Issuer. +* csv: fix overly aggressive TrimLeadingSpace. +* exp/ssh: general cleanups for client support (thanks Dave Cheney). +* exp/template/html: fix bug in cssEscaper. +* exp/terminal: split terminal handling from exp/ssh. +* exp/winfsnotify: filesystem watcher for Windows (thanks Hector Chu). +* fmt: fix test relying on map iteration order. +* gc: changes to export format in preparation for inlining, + pass FlagNoPointers to runtime.new, + preserve uint8 and byte distinction in errors and import data, + stricter multiple assignment + test, + treat uintptr as potentially containing a pointer. +* go/scanner: remove AllowIllegalChars mode. +* go/token: document deserialization property. +* gob: avoid one copy for every message written. +* godefs: add enum/const testdata (thanks Dave Cheney). +* godoc: generate package toc in template, not in JavaScript, + show "unexported" declarations when executing "godoc builtin", + show correct source name with -path. +* gofix: make fix order explicit, add mapdelete. +* gofmt: fix //line handling, + disallow rewrites for incomplete programs. +* gotest: avoid conflicts with the name of the tested package (thanks Esko Luontola), + test example code. +* goyacc: clean up after units (thanks Anthony Martin), + make more gofmt-compliant. +* html: add a Render function, various bug fixes and improvements, + parser improvements (thanks Andrew Balholm). +* http: DoS protection: cap non-Handler Request.Body reads, + RoundTrippers shouldn't mutate Request, + avoid panic caused by nil URL (thanks Anthony Martin), + fix read timeouts and closing, + remove Request.RawURL. +* image/tiff: implement PackBits decoding (thanks Benny Siegert). +* ld: fix "cannot create 8.out.exe" (thanks Jaroslavas Počepko). +* misc/emacs: add a "godoc" command, like M-x man (thanks Evan Martin). +* misc/swig: delete binaries (thanks Anthony Martin). +* misc/windows: automated toolchain packager (thanks Joe Poirier). +* net/windows: implement ip protocol name to number resolver (thanks Alex Brainman). +* net: add File method to IPConn (thanks Mikio Hara), + allow LookupSRV on non-standard DNS names, + fix "unexpected socket family" error from WriteToUDP (thanks Albert Strasheim), + fix socket leak in case of Dial failure (thanks Chris Farmiloe), + remove duplicate error information in Dial (thanks Andrey Mirtchovski), + return error from CloseRead and CloseWrite (thanks Albert Strasheim), + skip ICMP test on Windows too unless uid 0. +* reflect: disallow Interface method on Value obtained via unexported name, + make unsafe use of SliceHeader gc-friendly. +* rpc: don't panic on write error. +* runtime: faster strings, + fix crash if user sets MemProfileRate=0, + fix crash when returning from syscall during gc (thanks Hector Chu), + fix memory leak in parallel garbage collector. +* scanner: invalidate scanner.Position when no token is present. +* spec: define order of multiple assignment. +* syscall/windows: dll function load and calling changes (thanks Alex Brainman). +* syscall: add #ifdefs to fix the manual corrections in ztypes_linux_arm.go (thanks Dave Cheney), + adjust Mount to accomodate stricter FS implementations. +* testing: fix time reported for failing tests. +* utf8: add Valid and ValidString. +* websocket: tweak hybi ReadHandshake to support Firefox (thanks Luca Greco). +* xml: match Marshal's XMLName behavior in Unmarshal (thanks Chris Farmiloe). +</pre> + +<h2 id="2011-10-06">2011-10-06</h2> + +<pre> +This weekly snapshot includes changes to the io, image, and math packages that +may require changes to client code. + +The io package's Copyn function has been renamed to CopyN. + +The math package's Fabs, Fdim, Fmax, Fmin and Fmod functions +have been renamed to Abs, Dim, Max, Min, and Mod. + +Parts of the image package have been moved to the new image/color package. +The spin-off renames some types. The new names are simply better: + image.Color -> color.Color + image.ColorModel -> color.Model + image.ColorModelFunc -> color.ModelFunc + image.PalettedColorModel -> color.Palette + image.RGBAColor -> color.RGBA + image.RGBAColorModel -> color.RGBAModel + image.RGBA64Color -> color.RGBA64 + image.RGBA64ColorModel -> color.RGBA64Model +(similarly for NRGBAColor, GrayColorModel, etc) +The image.ColorImage type stays in the image package, but is renamed: + image.ColorImage -> image.Uniform +The image.Image implementations (image.RGBA, image.RGBA64, image.NRGBA, +image.Alpha, etc) do not change their name, and gain a nice symmetry: +an image.RGBA is an image of color.RGBA, etc. +The image.Black, image.Opaque uniform images remain unchanged (although their +type is renamed from image.ColorImage to image.Uniform). +The corresponding color types (color.Black, color.Opaque, etc) are new. +Nothing in the image/ycbcr is renamed yet. The ycbcr.YCbCrColor and +ycbcr.YCbCrImage types will eventually migrate to color.YCbCr and image.YCbCr, +at a later date. + +* 5g/6g/8g: fix loop finding bug, fix -f(), registerize variables again. +* 5l/6l/8l: add a DT_DEBUG dynamic tag to a dynamic ELF binary. +* archive/zip: read and write unix file modes (thanks Gustavo Niemeyer). +* build: clear execute bit from source files (thanks Mikio Hara). +* bytes: add EqualFold. +* cgo: allow Windows path characters in flag directives (thanks Joe Poirier), + support for mingw-w64 4.5.1 and newer (thanks Wei Guangjing). +* codereview: extra repo sanity check, + fix for Mercurial 1.9.2, + fix hg change in Windows console (thanks Yasuhiro Matsumoto). +* crypto/elliptic: use %x consistently in error print. +* doc/spec: remove notes about gccgo limitations, now fixed. +* doc: add 'Debugging Go code with GDB' tutorial, + fix memory model read visibility bug. +* encoding/binary: PutX functions require buffer of sufficient size, + added benchmarks, support for varint encoding. +* exec: add Command.ExtraFiles. +* exp/sql{,/driver}: new database packages. +* exp/ssh: move common code to common.go (thanks Dave Cheney). +* exp/template/html: work continues. +* fmt: replace channel cache with slice. +* gc: limit helper threads based on ncpu. +* go/doc, godoc, gotest: support for reading example documentation. +* go: documentation and skeleton implementation of new command. +* gob: protect against invalid message length, + allow sequential decoders on the same input stream. +* hgpatch: do not use hg exit status (thanks Yasuhiro Matsumoto). +* http: add Location method to Response, + don't send a 400 Bad Request after a client shutdown. +* index/suffixarray: 4.5x faster index serialization (to memory). +* io/ioutil: add a comment on why devNull is a ReaderFrom. +* json: use strings.EqualFold instead of strings.ToLower. +* misc/emacs: fix indent bug. +* net: add shutdown: TCPConn.CloseWrite and CloseRead. +* net: use AF_UNSPEC instead of individual address family (thanks Mikio Hara). +* path/filepath: added Rel as the complement of Abs (thanks Gustavo Niemeyer). +* pkg/syscall: add Mkfifo for linux platforms. +* regexp: move to old/regexp, replace with exp/regexp, speedups. +* runtime/gdb: fix pretty printing of channels, + gracefully handle not being able to find types. +* runtime: check for nil value pointer in select syncsend case, + faster finalizers, + fix malloc sampling bug, + fix map memory leak, + fix spurious deadlock reporting, + fix usleep on linux/386 and re-enable parallel gc (thanks Hector Chu), + parallelize garbage collector mark + sweep. +* strconv: faster Unquote in common case. +* strings: add EqualFold, Replacer, NewReplacer. +* suffixarray: add benchmarks for construction (thanks Eric Eisner). +* syscall: add GetsockoptByte, SetsockoptByte for openbsd (thanks Mikio Hara), + add IPv4 ancillary data for linux (thanks Mikio Hara), + mark stdin, stdout, stderr non-inheritable by child processes (thanks Alex Brainman), + mksyscall_windows.pl creates non-syscall packages (thanks Jaroslavas Počepko), + update multicast socket options (thanks Mikio Hara). +* testing: support for running tests in parallel (thanks Miki Tebeka). +* time: make month/day name comparisons case insenstive. +* unicode: fix make tables. +* vim: Send GoFmt errors to a location list (thanks Paul Sbarra). +* websocket: add hybi-13 support, add mutex to make websocket full-duplex. +</pre> + +<h2 id="2011-09-21">2011-09-21</h2> + +<pre> +This weekly contains several improvements, bug fixes, and new packages. + +* archive/tar: document Header fields and Type flags (thanks Mike Rosset). +* bytes: fix Replace so it actually copies (thanks Gustavo Niemeyer). +* cgo: use GOARCH from the environment (thanks Jaroslavas Počepko). +* codereview: save CL messages in $(hg root)/last-change. +* crypto/bcrypt: new package (thanks Jeff Hodges). +* crypto/blowfish: exposing the blowfish key schedule (thanks Jeff Hodges). +* doc: link to golang-france. +* doc: when configuring gold for gccgo, use --enable-gold=default. +* exp/norm: changed trie to produce smaller tables. +* exp/ssh: new package, + refactor halfConnection to transport (thanks Dave Cheney). +* exp/template/html: more fixes and improvements. +* filepath: fix Glob to return no error on nonmatching patterns. +* gc: disallow invalid map keys, + handle complex CONVNOP. +* gob: allocation fixes. +* godoc: simplify internal FileSystem interface. +* http/cgi: clean up environment (thanks Yasuhiro Matsumoto). +* http: always include Content-Length header, even for 0 (thanks Dave Grijalva), + check explicit wrong Request.ContentLength values, + fix TLS handshake blocking server accept loop, + prevent DumpRequest from adding implicit headers. +* httptest: add NewUnstartedServer. +* json: clearer Unmarshal doc, + skip nil in UnmarshalJSON and (for symmetry) MarshalJSON. +* net: use /etc/hosts first when looking up IP addresses (thanks Andrey Mirtchovski). +* reflect: add comment about the doubled semantics of Value.String. +* runtime: implement pprof support for windows (thanks Hector Chu), + increase stack system space on windows/amd64 (thanks Hector Chu). +* suffixarray: generate less garbage during construction (thanks Eric Eisner), + improved serialization code using gob instead of encoding/binary. +* sync/atomic: replace MFENCE with LOCK XADD. +</pre> + +<h2 id="2011-09-16">2011-09-16</h2> + +<pre> +This weekly snapshot includes changes to the image, path/filepath, and time +packages. Code that uses these packages may need to be updated. + +The image package's NewX functions (NewRGBA, NewNRGBA, etc) have been changed +to take a Rectangle argument instead of a width and height. +Gofix can make these changes automatically. + +The path/filepath package's Walk function has been changed to take a WalkFunc +function value instead of a Visitor interface value. WalkFunc is like the +Visitor's VisitDir and VisitFile methods except it handles both files and +directories: + func(path string, info *os.FileInfo, err os.Error) os.Error +To skip walking a directory (like returning false from VisitDir) the WalkFunc +must return SkipDir. + +The time package's Time struct's Weekday field has been changed to a method. +The value is calculated on demand, avoiding the need to re-parse +programmatically-constructed Time values to find the correct weekday. + +There are no gofixes for the filepath or time API changes, but instances of the +old APIs will be caught by the compiler. The Weekday one is easy to update by +hand. The Walk one may take more consideration, but will have fewer instances +to fix. + +* build: add build comments to core packages. +* codereview: Mercurial 1.9 fix for hg diff @nnn. +* crypto/tls: handle non-TLS more robustly, + support SSLv3. +* debug/elf: permit another case of SHT_NOBITS section overlap in test. +* exm/template/html: more work on this auto-escaping HTML template package. +* exp/norm: added regression test tool for the standard Unicode test set. +* exp/regexp/syntax: fix invalid input parser crash, + import all RE2 parse tests + fix bugs. +* exp/regexp: add MustCompilePOSIX, CompilePOSIX, leftmost-longest matching. +* flag: make zero FlagSet useful. +* gc: clean up if grammar. +* go/build: handle cgo, // +build comments. +* go/printer: use panic/defer instead of goroutine for handling errors. +* go/token: support to serialize file sets. +* godoc, suffixarray: switch to exp/regexp. +* godoc: show packages matching a query at the top, + support for complete index serialization, + use go/build to find files in a package. +* gofmt: accept program fragments on standard input, add else test. +* http/cgi: add openbsd environment configuration. +* http: document that Response.Body is non-nil. +* image/png: don't use a goroutine to decode, to permit decode during init. +* json: if a field's tag is "-", ignore the field for encoding and decoding. +* ld: grow dwarf includestack on demand. +* net, syscall: implement SetsockoptIPMReq(), and + move to winsock v2.2 for multicast support (thanks Paul Lalonde). +* net: add a LookupTXT function. +* os: os.RemoveAll to check for wboth error codes on Windows (thanks Jaroslavas Počepko). +* path/filepath: fix Visitor doc (thanks Gustavo Niemeyer), + make UNC file names work (thanks Yasuhiro Matsumoto). +* runtime: optimizations to channels on Windows (thanks Hector Chu), + syscall to return both AX and DX for windows/386 (thanks Alex Brainman). +* sync/atomic: add 64-bit Load and Store. +* syscall: add route flags for linux (thanks Mikio Hara). +* test: add test for inheriting private method from anonymous field. +* websocket: fix infinite recursion in Addr.String() (thanks Tarmigan Casebolt), + rename websocket.WebSocketAddr to *websocket.Addr. +</pre> + <h2 id="2011-09-07">2011-09-07</h2> <pre> @@ -438,7 +2677,7 @@ Other changes: * exp/regexp/syntax: add Prog.NumCap. * exp/template: API changes, bug fixes, and tweaks. * flag: make -help nicer. -* fmt: Scan(&int) was mishandling a lone digit. +* fmt: Scan(&int) was mishandling a lone digit. * gc: fix closure bug, fix to build with clang (thanks Dave Cheney), make size of struct{} and [0]byte 0 bytes (thanks Robert Hencke), @@ -596,7 +2835,7 @@ Other changes: <h2 id="2011-06-23">2011-06-23</h2> <pre> -This release includes a language change that restricts the use of goto. +This snapshot includes a language change that restricts the use of goto. In essence, a "goto" statement outside a block cannot jump to a label inside that block. Your code may require changes if it uses goto. This changeset shows how the new rule affected the Go tree: @@ -619,7 +2858,7 @@ Other changes: add support for Plan 9 (thanks Anthony Martin), better error message for windows LookPath (thanks Alex Brainman). * fmt: catch panics from calls to String etc. -* gc: descriptive panic for nil pointer -> value method call, +* gc: descriptive panic for nil pointer -> value method call, implement goto restriction, unsafe.Alignof, unsafe.Offsetof, unsafe.Sizeof now return uintptr. * go/build: include Import objects in Script Inputs. @@ -657,7 +2896,7 @@ Other changes: <h2 id="2011-06-16">2011-06-16</h2> <pre> -This release includes changes to the sort and image/draw packages that will +This snapshot includes changes to the sort and image/draw packages that will require changes to client code. The sort.IntArray type has been renamed to IntSlice, and similarly for @@ -694,7 +2933,7 @@ Other changes: * net: export all fields in Interface (thanks Mikio Hara), rearrange source to run more tests on Windows (thanks Alex Brainman), sendfile for win32 (thanks Yasuhiro Matsumoto). -* os: Plan 9, fix OpenFile & Chmod, add Process.Kill (thanks Yuval Pavel Zholkover). +* os: Plan 9, fix OpenFile & Chmod, add Process.Kill (thanks Yuval Pavel Zholkover). * runtime: fix Plan 9 "lingering goroutines bug" (thanks Yuval Pavel Zholkover). * spec: clarify rules for append, scope rules for :=, specify constant conversions, @@ -710,7 +2949,7 @@ Other changes: <h2 id="2011-06-09">2011-06-09 (<a href="release.html#r58">base for r58</a>)</h2> <pre> -This release includes changes to the strconv, http, and exp/draw packages. +This snapshot includes changes to the strconv, http, and exp/draw packages. Client code that uses the http or exp/draw packages will need to be changed, and code that uses strconv or fmt's "%q" formatting directive merits checking. @@ -768,7 +3007,7 @@ Other changes: <h2 id="2011-06-02">2011-06-02</h2> <pre> -This release includes changes to the exec package that will require changes +This snapshot includes changes to the exec package that will require changes to client code. The exec package has been re-designed with a more convenient and succinct API. @@ -780,7 +3019,7 @@ This code: return nil, err } var buf bytes.Buffer - io.Copy(&buf, p.Stdout) + io.Copy(&buf, p.Stdout) w, err := p.Wait(0) p.Close() if err != nil { @@ -838,7 +3077,7 @@ Other changes: * goinstall: fixes for windows (thanks Alex Brainman), more verbose logging with -v. * gotest, pkg/exec: use bash to run shell scripts on windows (thanks Alex Brainman). -* http/spdy: redo interfaces, flesh out implementation & frame types (thanks William Chan). +* http/spdy: redo interfaces, flesh out implementation & frame types (thanks William Chan). * http: Transport hook to register non-http(s) protocols, add client+server benchmark, catch Handler goroutine panics, @@ -889,7 +3128,7 @@ Other changes: <h2 id="2011-05-22">2011-05-22</h2> <pre> -This release includes changes to the http package that will require changes to +This snapshot includes changes to the http package that will require changes to client code. The finalURL return value of the Client.Get method has been removed. @@ -909,7 +3148,7 @@ should be rewritten as: Uses of http.Get that assign the finalURL value to _ can be rewritten automatically with gofix. -This release also includes an optimization to the append function that makes it +This snapshot also includes an optimization to the append function that makes it between 2 and 5 times faster in typical use cases. Other changes: @@ -994,7 +3233,7 @@ Other changes: * image/tiff: implement a decoder (thanks Benny Siegert). * image: add type-specific Set methods and use them when decoding PNG, make AlphaColor.Set conform to usual signature (thanks Roger Peppe), - png & jpeg encoding benchmarks. + png & jpeg encoding benchmarks. * ld: do not emit reference to dynamic library named "", fix alignment of rodata section on Plan 9 (thanks Anthony Martin), make ELF binaries with no shared library dependencies static binaries. @@ -1013,7 +3252,7 @@ Other changes: protocol family adaptive address family selection (thanks Mikio Hara), re-enable wildcard listening (thanks Mikio Hara), sort records returned by LookupSRV (thanks Gary Burd). -* os: make Readdir & Readdirnames return os.EOF at end, +* os: make Readdir & Readdirnames return os.EOF at end, make Setenv update C environment variables. * reflect: allow unexported key in Value.MapIndex. * runtime, sync/atomic: fix arm cas. @@ -1043,7 +3282,7 @@ Other changes: <h2 id="2011-04-27">2011-04-27 (<a href="release.html#r57">base for r57</a>)</h2> <pre> -This release includes revisions to the reflect package to make it more +This snapshot includes revisions to the reflect package to make it more efficient, after the last weekly's major API update. If your code uses reflect it may require further changes, not all of which can be made automatically by gofix. For the full details of the change, see @@ -1264,7 +3503,7 @@ Other changes: <h2 id="2011-04-04">2011-04-04</h2> <pre> -This release includes changes to the net package. Your code will require +This snapshot includes changes to the net package. Your code will require changes if it uses the Dial or LookupHost functions. The laddr argument has been removed from net.Dial, and the cname return value @@ -1353,7 +3592,7 @@ Other changes: * go/printer, gofmt: avoid exponential layout algorithm, gofmt: simplify struct formatting and respect line breaks. * go/scanner: to interpret line comments with Windows filenames (thanks Alex Brainman). -* go/token: use array instead of map for token->string table. +* go/token: use array instead of map for token->string table. * gob: optimizations to reduce allocations, use pointers in bootstrapType so interfaces behave properly. * gobuilder: recognize CLs of the form weekly.DATE. @@ -1459,7 +3698,7 @@ arguments as an *os.ProcAttr and *syscall.ProcAttr values, respectively. This code: os.StartProcess(bin, args, env, dir, fds) should now be written as: - os.StartProcess(bin, args, &os.ProcAttr{Files: fds, Dir: dir, Env: env}) + os.StartProcess(bin, args, &os.ProcAttr{Files: fds, Dir: dir, Env: env}) The gob package will now encode and decode values of types that implement the gob.GobEncoder and gob.GobDecoder interfaces. This allows types with unexported @@ -1860,12 +4099,12 @@ This release also changes some of the internal structure of the memory allocator in preparation for other garbage collector changes. If you run into problems, please let us know. There is one known issue that we are aware of but have not debugged yet: - http://code.google.com/p/go/issues/detail?id=1464&. + http://code.google.com/p/go/issues/detail?id=1464&. Other changes in this release: * 5l: document -F, force it on old ARMs (software floating point emulation) * 6g: fix registerization of temporaries (thanks Eoghan Sherry), - fix uint64(uintptr(unsafe.Pointer(&x))). + fix uint64(uintptr(unsafe.Pointer(&x))). * 6l: Relocate CMOV* instructions (thanks Gustavo Niemeyer), windows/amd64 port (thanks Wei Guangjing). * 8l: add PE dynexport, emit DWARF in Windows PE, and @@ -2069,7 +4308,7 @@ This release includes several fixes and changes: normalize processing of format string. * gc: return constant floats for parts of complex constants (thanks Anthony Martin), rewrite complex /= to l = l / r (thanks Patrick Gavlin), - fix &^=. + fix &^=. * go/ast: provide complete node text range info. * gob: generate a better error message in one confusing place. * godoc: fix godoc -src (thanks Icarus Sparry). @@ -2260,9 +4499,9 @@ will fail to compile rather than behave erroneously. The bytes package has changed. Its Add and AddByte functions have been removed, as their functionality is provided by the recently-introduced built-in function "append". Any code that uses them will need to be changed: -s = bytes.Add(s, b) -> s = append(s, b...) -s = bytes.AddByte(b, c) -> s = append(s, b) -s = bytes.Add(nil, c) -> append([]byte(nil), c) +s = bytes.Add(s, b) -> s = append(s, b...) +s = bytes.AddByte(b, c) -> s = append(s, b) +s = bytes.Add(nil, c) -> append([]byte(nil), c) The template package has changed. Your code will need to be updated if it calls the HTMLFormatter or StringFormatter functions, or implements its own formatter @@ -2528,12 +4767,12 @@ standard error by default. The names have also changed, although the old names are still supported. They will be deleted in the next release, though, so it would be good to update now if you can. For most purposes all you need to do is make these substitutions: - log.Stderr -> log.Println or log.Print - log.Stderrf -> log.Printf - log.Crash -> log.Panicln or log.Panic - log.Crashf -> log.Panicf - log.Exit -> log.Exitln or log.Exit - log.Exitf -> log.Exitf (no change) + log.Stderr -> log.Println or log.Print + log.Stderrf -> log.Printf + log.Crash -> log.Panicln or log.Panic + log.Crashf -> log.Panicf + log.Exit -> log.Exitln or log.Exit + log.Exitf -> log.Exitf (no change) Calls to log.New() must drop the second argument. Also, custom loggers with exit or panic properties will need to be reworked. For full details, see the change description: @@ -2772,7 +5011,7 @@ as well as the following fixes and changes: implement new slice spec (thanks Scott Lawrence) make string x + y + z + ... + w efficient more accurate line numbers for ATEXT - remove &[10]int -> []int conversion + remove &[10]int -> []int conversion * go-mode.el: fix highlighting for 'chan' type (thanks Scott Lawrence) * godoc: better support for directory trees for user-supplied paths use correct delay time (bug fix) @@ -3258,7 +5497,7 @@ clarifications and consolidations to the Language Specification. The type checking rules around assignments and conversions are simpler but more restrictive: assignments no longer convert implicitly from *[10]int to []int -(write x[0:] instead of &x), and conversions can no longer change the names of +(write x[0:] instead of &x), and conversions can no longer change the names of types inside composite types. The fmt package now includes flexible type-driven (fmt.Scan) and @@ -3290,7 +5529,7 @@ format-driven (fmt.Scanf) scanners for all basic types. * os/signal: correct the regexp for finding Unix signal names (thanks Vinu Rajashekhar). * regexp: optimizations (thanks Kyle Consalus). * runtime: fix printing -Inf (thanks Evan Shaw), - finish pchw -> tiny, added gettime for tiny (thanks Daniel Theophanes). + finish pchw -> tiny, added gettime for tiny (thanks Daniel Theophanes). * spec: clean-ups and consolidation. * syscall: additional Windows compatibility fixes (thanks Alex Brainman). * test/bench: added regex-dna-parallel.go (thanks Kyle Consalus). @@ -3313,10 +5552,10 @@ preparing for Google I/O. * cmath: update range of Phase and Polar due to signed zero (thanks Charles L. Dorian). * codereview: work better with mq (thanks Peter Williams). * compress: renamings - NewDeflater -> NewWriter - NewInflater -> NewReader - Deflater -> Compressor - Inflater -> Decompressor + NewDeflater -> NewWriter + NewInflater -> NewReader + Deflater -> Compressor + Inflater -> Decompressor * exp/draw/x11: respect $XAUTHORITY, treat $DISPLAY the same way x-go-bindings does. * exp/draw: fast path for glyph images, other optimizations, @@ -3338,7 +5577,7 @@ preparing for Google I/O. fix printing of labels. * http: prevent crash if remote server is not responding with "HTTP/". * json: accept escaped slash in string scanner (thanks Michael Hoisie), - fix array -> non-array decoding. + fix array -> non-array decoding. * libmach: skip __nl_symbol_ptr section on OS X. * math: amd64 versions of Fdim, Fmax, Fmin, signed zero Sqrt special case (thanks Charles L. Dorian). @@ -3633,8 +5872,8 @@ This release also includes the goinstall command-line tool. There is one language change: the ability to convert a string to []byte or []int. This deprecates the strings.Bytes and strings.Runes functions. You can convert your existing sources using these gofmt commands: - gofmt -r 'strings.Bytes(x) -> []byte(x)' -w file-or-directory-list - gofmt -r 'strings.Runes(x) -> []int(x)' -w file-or-directory-list + gofmt -r 'strings.Bytes(x) -> []byte(x)' -w file-or-directory-list + gofmt -r 'strings.Runes(x) -> []int(x)' -w file-or-directory-list After running these you might need to delete unused imports of the "strings" package. @@ -3794,7 +6033,7 @@ There are no language changes. build: $GOBIN should no longer be required in $PATH (thanks Devon H. O'Dell), new package target "make bench" to run benchmarks -8g: faster float -> uint64 conversion (thanks Evan Shaw) +8g: faster float -> uint64 conversion (thanks Evan Shaw) 5g, 6g, 8g: clean opnames.h to avoid stale errors (thanks Yongjian Xu), a handful of small compiler fixes diff --git a/doc/docs.html b/doc/docs.html index a86d1714e..f88e930fb 100644 --- a/doc/docs.html +++ b/doc/docs.html @@ -1,204 +1,145 @@ -<!-- title Documentation --> +<!--{ + "Title": "Documentation", + "Path": "/doc/" +}--> -<div class="left-column"> - -<h2 id="learning">Learning Go</h2> +<p> +The Go programming language is an open source project to make programmers more +productive. +</p> <p> -If you're new to Go, we recommend you work through the -<a href="go_tutorial.html">tutorial</a>. The -<a href="go_spec.html">language specification</a> has all the details should -you want to explore. +Go is expressive, concise, clean, and efficient. Its concurrency +mechanisms make it easy to write programs that get the most out of multicore +and networked machines, while its novel type system enables flexible and +modular program construction. Go compiles quickly to machine code yet has the +convenience of garbage collection and the power of run-time reflection. It's a +fast, statically typed, compiled language that feels like a dynamically typed, +interpreted language. </p> + +<div id="manual-nav"></div> + +<h2>Installing Go</h2> + +<h3><a href="/doc/install">Getting Started</a></h3> <p> -Once you've learned a little about the language, -<a href="effective_go.html">Effective Go</a> will help you learn the style and -idioms of programming in Go. +Instructions for downloading and installing the Go compilers, tools, and +libraries. </p> -<h3 id="go_tour"><a href="http://go-tour.appspot.com/">A Tour of Go</a></h3> + +<h2 id="learning">Learning Go</h2> + +<img class="gopher" src="/doc/gopher/doc.png"/> + +<h3 id="go_tour"><a href="http://tour.golang.org/">A Tour of Go</a></h3> <p> An interactive introduction to Go in three sections. The first section covers basic syntax and data structures; the second discusses methods and interfaces; and the third introduces Go's concurrency primitives. Each section concludes with a few exercises so you can practice what you've -learned. You can <a href="http://go-tour.appspot.com/">take the tour online</a> or +learned. You can <a href="http://tour.golang.org/">take the tour online</a> or <a href="http://code.google.com/p/go-tour/">install it locally</a>. </p> -<h3 id="orig_tutorial"><a href="go_tutorial.html">A Tutorial for the Go Programming Language</a></h3> -<p> -The first tutorial. An introductory text that touches upon several core -concepts: syntax, types, allocation, constants, I/O, sorting, printing, -goroutines, and channels. -</p> - -<h3 id="course_notes">Course Notes</h3> +<h3 id="code"><a href="code.html">How to write Go code</a></h3> <p> -Slides from a 3-day course about the Go programming language. -A more thorough introduction than the tutorial. +How to use the <a href="/cmd/go/">go command</a> to fetch, build, and install +packages, commands, and run tests. </p> -<ul> -<li><a href="GoCourseDay1.pdf">Day 1: Basics</a> <small>[270KB PDF]</small></li> -<li><a href="GoCourseDay2.pdf">Day 2: Types, Methods, Interfaces</a> <small>[270KB PDF]</small></li> -<li><a href="GoCourseDay3.pdf">Day 3: Concurrency and Communication</a> <small>[180KB PDF]</small></li> -</ul> <h3 id="effective_go"><a href="effective_go.html">Effective Go</a></h3> <p> A document that gives tips for writing clear, idiomatic Go code. -A must read for any new Go programmer. It augments the tutorial and +A must read for any new Go programmer. It augments the tour and the language specification, both of which should be read first. </p> +<h3 id="appengine"><a href="http://code.google.com/appengine/docs/go/gettingstarted/">Getting Started with Go on App Engine</a></h3> +<p> +How to develop and deploy a simple Go project with +<a href="http://code.google.com/appengine/">Google App Engine</a>. +</p> + <h3 id="go_faq"><a href="go_faq.html">Frequently Asked Questions (FAQ)</a></h3> <p> Answers to common questions about Go. </p> -<h3 id="code"><a href="code.html">How to write Go code</a></h3> +<h3 id="wiki"><a href="http://code.google.com/p/go-wiki/wiki">Go Language Community Wiki</a></h3> +<p>A wiki maintained by the Go community.</p> + +<h2 id="go1">Go version 1</h2> + +<h3 id="go1notes"><a href="/doc/go1.html">Go 1 Release Notes</a></h3> <p> -How to write a new package and how to test code. +A guide for updating your code to work with Go 1. </p> -<h3 id="codelab_wiki"><a href="codelab/wiki/">Codelab: Writing Web Applications</a></h3> +<h3 id="go1compat"><a href="/doc/go1compat.html">Go 1 and the Future of Go Programs</a></h3> <p> -This codelab takes the reader through the creation of a simple wiki web -application. It touches on structs, methods, file I/O, http, regular expressions, -and closures. +What Go 1 defines and the backwards-compatibility guarantees one can expect as +Go 1 matures. </p> -<h3 id="codewalks"><a href="codewalk/">Codewalks</a></h3> +<h2 id="articles">Go Articles</h2> + +<h3 id="blog"><a href="http://blog.golang.org/">The Go Blog</a></h3> +<p>The official blog of the Go project, featuring news and in-depth articles by +the Go team and guests.</p> + +<h4>Codewalks</h4> <p> -Guided tours of Go programs. +Guided tours of Go programs. </p> <ul> <li><a href="/doc/codewalk/functions">First-Class Functions in Go</a></li> <li><a href="/doc/codewalk/markov">Generating arbitrary text: a Markov chain algorithm</a></li> <li><a href="/doc/codewalk/sharemem">Share Memory by Communicating</a></li> +<li><a href="/doc/articles/wiki/">Writing Web Applications</a> - building a simple web application.</li> </ul> -<h3 id="go_for_cpp_programmers"><a href="go_for_cpp_programmers.html">Go for C++ Programmers</a></h3> -<p> -An introduction to Go for C++ programmers. -</p> - -<h2 id="articles">Go Articles</h2> - -<p> -Notable articles from the <a href="http://blog.golang.org/">Go Blog</a>. -</p> - -<h3>Language</h3> - +<h4>Language</h4> <ul> -<li><a href="http://blog.golang.org/2010/04/json-rpc-tale-of-interfaces.html">JSON-RPC: a tale of interfaces</a></li> -<li><a href="http://blog.golang.org/2010/07/gos-declaration-syntax.html">Go's Declaration Syntax</a></li> -<li><a href="http://blog.golang.org/2010/08/defer-panic-and-recover.html">Defer, Panic, and Recover</a></li> -<li><a href="http://blog.golang.org/2010/09/go-concurrency-patterns-timing-out-and.html">Go Concurrency Patterns: Timing out, moving on</a></li> -<li><a href="http://blog.golang.org/2011/01/go-slices-usage-and-internals.html">Go Slices: usage and internals</a></li> +<li><a href="/doc/articles/json_rpc_tale_of_interfaces.html">JSON-RPC: a tale of interfaces</a></li> +<li><a href="/doc/articles/gos_declaration_syntax.html">Go's Declaration Syntax</a></li> +<li><a href="/doc/articles/defer_panic_recover.html">Defer, Panic, and Recover</a></li> +<li><a href="/doc/articles/concurrency_patterns.html">Go Concurrency Patterns: Timing out, moving on</a></li> +<li><a href="/doc/articles/slices_usage_and_internals.html">Go Slices: usage and internals</a></li> <li><a href="http://blog.golang.org/2011/05/gif-decoder-exercise-in-go-interfaces.html">A GIF decoder: an exercise in Go interfaces</a></li> -<li><a href="http://blog.golang.org/2011/07/error-handling-and-go.html">Error Handling and Go</a></li> +<li><a href="/doc/articles/error_handling.html">Error Handling and Go</a></li> </ul> -<h3>Packages</h3> - +<h4>Packages</h4> <ul> -<li><a href="http://blog.golang.org/2011/01/json-and-go.html">JSON and Go</a> - using the <a href="/pkg/json/">json</a> package.</li> -<li><a href="http://blog.golang.org/2011/03/gobs-of-data.html">Gobs of data</a> - the design and use of the <a href="/pkg/gob/">gob</a> package.</li> -<li><a href="http://blog.golang.org/2011/09/laws-of-reflection.html">The Laws of Reflection</a> - the fundamentals of the <a href="/pkg/reflect/">reflect</a> package.</li> -<li><a href="http://blog.golang.org/2011/09/go-image-package.html">The Go image package</a> - the fundamentals of the <a href="/pkg/image/">image</a> package.</li> -<li><a href="http://blog.golang.org/2011/09/go-imagedraw-package.html">The Go image/draw package</a> - the fundamentals of the <a href="/pkg/image/draw/">image/draw</a> package.</li> +<li><a href="/doc/articles/json_and_go.html">JSON and Go</a> - using the <a href="/pkg/encoding/json/">json</a> package.</li> +<li><a href="/doc/articles/gobs_of_data.html">Gobs of data</a> - the design and use of the <a href="/pkg/encoding/gob/">gob</a> package.</li> +<li><a href="/doc/articles/laws_of_reflection.html">The Laws of Reflection</a> - the fundamentals of the <a href="/pkg/reflect/">reflect</a> package.</li> +<li><a href="/doc/articles/image_package.html">The Go image package</a> - the fundamentals of the <a href="/pkg/image/">image</a> package.</li> +<li><a href="/doc/articles/image_draw.html">The Go image/draw package</a> - the fundamentals of the <a href="/pkg/image/draw/">image/draw</a> package.</li> </ul> -<h3>Tools</h3> - +<h4>Tools</h4> <ul> -<li><a href="http://blog.golang.org/2011/03/c-go-cgo.html">C? Go? Cgo!</a> - linking against C code with <a href="/cmd/cgo/">cgo</a>.</li> -<li><a href="http://blog.golang.org/2011/03/godoc-documenting-go-code.html">Godoc: documenting Go code</a> - writing good documentation for <a href="/cmd/godoc/">godoc</a>.</li> +<li><a href="/doc/articles/go_command.html">About the Go command</a> - why we wrote it, what it is, what it's not, and how to use it.</li> +<li><a href="/doc/articles/c_go_cgo.html">C? Go? Cgo!</a> - linking against C code with <a href="/cmd/cgo/">cgo</a>.</li> +<li><a href="/doc/gdb">Debugging Go Code with GDB</a></li> +<li><a href="/doc/articles/godoc_documenting_go_code.html">Godoc: documenting Go code</a> - writing good documentation for <a href="/cmd/godoc/">godoc</a>.</li> <li><a href="http://blog.golang.org/2011/06/profiling-go-programs.html">Profiling Go Programs</a></li> </ul> -<h2 id="tutorials_nonenglish">Non-English Documentation</h2> - -<h3 id="docs_be">Belarusian — Беларуская</h3> - -<ul> -<li><a href="http://www.designcontest.com/show/faq-be">faq-be</a> - Frequently Asked Questions.</li> -</ul> - -<h3 id="docs_cn">Chinese — 中文</h3> +<h2 id="talks">Talks</h2> -<ul> -<li><a href="http://code.google.com/p/golang-china/">golang-china</a> - a broad range of Go documentation.</li> -<li><a href="http://code.google.com/p/ac-me/downloads/detail?name=fango.pdf">Effective Go and Tutorial</a></li> -</ul> - -<h3 id="docs_de">German — Deutsch</h3> - -<ul> -<li><a href="http://bitloeffel.de/DOC/golang/go_tutorial_de.html">Eine Anleitung zum Programmieren in Go</a> - the Go Tutorial.</li> -<li><a href="http://bitloeffel.de/DOC/golang/effective_go_de.html">Wirkungsvoll Go programmieren</a> - Effective Go.</li> -<li><a href="http://bitloeffel.de/DOC/golang/code_de.html">Wie man Go-Kode schreibt</a> - How to Write Go Code.</li> -</ul> +<img class="gopher" src="/doc/gopher/talks.png"/> -<h3 id="docs_jp">Japanese — 日本語</h3> -<ul> -<li><a href="http://golang.jp/">golang.jp</a> - Go documentation and news. -</ul> - -<h3 id="docs_kr">Korean — 한국어</h3> -<ul> -<li><a href="http://code.google.com/p/golang-korea">golang-korea</a> - Go documentation and news. -</ul> - -<h3 id="docs_ru">Russian — Русский</h3> -<ul> -<li><a href="http://golanguage.ru/">golanguage.ru</a> - Go documentation. -</ul> - -</div> - - -<div class="right-column"> - -<h2 id="References">References</h2> - -<p>Keep these under your pillow.</p> - -<h3 id="pkg"><a href="/pkg/">Package Documentation</a></h3> -<p> -The built-in documentation for the Go standard library. -</p> - -<h3 id="cmd"><a href="/cmd/">Command Documentation</a></h3> -<p> -The built-in documentation for the Go tools. -</p> - -<h3 id="spec"><a href="go_spec.html">Language Specification</a></h3> -<p> -The official Go Language specification. -</p> - -<h3 id="release"><a href="devel/release.html">Release History</a></h3> -<p>A summary of the changes between Go releases.</p> - -<h3 id="go_mem"><a href="go_mem.html">The Go Memory Model</a></h3> <p> -A document that specifies the conditions under which reads of a variable in -one goroutine can be guaranteed to observe values produced by writes to the -same variable in a different goroutine. +The talks marked with a red asterisk (<font color="red">*</font>) were written +before Go 1 and contain some examples that are no longer correct, but they are +still of value. </p> -<h3 id="debugging_with_gdb"><a href="debugging_with_gdb.html">Debugging Go Code with GDB</a></h3> -<p> -Using GDB to debug Go programs. -</p> - -<h2 id="videos_talks">Videos and Talks</h2> - -<h3 id="writing_web_apps"><a href="http://www.youtube.com/watch?v=-i0hat7pdpk">Writing Web Apps in Go</a></h3> +<h3 id="writing_web_apps"><a href="http://www.youtube.com/watch?v=-i0hat7pdpk">Writing Web Apps in Go</a><font color="red">*</font></h3> <p> A talk by Rob Pike and Andrew Gerrand presented at Google I/O 2011. It walks through the construction and deployment of a simple web application @@ -206,7 +147,7 @@ and unveils the <a href="http://blog.golang.org/2011/05/go-and-google-app-engine See the <a href="/doc/talks/io2011/Writing_Web_Apps_in_Go.pdf">presentation slides</a>. </p> -<h3 id="real_world_go"><a href="http://www.youtube.com/watch?v=7QDVRowyUQA">Real World Go</a></h3> +<h3 id="real_world_go"><a href="http://www.youtube.com/watch?v=7QDVRowyUQA">Real World Go</a><font color="red">*</font></h3> <p> A talk by Andrew Gerrand presented at Google I/O Bootcamp 2011. It gives a broad overview of Go's type system and concurrency model @@ -214,15 +155,22 @@ and provides four examples of Go programs that solve real problems. See the <a href="/doc/talks/io2011/Real_World_Go.pdf">presentation slides</a>. </p> -<h3 id="go_programming"><a href="http://www.youtube.com/watch?v=jgVhBThJdXc">Go Programming</a></h3> +<h3 id="integrated_apps"><a href="http://www.youtube.com/watch?v=Mo1YKpIF1PQ">Building Integrated Apps on Google's Cloud Platform</a></h3> +<p> +A talk by Andrew Gerrand presented at Google Developer Day Japan 2011. +It discusses the development of a web application that runs on Google +App Engine and renders images that it stores on Google Cloud Storage. +</p> + +<h3 id="go_programming"><a href="http://www.youtube.com/watch?v=jgVhBThJdXc">Go Programming</a><font color="red">*</font></h3> <p> A presentation delivered by Rob Pike and Russ Cox at Google I/O 2010. It illustrates how programming in Go differs from other languages through a set of examples demonstrating features particular to Go. These include concurrency, -embedded types, methods on any type, and program construction using interfaces. +embedded types, methods on any type, and program construction using interfaces. </p> -<h3 id="practical_go_programming"><a href="http://osdc.blip.tv/file/4432146/">Practical Go Programming</a></h3> +<h3 id="practical_go_programming"><a href="http://www.youtube.com/watch?v=2-pPAvqyluI">Practical Go Programming</a><font color="red">*</font></h3> <p> This talk presents the development of a complete web application in Go. It looks at design, storage, concurrency, and scaling issues in detail, using @@ -230,63 +178,37 @@ the simple example of an URL shortening service. See the <a href="http://wh3rd.net/practical-go/">presentation slides</a>. </p> -<h3 id="techtalk"><a href="http://www.youtube.com/watch?v=rKnDgT73v8s">The Go Tech Talk</a></h3> +<h4 id="talks_more">More</h4> <p> -An hour-long talk delivered by Rob Pike at Google in October 2009. -The language's first public introduction. (See the <a href="talks/go_talk-20091030.pdf">slides in PDF format</a>.) The language has changed since it was made, -but it's still a good introduction. +See the <a href="http://code.google.com/p/go-wiki/wiki/GoTalks">GoTalks +page</a> at the <a href="http://code.google.com/p/go-wiki/wiki">Go Wiki</a> for +more Go talks. </p> -<h3 id="gocoding_channel"><a href="http://www.youtube.com/gocoding">gocoding YouTube Channel</a></h3> -<p> -A YouTube channel that includes screencasts and other Go-related videos: -</p> -<ul> -<li><a href="http://www.youtube.com/gocoding#p/u/0/jDWBJOXs_iI">Screencast: Writing Go Packages</a> - writing, building, and distributing Go packages.</li> -<li><a href="http://www.youtube.com/watch?v=3brH0zOqm0w">Screencast: Testing Go Packages</a> - writing unit tests and benchmarking Go packages.</li> -</ul> +<h2 id="nonenglish">Non-English Documentation</h2> -<h3 id="jaoo_go"><a href="/doc/ExpressivenessOfGo.pdf">The Expressiveness Of Go</a></h3> <p> -A discussion of the qualities that make Go an expressive and comprehensible -language. The talk was presented by Rob Pike at JAOO 2010. -The recording of the event was lost due to a hardware error. +See the <a href="http://code.google.com/p/go-wiki/wiki/NonEnglish">NonEnglish</a> page +at the <a href="http://code.google.com/p/go-wiki/wiki">Go Wiki</a> for localized +documentation. </p> -<h3 id="oscon_go"><a href="http://www.oscon.com/oscon2010/public/schedule/detail/14760">Another Go at Language Design</a></h3> -<p> -A tour, with some background, of the major features of Go, intended for -an audience new to the language. The talk was presented at OSCON 2010. -See the <a href="http://assets.en.oreilly.com/1/event/45/Another%20Go%20at%20Language%20Design%20Presentation.pdf">presentation slides</a>. -</p> -<p> -This talk was also delivered at Sydney University in September 2010. A video -of the lecture is available -<a href="http://sydney.edu.au/engineering/it/videos/seminar_pike">here</a>. -</p> +<h2 id="community">The Go Community</h2> -<h3 id="emerging_go"><a href="http://www.oscon.com/oscon2010/public/schedule/detail/15464">Go Emerging Languages Conference Talk</a></h3> -<p> -Rob Pike's Emerging Languages Conference presentation delivered in July 2010. See the <a href="http://assets.en.oreilly.com/1/event/45/Go%20Presentation.pdf">presentation slides</a>. Abstract: -</p> -<p><i> -Go’s approach to concurrency differs from that of many languages, even those -(such as Erlang) that make concurrency central, yet it has deep roots. The path -from Hoare’s 1978 paper to Go provides insight into how and why Go works as it -does. -</i></p> - -<h3 id="go_frontend_gcc"><a href="talks/gofrontend-gcc-summit-2010.pdf">The Go frontend for GCC</a></h3> -<p> -A description of the Go language frontend for gcc. -Ian Lance Taylor's paper delivered at the GCC Summit 2010. -</p> +<img class="gopher" src="/doc/gopher/project.png"/> -<h3 id="promo_video"><a href="http://www.youtube.com/watch?v=wwoWei-GAPo">The Go Promo Video</a></h3> -<p> -A short promotional video featuring Russ Cox demonstrating Go's fast compiler. -</p> +<h3 id="mailinglist"><a href="http://groups.google.com/group/golang-nuts">Go Nuts Mailing List</a></h3> +<p>The <a href="http://groups.google.com/group/golang-nuts">golang-nuts</a> +mailing list is for general Go discussion.</p> + +<h3 id="projects"><a href="http://godashboard.appspot.com/project">Go Project Dashboard</a></h3> +<p>A list of external Go projects including programs and libraries.</p> + +<h3 id="irc"><a href="irc:irc.freenode.net/go-nuts">Go IRC Channel</a></h3> +<p><b>#go-nuts</b> on <b>irc.freenode.net</b> is the official Go IRC channel.</p> -</div> +<h3 id="plus"><a href="https://plus.google.com/101406623878176903605/posts">The Go Programming Language at Google+</a></h3> +<p>The Go project's Google+ page.</p> -<div class="end-columns"></div> +<h3 id="twitter"><a href="http://twitter.com/go_nuts">@go_nuts at Twitter</a></h3> +<p>The Go project's official Twitter account.</p> diff --git a/doc/effective_go.html b/doc/effective_go.html index 37cb516b0..ed777f4bb 100644 --- a/doc/effective_go.html +++ b/doc/effective_go.html @@ -1,4 +1,7 @@ -<!-- Effective Go --> +<!--{ + "Title": "Effective Go", + "Template": true +}--> <h2 id="introduction">Introduction</h2> @@ -24,8 +27,10 @@ will be easy for other Go programmers to understand. <p> This document gives tips for writing clear, idiomatic Go code. -It augments the <a href="go_spec.html">language specification</a> -and the <a href="go_tutorial.html">tutorial</a>, both of which you +It augments the <a href="/ref/spec">language specification</a>, +the <a href="http://tour.golang.org/">Tour of Go</a>, +and <a href="/doc/code.html">How to Write Go Code</a>, +all of which you should read first. </p> @@ -59,7 +64,10 @@ prescriptive style guide. With Go we take an unusual approach and let the machine take care of most formatting issues. -The <code>gofmt</code> tool reads a Go program +The <code>gofmt</code> program +(also available as <code>go fmt</code>, which +operates at the package level rather than source file level) +reads a Go program and emits the source in a standard style of indentation and vertical alignment, retaining and if necessary reformatting comments. @@ -221,7 +229,7 @@ starts with the name being declared. <pre> // Compile parses a regular expression and returns, if successful, a Regexp // object that can be used to match against text. -func Compile(str string) (regexp *Regexp, error os.Error) { +func Compile(str string) (regexp *Regexp, err error) { </pre> <p> @@ -233,9 +241,9 @@ Since the whole declaration is presented, such a comment can often be perfunctor <pre> // Error codes returned by failures to parse an expression. var ( - ErrInternal = os.NewError("regexp: internal error") - ErrUnmatchedLpar = os.NewError("regexp: unmatched '('") - ErrUnmatchedRpar = os.NewError("regexp: unmatched ')'") + ErrInternal = errors.New("regexp: internal error") + ErrUnmatchedLpar = errors.New("regexp: unmatched '('") + ErrUnmatchedRpar = errors.New("regexp: unmatched ')'") ... ) </pre> @@ -526,12 +534,62 @@ if err != nil { } d, err := f.Stat() if err != nil { + f.Close() return err } codeUsing(f, d) </pre> +<h3 id="redeclaration">Redeclaration</h3> + +<p> +An aside: The last example in the previous section demonstrates a detail of how the +<code>:=</code> short declaration form works. +The declaration that calls <code>os.Open</code> reads, +</p> + +<pre> +f, err := os.Open(name) +</pre> + +<p> +This statement declares two variables, <code>f</code> and <code>err</code>. +A few lines later, the call to <code>f.Stat</code> reads, +</p> + +<pre> +d, err := f.Stat() +</pre> + +<p> +which looks as if it declares <code>d</code> and <code>err</code>. +Notice, though, that <code>err</code> appears in both statements. +This duplication is legal: <code>err</code> is declared by the first statement, +but only <em>re-assigned</em> in the second. +This means that the call to <code>f.Stat</code> uses the existing +<code>err</code> variable declared above, and just gives it a new value. +</p> + +<p> +In a <code>:=</code> declaration a variable <code>v</code> may appear even +if it has already been declared, provided: +</p> + +<ul> +<li>this declaration is in the same scope as the existing declaration of <code>v</code> +(if <code>v</code> is already declared in an outer scope, the declaration will create a new variable),</li> +<li>the corresponding value in the initialization is assignable to <code>v</code>, and</li> +<li>there is at least one other variable in the declaration that is being declared anew.</li> +</ul> + +<p> +This unusual property is pure pragmatism, +making it easy to use a single <code>err</code> value, for example, +in a long <code>if-else</code> chain. +You'll see it used often. +</p> + <h3 id="for">For</h3> <p> @@ -567,9 +625,28 @@ or reading from a channel, a <code>range</code> clause can manage the loop. </p> <pre> -var m map[string]int +for key, value := range oldMap { + newMap[key] = value +} +</pre> + +<p> +If you only need the first item in the range (the key or index), drop the second: +</p> +<pre> +for key := range m { + if expired(key) { + delete(m, key) + } +} +</pre> + +<p> +If you only need the second item in the range (the value), use the <em>blank identifier</em>, an underscore, to discard the first: +</p> +<pre> sum := 0 -for _, value := range m { // key is unused +for _, value := range array { sum += value } </pre> @@ -651,7 +728,7 @@ func shouldEscape(c byte) bool { Here's a comparison routine for byte arrays that uses two <code>switch</code> statements: <pre> -// Compare returns an integer comparing the two byte arrays +// Compare returns an integer comparing the two byte arrays, // lexicographically. // The result will be 0 if a == b, -1 if a < b, and +1 if a > b func Compare(a, b []byte) int { @@ -713,16 +790,16 @@ error code secreted away in a volatile location. In Go, <code>Write</code> can return a count <i>and</i> an error: “Yes, you wrote some bytes but not all of them because you filled the device”. -The signature of <code>*File.Write</code> in package <code>os</code> is: +The signature of <code>File.Write</code> in package <code>os</code> is: </p> <pre> -func (file *File) Write(b []byte) (n int, err Error) +func (file *File) Write(b []byte) (n int, err error) </pre> <p> and as the documentation says, it returns the number of bytes -written and a non-nil <code>Error</code> when <code>n</code> +written and a non-nil <code>error</code> when <code>n</code> <code>!=</code> <code>len(b)</code>. This is a common style; see the section on error handling for more examples. </p> @@ -788,12 +865,12 @@ of <code>io.ReadFull</code> that uses them well: </p> <pre> -func ReadFull(r Reader, buf []byte) (n int, err os.Error) { +func ReadFull(r Reader, buf []byte) (n int, err error) { for len(buf) > 0 && err == nil { var nr int nr, err = r.Read(buf) n += nr - buf = buf[nr:len(buf)] + buf = buf[nr:] } return } @@ -812,7 +889,7 @@ canonical examples are unlocking a mutex or closing a file. <pre> // Contents returns the file's contents as a string. -func Contents(filename string) (string, os.Error) { +func Contents(filename string) (string, error) { f, err := os.Open(filename) if err != nil { return "", err @@ -825,7 +902,7 @@ func Contents(filename string) (string, os.Error) { n, err := f.Read(buf[0:]) result = append(result, buf[0:n]...) // append is discussed later. if err != nil { - if err == os.EOF { + if err == io.EOF { break } return "", err // f will be closed if we return here. @@ -945,7 +1022,7 @@ but the rules are simple. Let's talk about <code>new</code> first. It's a built-in function that allocates memory, but unlike its namesakes in some other languages it does not <em>initialize</em> the memory, -it only <em>zeroes</em> it. +it only <em>zeros</em> it. That is, <code>new(T)</code> allocates zeroed storage for a new item of type <code>T</code> and returns its address, a value of type <code>*T</code>. @@ -954,8 +1031,9 @@ In Go terminology, it returns a pointer to a newly allocated zero value of type </p> <p> -Since the memory returned by <code>new</code> is zeroed, it's helpful to arrange that the -zeroed object can be used without further initialization. This means a user of +Since the memory returned by <code>new</code> is zeroed, it's helpful to arrange +when designing your data structures that the +zero value of each type can be used without further initialization. This means a user of the data structure can create one with <code>new</code> and get right to work. For example, the documentation for <code>bytes.Buffer</code> states that @@ -1075,8 +1153,9 @@ m := map[int]string{Enone: "no error", Eio: "Eio", Einval: "invalid argument"} Back to allocation. The built-in function <code>make(T, </code><i>args</i><code>)</code> serves a purpose different from <code>new(T)</code>. -It creates slices, maps, and channels only, and it returns an initialized (not zero) -value of type <code>T</code>, not <code>*T</code>. +It creates slices, maps, and channels only, and it returns an <em>initialized</em> +(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 must be initialized before use. @@ -1193,7 +1272,7 @@ limit of how much data to read. Here is the signature of the <code>os</code>: </p> <pre> -func (file *File) Read(buf []byte) (n int, err os.Error) +func (file *File) Read(buf []byte) (n int, err error) </pre> <p> The method returns the number of bytes read and an error value, if @@ -1205,11 +1284,11 @@ any. To read into the first 32 bytes of a larger buffer </pre> <p> Such slicing is common and efficient. In fact, leaving efficiency aside for -the moment, this snippet would also read the first 32 bytes of the buffer. +the moment, the following snippet would also read the first 32 bytes of the buffer. </p> <pre> var n int - var err os.Error + var err error for i := 0; i < 32; i++ { nbytes, e := f.Read(buf[i:i+1]) // Read one byte. if nbytes == 0 || e != nil { @@ -1267,9 +1346,9 @@ values of different types. The key can be of any type for which the equality operator is defined, such as integers, floating point and complex numbers, -strings, pointers, and interfaces (as long as the dynamic type -supports equality). Structs, arrays and slices cannot be used as map keys, -because equality is not defined on those types. +strings, pointers, interfaces (as long as the dynamic type +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 that changes the contents of the map, the changes will be visible in the caller. @@ -1347,7 +1426,7 @@ func offset(tz string) int { </pre> <p> To test for presence in the map without worrying about the actual value, -you can use the <em>blank identifier</em>, a simple underscore (<code>_</code>). +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. @@ -1356,13 +1435,13 @@ identifier in place of the usual variable for the value. _, present := timeZone[tz] </pre> <p> -To delete a map entry, turn the multiple assignment around by placing -an extra boolean on the right; if the boolean is false, the entry -is deleted. It's safe to do this even if the key is already absent +To delete a map entry, use the <code>delete</code> +built-in function, whose arguments are the map and the key to be deleted. +It's safe to do this this even if the key is already absent from the map. </p> <pre> -timeZone["PDT"] = 0, false // Now on Standard Time +delete(timeZone, "PDT") // Now on Standard Time </pre> <h3 id="printing">Printing</h3> @@ -1392,7 +1471,7 @@ fmt.Println(fmt.Sprint("Hello ", 23)) </pre> <p> As mentioned in -the <a href="go_tutorial.html">tutorial</a>, <code>fmt.Fprint</code> +the <a href="http://tour.golang.org">Tour</a>, <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. @@ -1437,7 +1516,7 @@ format <code>%#v</code> prints the value in full Go syntax. <pre> type T struct { a int - b float + b float64 c string } t := &T{ 7, -2.35, "abc\tdef" } @@ -1507,7 +1586,7 @@ for its final argument to specify that an arbitrary number of parameters (of arb can appear after the format. </p> <pre> -func Printf(format string, v ...interface{}) (n int, errno os.Error) { +func Printf(format string, v ...interface{}) (n int, err error) { </pre> <p> Within the function <code>Printf</code>, <code>v</code> acts like a variable of type @@ -1553,40 +1632,49 @@ Now we have the missing piece we needed to explain the design of the <code>append</code> built-in function. The signature of <code>append</code> 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> </pre> +<p> where <i>T</i> is a placeholder for any given type. You can't actually write a function in Go where the type <code>T</code> is determined by the caller. That's why <code>append</code> is built in: it needs support from the compiler. +</p> <p> What <code>append</code> does is append the elements to the end of the slice and return the result. The result needs to be returned because, as with our hand-written <code>Append</code>, the underlying array may change. This simple example +</p> <pre> x := []int{1,2,3} x = append(x, 4, 5, 6) fmt.Println(x) </pre> +<p> prints <code>[1 2 3 4 5 6]</code>. So <code>append</code> works a little like <code>Printf</code>, collecting an arbitrary number of arguments. +</p> <p> But what if we wanted to do what our <code>Append</code> does and append a slice to a slice? Easy: use <code>...</code> at the call site, just as we did in the call to <code>Output</code> above. This snippet produces identical output to the one above. +</p> <pre> x := []int{1,2,3} y := []int{4,5,6} x = append(x, y...) fmt.Println(x) </pre> +<p> Without that <code>...</code>, it wouldn't compile because the types would be wrong; <code>y</code> is not of type <code>int</code>. +</p> <h2 id="initialization">Initialization</h2> @@ -1620,56 +1708,28 @@ enumerator. Since <code>iota</code> can be part of an expression and expressions can be implicitly repeated, it is easy to build intricate sets of values. </p> -<pre> -type ByteSize float64 -const ( - _ = iota // ignore first value by assigning to blank identifier - KB ByteSize = 1<<(10*iota) - MB - GB - TB - PB - EB - ZB - YB -) -</pre> +{{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. </p> -<pre> -func (b ByteSize) String() string { - switch { - case b >= YB: - return fmt.Sprintf("%.2fYB", float64(b/YB)) - case b >= ZB: - return fmt.Sprintf("%.2fZB", float64(b/ZB)) - case b >= EB: - return fmt.Sprintf("%.2fEB", float64(b/EB)) - case b >= PB: - return fmt.Sprintf("%.2fPB", float64(b/PB)) - case b >= TB: - return fmt.Sprintf("%.2fTB", float64(b/TB)) - case b >= GB: - return fmt.Sprintf("%.2fGB", float64(b/GB)) - case b >= MB: - return fmt.Sprintf("%.2fMB", float64(b/MB)) - case b >= KB: - return fmt.Sprintf("%.2fKB", float64(b/KB)) - } - return fmt.Sprintf("%.2fB", float64(b)) -} -</pre> +{{code "/doc/progs/eff_bytesize.go" `/^func.*ByteSize.*String/` `/^}/`}} <p> -(The <code>float64</code> conversions prevent <code>Sprintf</code> -from recurring back through the <code>String</code> method for -<code>ByteSize</code>.) The expression <code>YB</code> prints as <code>1.00YB</code>, 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>. +</p> + <h3 id="variables">Variables</h3> <p> @@ -1689,10 +1749,7 @@ var ( <p> Finally, each source file can define its own niladic <code>init</code> function to set up whatever state is required. (Actually each file can have multiple -<code>init</code> functions.) The only restriction is that, although -goroutines can be launched during initialization, they will not begin -execution until it completes; initialization always runs as a single thread -of execution. +<code>init</code> functions.) And finally means finally: <code>init</code> is called after all the variable declarations in the package have evaluated their initializers, and those are evaluated only after all the imported packages have been @@ -1757,7 +1814,7 @@ In fact, we can do even better. If we modify our function so it looks like a standard <code>Write</code> method, like this, </p> <pre> -func (p *ByteSlice) Write(data []byte) (n int, err os.Error) { +func (p *ByteSlice) Write(data []byte) (n int, err error) { slice := *p // Again as above. *p = slice @@ -1810,33 +1867,7 @@ by the routines in package <code>sort</code> if it implements and it could also have a custom formatter. In this contrived example <code>Sequence</code> satisfies both. </p> -<pre> -type Sequence []int - -// Methods required by sort.Interface. -func (s Sequence) Len() int { - return len(s) -} -func (s Sequence) Less(i, j int) bool { - return s[i] < s[j] -} -func (s Sequence) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} - -// Method for printing - sorts the elements before printing. -func (s Sequence) String() string { - sort.Sort(s) - str := "[" - for i, elem := range s { - if i > 0 { - str += " " - } - str += fmt.Sprint(elem) - } - return str + "]" -} -</pre> +{{code "/doc/progs/eff_sequence.go" `/^type/` "$"}} <h3 id="conversions">Conversions</h3> @@ -1868,7 +1899,7 @@ do create a new value.) It's an idiom in Go programs to convert the type of an expression to access a different set of methods. As an example, we could use the existing -type <code>sort.IntArray</code> to reduce the entire example +type <code>sort.IntSlice</code> to reduce the entire example to this: </p> <pre> @@ -1876,14 +1907,14 @@ type Sequence []int // Method for printing - sorts the elements before printing func (s Sequence) String() string { - sort.IntArray(s).Sort() + sort.IntSlice(s).Sort() return fmt.Sprint([]int(s)) } </pre> <p> Now, instead of having <code>Sequence</code> implement multiple interfaces (sorting and printing), we're using the ability of a data item to be -converted to multiple types (<code>Sequence</code>, <code>sort.IntArray</code> +converted to multiple types (<code>Sequence</code>, <code>sort.IntSlice</code> and <code>[]int</code>), each of which does some part of the job. That's more unusual in practice but can be effective. </p> @@ -1912,42 +1943,53 @@ the rest of the code is unaffected by the change of algorithm. </p> <p> A similar approach allows the streaming cipher algorithms -in the <code>crypto/block</code> package to be +in the various <code>crypto</code> packages to be separated from the block ciphers they chain together. -By analogy with the <code>bufio</code> package, -they wrap a <code>Cipher</code> interface -and return <code>hash.Hash</code>, -<code>io.Reader</code>, or <code>io.Writer</code> -interface values, not specific implementations. +The <code>Block</code> interface +in the <code>crypto/cipher</code> package specifies the +behavior of a block cipher, which provides encryption +of a single block of data. +Then, by analogy with the <code>bufio</code> package, +cipher packages that implement this interface +can be used to construct streaming ciphers, represented +by the <code>Stream</code> interface, without +knowing the details of the block encryption. </p> <p> -The interface to <code>crypto/block</code> includes: +The <code>crypto/cipher</code> interfaces look like this: </p> <pre> -type Cipher interface { +type Block interface { BlockSize() int Encrypt(src, dst []byte) Decrypt(src, dst []byte) } -// NewECBDecrypter returns a reader that reads data -// from r and decrypts it using c in electronic codebook (ECB) mode. -func NewECBDecrypter(c Cipher, r io.Reader) io.Reader +type Stream interface { + XORKeyStream(dst, src []byte) +} +</pre> + +<p> +Here's the definition of the counter mode (CTR) stream, +which turns a block cipher into a streaming cipher; notice +that the block cipher's details are abstracted away: +</p> -// NewCBCDecrypter returns a reader that reads data -// from r and decrypts it using c in cipher block chaining (CBC) mode -// with the initialization vector iv. -func NewCBCDecrypter(c Cipher, iv []byte, r io.Reader) io.Reader +<pre> +// NewCTR returns a Stream that encrypts/decrypts using the given Block in +// counter mode. The length of iv must be the same as the Block's block size. +func NewCTR(block Block, iv []byte) Stream </pre> <p> -<code>NewECBDecrypter</code> and <code>NewCBCReader</code> apply not +<code>NewCTR</code> applies not just to one specific encryption algorithm and data source but to any -implementation of the <code>Cipher</code> interface and any -<code>io.Reader</code>. Because they return <code>io.Reader</code> -interface values, replacing ECB -encryption with CBC encryption is a localized change. The constructor +implementation of the <code>Block</code> interface and any +<code>Stream</code>. Because they return +interface values, replacing CTR +encryption with other encryption modes is a localized change. The constructor calls must be edited, but because the surrounding code must treat the result only -as an <code>io.Reader</code>, it won't notice the difference. +as a <code>Stream</code>, it won't notice the difference. </p> <h3 id="interface_methods">Interfaces and methods</h3> @@ -1993,7 +2035,7 @@ func (ctr *Counter) ServeHTTP(w http.ResponseWriter, req *http.Request) { <code>http.ResponseWriter</code>.) For reference, here's how to attach such a server to a node on the URL tree. <pre> -import "http" +import "net/http" ... ctr := new(Counter) http.Handle("/counter", ctr) @@ -2032,7 +2074,7 @@ It's easy to write a function to print the arguments. </p> <pre> func ArgServer() { - for i, s := range os.Args { + for _, s := range os.Args { fmt.Println(s) } } @@ -2070,7 +2112,7 @@ to have the right signature. <pre> // Argument server. func ArgServer(w http.ResponseWriter, req *http.Request) { - for i, s := range os.Args { + for _, s := range os.Args { fmt.Fprintln(w, s) } } @@ -2078,8 +2120,8 @@ func ArgServer(w http.ResponseWriter, req *http.Request) { <p> <code>ArgServer</code> now has same signature as <code>HandlerFunc</code>, so it can be converted to that type to access its methods, -just as we converted <code>Sequence</code> to <code>IntArray</code> -to access <code>IntArray.Sort</code>. +just as we converted <code>Sequence</code> to <code>IntSlice</code> +to access <code>IntSlice.Sort</code>. The code to set it up is concise: </p> <pre> @@ -2116,11 +2158,11 @@ here are their definitions. </p> <pre> type Reader interface { - Read(p []byte) (n int, err os.Error) + Read(p []byte) (n int, err error) } type Writer interface { - Write(p []byte) (n int, err os.Error) + Write(p []byte) (n int, err error) } </pre> <p> @@ -2182,7 +2224,7 @@ satisfy the <code>io</code> interfaces, we would also need to provide forwarding methods, like this: </p> <pre> -func (rw *ReadWriter) Read(p []byte) (n int, err os.Error) { +func (rw *ReadWriter) Read(p []byte) (n int, err error) { return rw.reader.Read(p) } </pre> @@ -2315,7 +2357,7 @@ it can also be seen as a type-safe generalization of Unix pipes. They're called <em>goroutines</em> because the existing terms—threads, coroutines, processes, and so on—convey inaccurate connotations. A goroutine has a simple model: it is a -function executing in parallel with other goroutines in the same +function executing concurrently with other goroutines in the same address space. It is lightweight, costing little more than the allocation of stack space. And the stacks start small, so they are cheap, and grow @@ -2336,12 +2378,12 @@ exits, silently. (The effect is similar to the Unix shell's background.) </p> <pre> -go list.Sort() // run list.Sort in parallel; don't wait for it. +go list.Sort() // run list.Sort concurrently; don't wait for it. </pre> <p> A function literal can be handy in a goroutine invocation. <pre> -func Announce(message string, delay int64) { +func Announce(message string, delay time.Duration) { go func() { time.Sleep(delay) fmt.Println(message) @@ -2504,8 +2546,8 @@ system, and there's not a mutex in sight. <p> Another application of these ideas is to parallelize a calculation across multiple CPU cores. If the calculation can be broken into -separate pieces, it can be parallelized, with a channel to signal -when each piece completes. +separate pieces that can execute independently, it can be parallelized, +with a channel to signal when each piece completes. </p> <p> Let's say we have an expensive operation to perform on a vector of items, @@ -2547,7 +2589,7 @@ func (v Vector) DoAll(u Vector) { </pre> <p> -The current implementation of <code>gc</code> (<code>6g</code>, etc.) +The current implementation of the Go runtime will not parallelize this code by default. It dedicates only a single core to user-level processing. An arbitrary number of goroutines can be blocked in system calls, but @@ -2557,8 +2599,10 @@ is if you want CPU parallelism you must tell the run-time how many goroutines you want executing code simultaneously. There are two related ways to do this. Either run your job with environment variable <code>GOMAXPROCS</code> set to the number of cores to use -(default 1); or import the <code>runtime</code> package and call +or import the <code>runtime</code> package and call <code>runtime.GOMAXPROCS(NCPU)</code>. +A helpful value might be <code>runtime.NumCPU()</code>, which reports the number +of logical CPUs on the local machine. Again, this requirement is expected to be retired as the scheduling and run-time improve. </p> @@ -2634,12 +2678,12 @@ the garbage collector for bookkeeping. Library routines must often return some sort of error indication to the caller. As mentioned earlier, Go's multivalue return makes it easy to return a detailed error description alongside the normal -return value. By convention, errors have type <code>os.Error</code>, -a simple interface. +return value. By convention, errors have type <code>error</code>, +a simple built-in interface. </p> <pre> -type Error interface { - String() string +type error interface { + Error() string } </pre> <p> @@ -2654,15 +2698,15 @@ For example, <code>os.Open</code> returns an <code>os.PathError</code>. type PathError struct { Op string // "open", "unlink", etc. Path string // The associated file. - Error Error // Returned by the system call. + Err error // Returned by the system call. } -func (e *PathError) String() string { - return e.Op + " " + e.Path + ": " + e.Error.String() +func (e *PathError) Error() string { + return e.Op + " " + e.Path + ": " + e.Err.Error() } </pre> <p> -<code>PathError</code>'s <code>String</code> generates +<code>PathError</code>'s <code>Error</code> generates a string like this: </p> <pre> @@ -2679,25 +2723,25 @@ 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 -image, the string representation for a decoding error due to an unknown format -is "image: unknown format". +<code>image</code>, the string representation for a decoding error due to an +unknown format is "image: unknown format". </p> <p> Callers that care about the precise error details can use a type switch or a type assertion to look for specific errors and extract details. For <code>PathErrors</code> -this might include examining the internal <code>Error</code> +this might include examining the internal <code>Err</code> field for recoverable failures. </p> <pre> for try := 0; try < 2; try++ { - file, err = os.Open(filename) + file, err = os.Create(filename) if err == nil { return } - if e, ok := err.(*os.PathError); ok && e.Error == os.ENOSPC { + if e, ok := err.(*os.PathError); ok && e.Err == syscall.ENOSPC { deleteTempFiles() // Recover some space. continue } @@ -2705,13 +2749,25 @@ for try := 0; try < 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> +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>, +which we can examine for more information about the error. +</p> + <h3 id="panic">Panic</h3> <p> The usual way to report an error to a caller is to return an -<code>os.Error</code> as an extra return value. The canonical +<code>error</code> as an extra return value. The canonical <code>Read</code> method is a well-known instance; it returns a byte -count and an <code>os.Error</code>. But what if the error is +count and an <code>error</code>. But what if the error is unrecoverable? Sometimes the program simply cannot continue. </p> @@ -2827,14 +2883,14 @@ 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 parsing errors by calling <code>panic</code> with a local -<code>Error</code> type. Here's the definition of <code>Error</code>, +error type. Here's the definition of <code>Error</code>, an <code>error</code> method, and the <code>Compile</code> function. </p> <pre> -// Error is the type of a parse error; it satisfies os.Error. +// Error is the type of a parse error; it satisfies the error interface. type Error string -func (e Error) String() string { +func (e Error) Error() string { return string(e) } @@ -2845,7 +2901,7 @@ func (regexp *Regexp) error(err string) { } // Compile returns a parsed representation of the regular expression. -func Compile(str string) (regexp *Regexp, err os.Error) { +func Compile(str string) (regexp *Regexp, err error) { regexp = new(Regexp) // doParse will panic if there is a parse error. defer func() { @@ -2863,7 +2919,7 @@ If <code>doParse</code> panics, the recovery block will set the return value to <code>nil</code>—deferred functions can modify named return values. It then will then check, in the assignment to <code>err</code>, that the problem was a parse error by asserting -that it has type <code>Error</code>. +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 @@ -2881,7 +2937,7 @@ the parse stack by hand. <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 -<code>os.Error</code> values; it does not expose <code>panics</code> +<code>error</code> values; it does not expose <code>panics</code> to its client. That is a good rule to follow. </p> @@ -2917,66 +2973,7 @@ for instance, a URL, saving you typing the URL into the phone's tiny keyboard. Here's the complete program. An explanation follows. </p> - -<pre> -package main - -import ( - "flag" - "http" - "io" - "log" - "old/template" // New template package coming soon... -) - -var addr = flag.String("addr", ":1718", "http service address") // Q=17, R=18 -var fmap = template.FormatterMap{ - "html": template.HTMLFormatter, - "url+html": UrlHtmlFormatter, -} -var templ = template.MustParse(templateStr, fmap) - -func main() { - flag.Parse() - http.Handle("/", http.HandlerFunc(QR)) - err := http.ListenAndServe(*addr, nil) - if err != nil { - log.Fatal("ListenAndServe:", err) - } -} - -func QR(w http.ResponseWriter, req *http.Request) { - templ.Execute(w, req.FormValue("s")) -} - -func UrlHtmlFormatter(w io.Writer, fmt string, v ...interface{}) { - template.HTMLEscape(w, []byte(http.URLEscape(v[0].(string)))) -} - - -const templateStr = ` -<html> -<head> -<title>QR Link Generator</title> -</head> -<body> -{.section @} -<img src="http://chart.apis.google.com/chart?chs=300x300&cht=qr&choe=UTF-8&chl={@|url+html}" -/> -<br> -{@|html} -<br> -<br> -{.end} -<form action="/" name=f method="GET"><input maxLength=1024 size=70 -name=s value="" title="Text to QR Encode"><input type=submit -value="Show QR" name=qr> -</form> -</body> -</html> -` -</pre> - +{{code "/doc/progs/eff_qr.go"}} <p> The pieces up to <code>main</code> should be easy to follow. The one flag sets a default HTTP port for our server. The template @@ -2995,34 +2992,30 @@ server; it blocks while the server runs. executes the template on the data in the form value named <code>s</code>. </p> <p> -The template package, inspired by <a -href="http://code.google.com/p/json-template">json-template</a>, is -powerful; +The template package is powerful; this program just touches on its capabilities. In essence, it rewrites a piece of text on the fly by substituting elements derived from data items passed to <code>templ.Execute</code>, in this case the form value. Within the template text (<code>templateStr</code>), -brace-delimited pieces denote template actions. -The piece from the <code>{.section @}</code> -to <code>{.end}</code> executes with the value of the data item <code>@</code>, -which is a shorthand for “the current item”, which is the form value. -(When the string is empty, this piece of the template is suppressed.) +double-brace-delimited pieces denote template actions. +The piece from <code>{{html "{{if .}}"}}</code> +to <code>{{html "{{end}}"}}</code> executes only if the value of the current data item, called <code>.</code> (dot), +is non-empty. +That is, when the string is empty, this piece of the template is suppressed. </p> <p> -The snippet <code>{@|url+html}</code> says to run the data through the formatter -installed in the formatter map (<code>fmap</code>) -under the name <code>"url+html"</code>. -That is the function <code>UrlHtmlFormatter</code>, which sanitizes the string +The snippet <code>{{html "{{urlquery .}}"}}</code> says to process the data with the function +<code>urlquery</code>, which sanitizes the query string for safe display on the web page. </p> <p> The rest of the template string is just the HTML to show when the page loads. -If this is too quick an explanation, see the <a href="/pkg/template/">documentation</a> +If this is too quick an explanation, see the <a href="/pkg/text/template/">documentation</a> for the template package for a more thorough discussion. </p> <p> -And there you have it: a useful webserver in a few lines of code plus some +And there you have it: a useful web server in a few lines of code plus some data-driven HTML text. Go is powerful enough to make a lot happen in a few lines. </p> diff --git a/doc/frontpage.css b/doc/frontpage.css deleted file mode 100644 index 299855ce9..000000000 --- a/doc/frontpage.css +++ /dev/null @@ -1,143 +0,0 @@ -/* Overloads to all.css */ -#container { width: 76em } -.left-column { width: 48%; } -.right-column { width: 48%; } - -/* Frontpage styles */ -#content-introductory code { - font-family: "Bitstream Vera Sans Mono", "Andale Mono", monospace; -} -#content-introductory input, select, textarea { - font-family: "Bitstream Vera Sans", Verdana, sans-serif; - font-size: 1em; -} -span.keyword { - font-family: Cambria, Georgia, Times, "Times New Roman", serif; - font-size: 1.15em; - font-style: italic; -} -#content h3, #content h2 { - margin: 0; - font-size: 1em; - background: none; - border: none; - padding: 0; -} -#content .more { - color: #999; - font-weight: normal; -} -#frontpage h2#branding-tagline { - font-weight: normal; - font-style: italic; -} -#resources { - position: relative; - margin-top: 1em; -} -#resources h3 { - margin-top: 0; - margin-bottom: -.5em; - font-size: 1em; - font-weight: normal; -} -#resources-users { - float: left; - width: 48%; -} -#resources-contributors { - float: right; - width: 50%; -} -#resources ul { - padding-left: 2em; -} -#resources li { - margin-bottom: 0.5em; -} -#content-rotating { - height: 200px; -} -#content-videos { - float: left; - width: 170px; -} -#content-videos .thumbnail { - width: 150px; - height: 103px; - background-repeat: no-repeat; - border: none; -} -#content-videos .thumbnail._001 { - background: url(/doc/video-001.png); -} -#content-videos .thumbnail._002 { - background: url(/doc/video-002.png); -} -#content-videos .thumbnail._003 { - background: url(/doc/video-003.png); -} -#content-videos .thumbnail._004 { - background: url(/doc/video-004.png); -} -#content-videos .thumbnail._005 { - background: url(/doc/video-005.jpg); -} -#content-videos a.video { - display: inline-block; - width: 150px; - margin-right: .30em; - margin-top: 1.2em; -} -#content-videos a.video .caption { - display: block; - text-align: center; -} -#content-videos a.video .caption.title { - margin-top: .31em; - font-weight: bold; -} -#content-blog ul { - margin-top: 1em; - margin-left: 0; - padding-left: 0; -} -#content-blog li { - list-style: none; - margin-bottom: 1em; -} -#content-blog li a { - color: #999; - text-decoration: none; -} -#content-blog .date { - color: #999; - font-size: 0.8em; - display: inline-block; - margin-left: 0.5em; -} -#content-blog li a:link .title { - color: #04a; -} -#content-blog li a:visited .title { - color: #04a; -} -#content-blog li a:hover .title { - color: #a40; - text-decoration: underline; -} -#content-blog li a:active .title { - color: #c00; -} -.navtop { - display: none !important; -} -.how { - float: right; - font-size: 75%; -} -.unsupported { - font-weight: bold; - color: red; -} - diff --git a/doc/gccgo_contribute.html b/doc/gccgo_contribute.html index 8eeb3a5c5..8ca13e4ef 100644 --- a/doc/gccgo_contribute.html +++ b/doc/gccgo_contribute.html @@ -1,92 +1,99 @@ -<!-- Contributing to the gccgo frontend --> +<!--{ + "Title": "Contributing to the gccgo frontend" +}--> <h2>Introduction</h2> <p> -These are some notes on contributing to the <code>gccgo</code> -frontend for GCC. For information on contributing to parts of Go other -than <code>gccgo</code>, see <a href="contribute.html">Contributing to -the Go project</a>. For information on building <code>gccgo</code> -for yourself, see <a href="gccgo_install.html">Setting up and using -gccgo</a>. +These are some notes on contributing to the gccgo frontend for GCC. +For information on contributing to parts of Go other than gccgo, +see <a href="/doc/contribute.html">Contributing to the Go project</a>. For +information on building gccgo for yourself, +see <a href="/doc/gccgo_install.html">Setting up and using gccgo</a>. </p> <h2>Legal Prerequisites</h2> <p> -You must follow the <a href="contribute.html#copyright">Go copyright -rules.</a> +You must follow the <a href="/doc/contribute.html#copyright">Go copyright +rules</a> for all changes to the gccgo frontend and the associated +libgo library. Code that is part of GCC rather than gccgo must follow +the general <a href="http://gcc.gnu.org/contribute.html">GCC +contribution rules</a>. </p> <h2>Code</h2> <p> -The source code for the <code>gccgo</code> frontend may be found at +The master sources for the gccgo frontend may be found at <a href="http://code.google.com/p/gofrontend">http://code.google.com/p/gofrontend</a>. -Changes made to that project are routinely merged into the source code -hosted at <code>gcc.gnu.org</code>. The <code>gofrontend</code> -project includes only the Go frontend proper. These are the files -which in the <code>gcc</code> sources may be found in the -directories <code>gcc/go</code> and <code>libgo</code>. -The <code>gcc</code> sources also include a copy of -the <code>test</code> directory -from <a href="http://code.google.com/p/go">the main Go repository</a>. +The master sources are not buildable by themselves, but only in +conjunction with GCC (in the future, other compilers may be +supported). Changes made to the gccgo frontend are also applied to +the GCC source code repository hosted at <code>gcc.gnu.org</code>. In +the <code>gofrontend</code> repository, the <code>go</code> directory +is mirrored to the <code>gcc/go/gofrontend</code> directory in the GCC +repository, and the <code>gofrontend</code> <code>libgo</code> +directory is mirrored to the GCC <code>libgo</code> directory. In +addition, the <code>test</code> directory +from <a href="http://code.google.com/p/go">the main Go repository</a> +is mirrored to the <code>gcc/testsuite/go.test/test</code> directory +in the GCC repository. +</p> <p> -The frontend is written in C++ and as such the GNU coding standards do -not entirely apply; in writing code for the frontend, follow the -formatting of the surrounding code. Although the frontend is -currently closely tied to the rest of the <code>gcc</code> codebase, -we plan to make it more independent. Any new code that uses other -parts of <code>gcc</code> should be placed in an appropriate file, -such as <code>gogo-tree.cc</code>. Eventually -all <code>gcc</code>-specific code should migrate to -a <code>gcc-interface</code> subdirectory. +Changes to these directories always flow from the master sources to +the GCC repository. The files should never be changed in the GCC +repository except by changing them in the master sources and mirroring +them. </p> <p> -The run-time library for <code>gccgo</code> is mostly the same as the -library in <a href="http://code.google.com/p/go">the main Go -repository</a>. The library code in the Go repository is periodically -copied into the <code>gofrontend</code> and the <code>gcc</code> -repositories. Accordingly, most library changes should be made in the -main Go repository. Changes to the few <code>gccgo</code>-specific -parts of the library should follow the process described here. -The <code>gccgo</code>-specific parts of the library are everything in -the <code>libgo</code> directory except for the <code>libgo/go</code> -subdirectory. +The gccgo frontend is written in C++. It follows the GNU coding +standards to the extent that they apply to C++. In writing code for +the frontend, follow the formatting of the surrounding code. Although +the frontend is currently tied to the rest of the GCC codebase, we +plan to make it more independent. Eventually all GCC-specific code +will migrate out of the frontend proper and into GCC proper. In the +GCC sources this will generally mean moving code +from <code>gcc/go/gofrontend</code> to <code>gcc/go</code>. </p> -<h2>Testing</h2> - <p> -All patches must be tested. There are two test suites. A patch that -introduces new failures is not acceptable. +The run-time library for gccgo is mostly the same as the library +in <a href="http://code.google.com/p/go">the main Go repository</a>. +The library code in the Go repository is periodically merged into +the <code>libgo/go</code> directory of the <code>gofrontend</code> and +then the GCC repositories, using the shell +script <code>libgo/merge.sh</code>. Accordingly, most library changes +should be made in the main Go repository. The files outside +of <code>libgo/go</code> are gccgo-specific; that said, some of the +files in <code>libgo/runtime</code> are based on files +in <code>src/pkg/runtime</code> in the main Go repository. </p> +<h2>Testing</h2> + <p> -To run the compiler test suite, run <code>make check-go</code> in the -<code>gcc</code> subdirectory of your build directory. This will run -various tests underneath <code>gcc/testsuite/go.*</code>. This -includes a copy of the tests in the main Go repository, which are run -using the DejaGNU script found in -in <code>gcc/testsuite/go.test/go-test.exp</code>. Many of the -compiler tests may be run without the Go library, but some do require -the library to built first. +All patches must be tested. A patch that introduces new failures is +not acceptable. </p> <p> -To run the library test suite, run <code>make -check-target-libgo</code> in the top level of your build directory. +To run the gccgo test suite, run <code>make check-go</code> in your +build directory. This will run various tests +under <code>gcc/testsuite/go.*</code> and will also run +the <code>libgo</code> testsuite. This copy of the tests from the +main Go repository is run using the DejaGNU script found in +in <code>gcc/testsuite/go.test/go-test.exp</code>. </p> <p> -Most new tests should be submitted to the main Go repository for -copying into the <code>gccgo</code> repository. If there is a need -for specific tests for <code>gccgo</code>, they should go in +Most new tests should be submitted to the main Go repository for later +mirroring into the GCC repository. If there is a need for specific +tests for gccgo, they should go in the <code>gcc/testsuite/go.go-torture</code> -or <code>gcc/testsuite/go.dg</code> directories in -the <code>gcc.gnu.org</code> repository. +or <code>gcc/testsuite/go.dg</code> directories in the GCC repository. </p> <h2>Submitting Changes</h2> @@ -95,5 +102,5 @@ the <code>gcc.gnu.org</code> repository. Changes to the Go frontend should follow the same process as for the main Go repository, only for the <code>gofrontend</code> project rather than the <code>go</code> project. Those changes will then be -merged into the <code>gcc</code> sources. +merged into the GCC sources. </p> diff --git a/doc/gccgo_install.html b/doc/gccgo_install.html index 159fab7bb..a8d7396e5 100644 --- a/doc/gccgo_install.html +++ b/doc/gccgo_install.html @@ -1,37 +1,63 @@ -<!-- Setting up and using gccgo --> +<!--{ + "Title": "Setting up and using gccgo", + "Path": "/doc/install/gccgo" +}--> <p> -This document explains how to use <code>gccgo</code>, a compiler for -the Go language. The <code>gccgo</code> compiler is a new frontend -for <code>gcc</code>, the widely used GNU compiler. Although the -frontend itself is under a BSD-style license, <code>gccgo</code> is -normally used as part of <code>gcc</code> and is then covered by +This document explains how to use gccgo, a compiler for +the Go language. The gccgo compiler is a new frontend +for GCC, the widely used GNU compiler. Although the +frontend itself is under a BSD-style license, gccgo is +normally used as part of GCC and is then covered by the <a href="http://www.gnu.org/licenses/gpl.html">GNU General Public -License</a>. +License</a> (the license covers gccgo itself as part of GCC; it +does not cover code generated by gccgo). </p> <p> -Note that <code>gccgo</code> is not the <code>6g</code> compiler; see -the <a href="install.html">Installing Go</a> instructions for that +Note that gccgo is not the <code>gc</code> compiler; see +the <a href="/doc/install.html">Installing Go</a> instructions for that compiler. </p> +<h2 id="Releases">Releases</h2> + +<p> +The simplest way to install gccgo is to install a GCC binary release +built to include Go support. GCC binary releases are available from +<a href="http://gcc.gnu.org/install/binaries.html">various +websites</a> and are typically included as part of GNU/Linux +distributions. We expect that most people who build these binaries +will include Go support. +</p> + +<p> +The GCC 4.7.0 release includes Go support that is very close to +<a href="/doc/go1.html">Go 1</a>. Due to release timing it will not +include the last few changes to the Go 1 libraries. The GCC 4.7.1 +release should include a complete Go 1 compiler and libraries. +</p> + <h2 id="Source_code">Source code</h2> <p> -The <code>gccgo</code> source code is accessible via Subversion. The -<code>gcc</code> web site +If you cannot use a release, or prefer to build gccgo for +yourself, +the gccgo source code is accessible via Subversion. The +GCC web site has <a href="http://gcc.gnu.org/svn.html">instructions for getting the -<code>gcc</code> source code</a>. The <code>gccgo</code> source code -is a branch of the main <code>gcc</code> code +GCC source code</a>. The gccgo source code is included. As a +convenience, a stable version of the Go support is available in +a branch of the main GCC code repository: <code>svn://gcc.gnu.org/svn/gcc/branches/gccgo</code>. +This branch is periodically updated with stable Go compiler sources. </p> <p> Note that although <code>gcc.gnu.org</code> is the most convenient way -to get the source code for the compiler, that is not where the master -sources live. If you want to contribute changes to the gccgo -compiler, see <a href="gccgo_contribute.html">Contributing to +to get the source code for the Go frontend, it is not where the master +sources live. If you want to contribute changes to the Go frontend +compiler, see <a href="/doc/gccgo_contribute.html">Contributing to gccgo</a>. </p> @@ -39,29 +65,37 @@ gccgo</a>. <h2 id="Building">Building</h2> <p> -Building <code>gccgo</code> is just like building <code>gcc</code> +Building gccgo is just like building GCC with one or two additional options. See the <a href="http://gcc.gnu.org/install/">instructions on the gcc web site</a>. When you run <code>configure</code>, add the option <code>--enable-languages=c,c++,go</code> (along with other languages you may want to build). If you are targeting a 32-bit x86, -then you will want to build <code>gccgo</code> to default to +then you will want to build gccgo to default to supporting locked compare and exchange instructions; do this by also using the <code>configure</code> option <code>--with-arch=i586</code> (or a newer architecture, depending on where you need your programs to -run). +run). If you are targeting a 64-bit x86, but sometimes want to use +the <code>-m32</code> option, then use the <code>configure</code> +option <code>--with-arch-32=i586</code>. </p> +<h3 id="Gold">Gold</h3> + <p> -On x86 GNU/Linux systems the <code>gccgo</code> compiler is able to +On x86 GNU/Linux systems the gccgo compiler is able to use a small discontiguous stack for goroutines. This permits programs to run many more goroutines, since each goroutine can use a relatively -small stack. Doing this requires using a development version of -the <code>gold</code> linker. The easiest way to do this is to build -the GNU binutils, using <code>--enable-gold</code> when you run -the <code>configure</code> script, and to -use <code>--with-ld=GOLD_BINARY</code> when you -configure <code>gccgo</code>. A typical sequence would look like +small stack. Doing this requires using the gold linker version 2.22 +or later. You can either install GNU binutils 2.22 or later, or you +can build gold yourself. +</p> + +<p> +To build gold yourself, build the GNU binutils, +using <code>--enable-gold=default</code> when you run +the <code>configure</code> script. Before building, you must install +the flex and bison packages. A typical sequence would look like this (you can replace <code>/opt/gold</code> with any directory to which you have write access): </p> @@ -69,38 +103,79 @@ which you have write access): <pre> cvs -z 9 -d :pserver:anoncvs@sourceware.org:/cvs/src login [password is "anoncvs"] +[The next command will create a directory named src, not binutils] cvs -z 9 -d :pserver:anoncvs@sourceware.org:/cvs/src co binutils mkdir binutils-objdir cd binutils-objdir -../src/configure --enable-gold --prefix=/opt/gold +../src/configure --enable-gold=default --prefix=/opt/gold make make install </pre> <p> -A number of prerequisites are required to build <code>gcc</code>, as -described on the <a href="http://gcc.gnu.org/">gcc web site</a>. If -those are all available, then a typical build and install sequence -would look like this (only use the <code>--with-ld</code> option if -you built and installed the gold linker as described above): +However you install gold, when you configure gccgo, use the +option <code>--with-ld=<var>GOLD_BINARY</var></code>. +</p> + +<h3 id="Prerequisites">Prerequisites</h3> + +<p> +A number of prerequisites are required to build GCC, as +described on +the <a href="http://gcc.gnu.org/install/prerequisites.html">gcc web +site</a>. It is important to install all the prerequisites before +running the gcc <code>configure</code> script. + +<h3 id="Build_commands">Build commands</h3> + +<p> +Once all the prerequisites are installed, then a typical build and +install sequence would look like this (only use +the <code>--with-ld</code> option if you are using the gold linker as +described above): </p> <pre> svn checkout svn://gcc.gnu.org/svn/gcc/branches/gccgo gccgo mkdir objdir cd objdir -../gccgo/configure --enable-languages=c,c++,go --with-ld=/opt/gold/bin/ld +../gccgo/configure --prefix=/opt/gccgo --enable-languages=c,c++,go --with-ld=/opt/gold/bin/ld make make install </pre> +<h3 id="Ubuntu">A note on Ubuntu</h3> + +<p> +Current versions of Ubuntu and current versions of gcc disagree on +where system libraries and header files are found. This is not a +gccgo issue, and we hope this will be resolved soon. Until it is, +setting these environment variables while configuring and building +gccgo may fix the problem. +</p> + +<pre> +LIBRARY_PATH=/usr/lib/x86_64-linux-gnu +C_INCLUDE_PATH=/usr/include/x86_64-linux-gnu +CPLUS_INCLUDE_PATH=/usr/include/x86_64-linux-gnu +export LIBRARY_PATH C_INCLUDE_PATH CPLUS_INCLUDE_PATH +</pre> + <h2 id="Using_gccgo">Using gccgo</h2> <p> -The <code>gccgo</code> compiler works like other gcc frontends. +The gccgo compiler works like other gcc frontends. The gccgo +installation does not currently include a version of +the <code>go</code> command. However if you have the <code>go</code> +command from an installation of the <code>gc</code> compiler, you can +use it with gccgo by passing the option <code>-compiler gccgo</code> +to <code>go build</code> or <code>go install</code> or <code>go +test</code>. +</p> <p> -To compile a file: +To compile a file without using the <code>go</code> command: +</p> <pre> gccgo -c file.go @@ -109,6 +184,7 @@ gccgo -c file.go <p> That produces <code>file.o</code>. To link files together to form an executable: +</p> <pre> gccgo -o file file.o @@ -116,44 +192,68 @@ gccgo -o file file.o <p> To run the resulting file, you will need to tell the program where to -find the compiled Go packages. This can be done either by setting -<code>LD_LIBRARY_PATH</code> in your environment: +find the compiled Go packages. There are a few ways to do this: +</p> + +<ul> +<li> +<p> +Set the <code>LD_LIBRARY_PATH</code> environment variable: +</p> <pre> -LD_LIBRARY_PATH=/usr/lib/gcc/MACHINE/VERSION +LD_LIBRARY_PATH=${prefix}/lib/gcc/MACHINE/VERSION +[or] +LD_LIBRARY_PATH=${prefix}/lib64/gcc/MACHINE/VERSION +export LD_LIBRARY_PATH </pre> <p> -or by passing a <code>-Wl,-R</code> option when you link: +Here <code>${prefix}</code> is the <code>--prefix</code> option used +when building gccgo. For a binary install this is +normally <code>/usr</code>. Whether to use <code>lib</code> +or <code>lib64</code> depends on the target. +Typically <code>lib64</code> is correct for x86_64 systems, +and <code>lib</code> is correct for other systems. The idea is to +name the directory where <code>libgo.so</code> is found. +</p> -<pre> -gccgo -o file file.o -Wl,-R,/usr/lib/gcc/MACHINE/VERSION -</pre> +</li> +<li> <p> -or you can use the <code>-static-libgo</code> link-time option to link -statically against libgo, or you can do a fully static link (static -linking is the default for the <code>6l</code> Go linker). On most -systems, a static link will look something like: +Passing a <code>-Wl,-R</code> option when you link: +</p> <pre> -gccgo -o file file.o -static -L /usr/lib/nptl -lgobegin -lgo -lpthread +gccgo -o file file.o -Wl,-R,${prefix}/lib/gcc/MACHINE/VERSION +[or] +gccgo -o file file.o -Wl,-R,${prefix}/lib64/gcc/MACHINE/VERSION </pre> +</li> +<li> <p> -You may get a warning about not creating an <code>.eh_frame_hdr</code> -section; this has nothing to do with Go, and may be ignored. In the -future the requirement of explicitly specifying -<code>-L /usr/lib/nptl -lgobegin -lgo -lpthread</code> -may be removed. +Use the <code>-static-libgo</code> option to link statically against +the compiled packages. +</p> +</li> +<li> +<p> +Use the <code>-static</code> option to do a fully static link (the +default for the <code>gc</code> compiler). +</p> +</li> +</ul> <h2 id="Options">Options</h2> <p> -The <code>gccgo</code> compiler supports all <code>gcc</code> options +The gccgo compiler supports all GCC options that are language independent, notably the <code>-O</code> and <code>-g</code> options. +</p> <p> The <code>-fgo-prefix=PREFIX</code> option may be used to set a unique @@ -162,28 +262,24 @@ use with large programs that contain many packages, in order to allow multiple packages to use the same identifier as the package name. The <code>PREFIX</code> may be any string; a good choice for the string is the directory where the package will be installed. - -<p> -The <code>-fno-require-return-statement</code> option may be used to -disable the compiler error about functions missing return statements. -Note that there is no way to disable this error in <code>6g</code>. +</p> <p> The <code>-I</code> and <code>-L</code> options, which are synonyms for the compiler, may be used to set the search path for finding imports. - +</p> <h2 id="Imports">Imports</h2> <p> -When you compile a file which exports something, the export -information will be stored directly in the object file. When -you import a package, you must tell <code>gccgo</code> how to +When you compile a file that exports something, the export +information will be stored directly in the object file. When +you import a package, you must tell gccgo how to find the file. <p> -When you import the package <var>FILE</var> with <code>gccgo</code>, +When you import the package <var>FILE</var> with gccgo, it will look for the import data in the following files, and use the first one that it finds. @@ -198,21 +294,25 @@ first one that it finds. <code><var>FILE</var>.gox</code>, when used, will typically contain nothing but export data. This can be generated from <code><var>FILE</var>.o</code> via +</p> <pre> objcopy -j .go_export FILE.o FILE.gox </pre> <p> -The <code>gccgo</code> compiler will look in the current -directory for import files. In more complex scenarios you +The gccgo compiler will look in the current +directory for import files. In more complex scenarios you may pass the <code>-I</code> or <code>-L</code> option to -<code>gccgo</code>. Both options take directories to search. The +gccgo. Both options take directories to search. The <code>-L</code> option is also passed to the linker. +</p> -The <code>gccgo</code> compiler does not currently (2009-11-06) record +<p> +The gccgo compiler does not currently (2012-03-20) record the file name of imported packages in the object file. You must arrange for the imported data to be linked into the program. +</p> <pre> gccgo -c mypackage.go # Exports mypackage @@ -220,48 +320,41 @@ gccgo -c main.go # Imports mypackage gccgo -o main main.o mypackage.o # Explicitly links with mypackage.o </pre> -<h2 id="Unimplemented">Unimplemented</h2> - -<p> -Some Go features are not yet implemented in <code>gccgo</code>. As of -2010-08-23, the following are not implemented: - -<ul> -<li>goroutines are implemented as NPTL threads. If you can not use - the gold linker as described above, they are created with a fixed - stack size, and the number of goroutines that may be created at - one time is limited. -</ul> - <h2 id="Debugging">Debugging</h2> <p> If you use the <code>-g</code> option when you compile, you can run -<code>gdb</code> on your executable. The debugger doesn't (yet) -know anything about Go. However, you can set breakpoints, single-step, +<code>gdb</code> on your executable. The debugger has only limited +knowledge about Go. You can set breakpoints, single-step, etc. You can print variables, but they will be printed as though they -had C/C++ types. For numeric types this doesn't matter. Go strings -will show up as pointers to structures; to see the value -<code>print *stringvar</code>. In general Go strings, maps, channels -and interfaces are always represented as C pointers. +had C/C++ types. For numeric types this doesn't matter. Go strings +and interfaces will show up as two-element structures. Go +maps and channels are always represented as C pointers to run-time +structures. +</p> <h2 id="C_Interoperability">C Interoperability</h2> <p> -When using <code>gccgo</code> there is limited interoperability with C, +When using gccgo there is limited interoperability with C, or with C++ code compiled using <code>extern "C"</code>. +</p> <h3 id="Types">Types</h3> <p> Basic types map directly: an <code>int</code> in Go is an <code>int</code> -in C, etc. Go <code>byte</code> is equivalent to C <code>unsigned char</code>. +in C, an <code>int32</code> is an <code>int32_t</code>, +etc. Go <code>byte</code> is equivalent to C <code>unsigned +char</code>. Pointers in Go are pointers in C. A Go <code>struct</code> is the same as C <code>struct</code> with the same fields and types. +</p> <p> The Go <code>string</code> type is currently defined as a two-element structure (this is <b style="color: red;">subject to change</b>): +</p> <pre> struct __go_string { @@ -276,10 +369,12 @@ array in Go is equivalent to a C pointer to the equivalent of the element type. For example, Go <code>*[10]int</code> is equivalent to C <code>int*</code>, assuming that the C pointer does point to 10 elements. +</p> <p> A slice in Go is a structure. The current definition is (this is <b style="color: red;">subject to change</b>): +</p> <pre> struct __go_slice { @@ -291,9 +386,10 @@ struct __go_slice { <p> The type of a Go function with no receiver is equivalent to a C function -whose parameter types are equivalent. When a Go function returns more -than one value, the C function returns a struct. For example, these +whose parameter types are equivalent. When a Go function returns more +than one value, the C function returns a struct. For example, these functions have equivalent types: +</p> <pre> func GoFunction(int) (int, float64) @@ -302,7 +398,9 @@ struct { int i; float64 f; } CFunction(int) <p> A pointer to a Go function is equivalent to a pointer to a C function -when the functions have equivalent types. +when the functions have equivalent types (this is +<b style="color: red;">subject to change</b>). +</p> <p> Go <code>interface</code>, <code>channel</code>, and <code>map</code> @@ -314,6 +412,7 @@ which one is difficult to predict in general; use a cast. C <code>union</code> types have no corresponding Go type. C <code>struct</code> types containing bitfields have no corresponding Go type. C++ <code>class</code> types have no corresponding Go type. +</p> <p> Memory allocation is completely different between C and Go, as Go uses @@ -325,43 +424,48 @@ while the Go side still has a copy the program will fail. When passing a pointer from Go to C, the Go function must retain a visible copy of it in some Go variable. Otherwise the Go garbage collector may delete the pointer while the C function is still using it. +</p> <h3 id="Function_names">Function names</h3> <p> Go code can call C functions directly using a Go extension implemented -in <code>gccgo</code>: a function declaration may be followed by -<code>__asm__("NAME")</code>. For example, here is how the C function +in gccgo: a function declaration may be preceded by +<code>//extern NAME</code>. For example, here is how the C function <code>open</code> can be declared in Go: +</p> <pre> -func c_open(name *byte, mode int, perm int) int __asm__ ("open"); +//extern open +func c_open(name *byte, mode int, perm int) int </pre> <p> -The C function naturally expects a nul terminated string, which in +The C function naturally expects a NUL-terminated string, which in Go is equivalent to a pointer to an array (not a slice!) of <code>byte</code> with a terminating zero byte. So a sample call -from Go would look like (after importing the <code>os</code> package): +from Go would look like (after importing the <code>syscall</code> package): +</p> <pre> var name = [4]byte{'f', 'o', 'o', 0}; -i := c_open(&name[0], os.O_RDONLY, 0); +i := c_open(&name[0], syscall.O_RDONLY, 0); </pre> <p> (this serves as an example only, to open a file in Go please use Go's <code>os.Open</code> function instead). +</p> <p> The name of Go functions accessed from C is subject to change. At present the name of a Go function that does not have a receiver is <code>prefix.package.Functionname</code>. The prefix is set by the <code>-fgo-prefix</code> option used when the package is compiled; -if the option is not used, the default is simply <code>go</code>. +if the option is not used, the default is <code>go</code>. To call the function from C you must set the name using -a <code>gcc</code> extension similar to the <code>gccgo</code> -extension. +a GCC extension. +</p> <pre> extern int go_function(int) __asm__ ("myprefix.mypackage.Function"); @@ -371,37 +475,35 @@ extern int go_function(int) __asm__ ("myprefix.mypackage.Function"); Automatic generation of Go declarations from C source code</h3> <p> -The Go version of <code>gcc</code> supports automatically generating -Go declarations from C code. The facility is rather awkward at present, -and a better mechanism is under development. +The Go version of GCC supports automatically generating +Go declarations from C code. The facility is rather awkward, and most +users should use the <a href="/cmd/cgo">cgo</a> program with +the <code>-gccgo</code> option instead. +</p> <p> -Compile your C code as usual, but replace <code>-c</code> with -<code>-S -ggo</code>. The result will be an assembler file -with a <code>.s</code> extension. This assembler file will contain -comments beginning with #GO. Those comments are declarations in the Go -language for the C types, variables and functions declared in the C code. -C types which can not be represented in Go will contain the string INVALID. -Unsupported macro definitions will be recorded as <code>unknowndefine</code>, -and uses of <code>#undef</code> will be recorded as <code>undef</code>. -So it is very approximately possible to get Go code by running - -<pre> -gcc -S -ggo foo.c -grep '#GO' foo.s | grep -v INVALID | grep -v unknowndefine | grep -v undef > foo.go -</pre> +Compile your C code as usual, and add the option +<code>-fdump-go-spec=<var>FILENAME</var></code>. This will create the +file <code><var>FILENAME</var></code> as a side effect of the +compilation. This file will contain Go declarations for the types, +variables and functions declared in the C code. C types that can not +be represented in Go will be recorded as comments in the Go code. The +generated file will not have a <code>package</code> declaration, but +can otherwise be compiled directly by gccgo. +</p> <p> This procedure is full of unstated caveats and restrictions and we make no guarantee that it will not change in the future. It is more useful as a starting point for real Go code than as a regular procedure. +</p> <h2 id="RTEMS_Port">RTEMS Port</h2> <p> -The <code>gccgo</code> compiler has been ported to <a href="http://www.rtems.com/"> +The gccgo compiler has been ported to <a href="http://www.rtems.com/"> <code>RTEMS</code></a>. <code>RTEMS</code> is a real-time executive that provides a high performance environment for embedded applications -on a range of processors and embedded hardware. The current <code>gccgo</code> +on a range of processors and embedded hardware. The current gccgo port is for x86. The goal is to extend the port to most of the <a href="http://www.rtems.org/wiki/index.php/SupportedCPUs"> architectures supported by <code>RTEMS</code></a>. For more information on the port, diff --git a/doc/go-logo-black.png b/doc/go-logo-black.png Binary files differindex 29be31943..3077ebdad 100644 --- a/doc/go-logo-black.png +++ b/doc/go-logo-black.png diff --git a/doc/go-logo-blue.png b/doc/go-logo-blue.png Binary files differindex b9eac2727..8d43a5677 100644 --- a/doc/go-logo-blue.png +++ b/doc/go-logo-blue.png diff --git a/doc/go-logo-white.png b/doc/go-logo-white.png Binary files differindex 4011069eb..fa29169fa 100644 --- a/doc/go-logo-white.png +++ b/doc/go-logo-white.png diff --git a/doc/go1.html b/doc/go1.html new file mode 100644 index 000000000..73d562acd --- /dev/null +++ b/doc/go1.html @@ -0,0 +1,2038 @@ +<!--{ + "Title": "Go 1 Release Notes", + "Template": true +}--> + +<h2 id="introduction">Introduction to Go 1</h2> + +<p> +Go version 1, Go 1 for short, defines a language and a set of core libraries +that provide a stable foundation for creating reliable products, projects, and +publications. +</p> + +<p> +The driving motivation for Go 1 is stability for its users. People should be able to +write Go programs and expect that they will continue to compile and run without +change, on a time scale of years, including in production environments such as +Google App Engine. Similarly, people should be able to write books about Go, be +able to say which version of Go the book is describing, and have that version +number still be meaningful much later. +</p> + +<p> +Code that compiles in Go 1 should, with few exceptions, continue to compile and +run throughout the lifetime of that version, even as we issue updates and bug +fixes such as Go version 1.1, 1.2, and so on. Other than critical fixes, changes +made to the language and library for subsequent releases of Go 1 may +add functionality but will not break existing Go 1 programs. +<a href="go1compat.html">The Go 1 compatibility document</a> +explains the compatibility guidelines in more detail. +</p> + +<p> +Go 1 is a representation of Go as it used today, not a wholesale rethinking of +the language. We avoided designing new features and instead focused on cleaning +up problems and inconsistencies and improving portability. There are a number +changes to the Go language and packages that we had considered for some time and +prototyped but not released primarily because they are significant and +backwards-incompatible. Go 1 was an opportunity to get them out, which is +helpful for the long term, but also means that Go 1 introduces incompatibilities +for old programs. Fortunately, the <code>go</code> <code>fix</code> tool can +automate much of the work needed to bring programs up to the Go 1 standard. +</p> + +<p> +This document outlines the major changes in Go 1 that will affect programmers +updating existing code; its reference point is the prior release, r60 (tagged as +r60.3). It also explains how to update code from r60 to run under Go 1. +</p> + +<h2 id="language">Changes to the language</h2> + +<h3 id="append">Append</h3> + +<p> +The <code>append</code> predeclared variadic function makes it easy to grow a slice +by adding elements to the end. +A common use is to add bytes to the end of a byte slice when generating output. +However, <code>append</code> did not provide a way to append a string to a <code>[]byte</code>, +which is another common case. +</p> + +{{code "/doc/progs/go1.go" `/greeting := ..byte/` `/append.*hello/`}} + +<p> +By analogy with the similar property of <code>copy</code>, Go 1 +permits a string to be appended (byte-wise) directly to a byte +slice, reducing the friction between strings and byte slices. +The conversion is no longer necessary: +</p> + +{{code "/doc/progs/go1.go" `/append.*world/`}} + +<p> +<em>Updating</em>: +This is a new feature, so existing code needs no changes. +</p> + +<h3 id="close">Close</h3> + +<p> +The <code>close</code> predeclared function provides a mechanism +for a sender to signal that no more values will be sent. +It is important to the implementation of <code>for</code> <code>range</code> +loops over channels and is helpful in other situations. +Partly by design and partly because of race conditions that can occur otherwise, +it is intended for use only by the goroutine sending on the channel, +not by the goroutine receiving data. +However, before Go 1 there was no compile-time checking that <code>close</code> +was being used correctly. +</p> + +<p> +To close this gap, at least in part, Go 1 disallows <code>close</code> on receive-only channels. +Attempting to close such a channel is a compile-time error. +</p> + +<pre> + var c chan int + var csend chan<- int = c + var crecv <-chan int = c + close(c) // legal + close(csend) // legal + close(crecv) // illegal +</pre> + +<p> +<em>Updating</em>: +Existing code that attempts to close a receive-only channel was +erroneous even before Go 1 and should be fixed. The compiler will +now reject such code. +</p> + +<h3 id="literals">Composite literals</h3> + +<p> +In Go 1, a composite literal of array, slice, or map type can elide the +type specification for the elements' initializers if they are of pointer type. +All four of the initializations in this example are legal; the last one was illegal before Go 1. +</p> + +{{code "/doc/progs/go1.go" `/type Date struct/` `/STOP/`}} + +<p> +<em>Updating</em>: +This change has no effect on existing code, but the command +<code>gofmt</code> <code>-s</code> applied to existing source +will, among other things, elide explicit element types wherever permitted. +</p> + + +<h3 id="init">Goroutines during init</h3> + +<p> +The old language defined that <code>go</code> statements executed during initialization created goroutines but that they did not begin to run until initialization of the entire program was complete. +This introduced clumsiness in many places and, in effect, limited the utility +of the <code>init</code> construct: +if it was possible for another package to use the library during initialization, the library +was forced to avoid goroutines. +This design was done for reasons of simplicity and safety but, +as our confidence in the language grew, it seemed unnecessary. +Running goroutines during initialization is no more complex or unsafe than running them during normal execution. +</p> + +<p> +In Go 1, code that uses goroutines can be called from +<code>init</code> routines and global initialization expressions +without introducing a deadlock. +</p> + +{{code "/doc/progs/go1.go" `/PackageGlobal/` `/^}/`}} + +<p> +<em>Updating</em>: +This is a new feature, so existing code needs no changes, +although it's possible that code that depends on goroutines not starting before <code>main</code> will break. +There was no such code in the standard repository. +</p> + +<h3 id="rune">The rune type</h3> + +<p> +The language spec allows the <code>int</code> type to be 32 or 64 bits wide, but current implementations set <code>int</code> to 32 bits even on 64-bit platforms. +It would be preferable to have <code>int</code> be 64 bits on 64-bit platforms. +(There are important consequences for indexing large slices.) +However, this change would waste space when processing Unicode characters with +the old language because the <code>int</code> type was also used to hold Unicode code points: each code point would waste an extra 32 bits of storage if <code>int</code> grew from 32 bits to 64. +</p> + +<p> +To make changing to 64-bit <code>int</code> feasible, +Go 1 introduces a new basic type, <code>rune</code>, to represent +individual Unicode code points. +It is an alias for <code>int32</code>, analogous to <code>byte</code> +as an alias for <code>uint8</code>. +</p> + +<p> +Character literals such as <code>'a'</code>, <code>'語'</code>, and <code>'\u0345'</code> +now have default type <code>rune</code>, +analogous to <code>1.0</code> having default type <code>float64</code>. +A variable initialized to a character constant will therefore +have type <code>rune</code> unless otherwise specified. +</p> + +<p> +Libraries have been updated to use <code>rune</code> rather than <code>int</code> +when appropriate. For instance, the functions <code>unicode.ToLower</code> and +relatives now take and return a <code>rune</code>. +</p> + +{{code "/doc/progs/go1.go" `/STARTRUNE/` `/ENDRUNE/`}} + +<p> +<em>Updating</em>: +Most source code will be unaffected by this because the type inference from +<code>:=</code> initializers introduces the new type silently, and it propagates +from there. +Some code may get type errors that a trivial conversion will resolve. +</p> + +<h3 id="error">The error type</h3> + +<p> +Go 1 introduces a new built-in type, <code>error</code>, which has the following definition: +</p> + +<pre> + type error interface { + Error() string + } +</pre> + +<p> +Since the consequences of this type are all in the package library, +it is discussed <a href="#errors">below</a>. +</p> + +<h3 id="delete">Deleting from maps</h3> + +<p> +In the old language, to delete the entry with key <code>k</code> from map <code>m</code>, one wrote the statement, +</p> + +<pre> + m[k] = value, false +</pre> + +<p> +This syntax was a peculiar special case, the only two-to-one assignment. +It required passing a value (usually ignored) that is evaluated but discarded, +plus a boolean that was nearly always the constant <code>false</code>. +It did the job but was odd and a point of contention. +</p> + +<p> +In Go 1, that syntax has gone; instead there is a new built-in +function, <code>delete</code>. The call +</p> + +{{code "/doc/progs/go1.go" `/delete\(m, k\)/`}} + +<p> +will delete the map entry retrieved by the expression <code>m[k]</code>. +There is no return value. Deleting a non-existent entry is a no-op. +</p> + +<p> +<em>Updating</em>: +Running <code>go</code> <code>fix</code> will convert expressions of the form <code>m[k] = value, +false</code> into <code>delete(m, k)</code> when it is clear that +the ignored value can be safely discarded from the program and +<code>false</code> refers to the predefined boolean constant. +The fix tool +will flag other uses of the syntax for inspection by the programmer. +</p> + +<h3 id="iteration">Iterating in maps</h3> + +<p> +The old language specification did not define the order of iteration for maps, +and in practice it differed across hardware platforms. +This caused tests that iterated over maps to be fragile and non-portable, with the +unpleasant property that a test might always pass on one machine but break on another. +</p> + +<p> +In Go 1, the order in which elements are visited when iterating +over a map using a <code>for</code> <code>range</code> statement +is defined to be unpredictable, even if the same loop is run multiple +times with the same map. +Code should not assume that the elements are visited in any particular order. +</p> + +<p> +This change means that code that depends on iteration order is very likely to break early and be fixed long before it becomes a problem. +Just as important, it allows the map implementation to ensure better map balancing even when programs are using range loops to select an element from a map. +</p> + +{{code "/doc/progs/go1.go" `/Sunday/` `/^ }/`}} + +<p> +<em>Updating</em>: +This is one change where tools cannot help. Most existing code +will be unaffected, but some programs may break or misbehave; we +recommend manual checking of all range statements over maps to +verify they do not depend on iteration order. There were a few such +examples in the standard repository; they have been fixed. +Note that it was already incorrect to depend on the iteration order, which +was unspecified. This change codifies the unpredictability. +</p> + +<h3 id="multiple_assignment">Multiple assignment</h3> + +<p> +The language specification has long guaranteed that in assignments +the right-hand-side expressions are all evaluated before any left-hand-side expressions are assigned. +To guarantee predictable behavior, +Go 1 refines the specification further. +</p> + +<p> +If the left-hand side of the assignment +statement contains expressions that require evaluation, such as +function calls or array indexing operations, these will all be done +using the usual left-to-right rule before any variables are assigned +their value. Once everything is evaluated, the actual assignments +proceed in left-to-right order. +</p> + +<p> +These examples illustrate the behavior. +</p> + +{{code "/doc/progs/go1.go" `/sa :=/` `/then sc.0. = 2/`}} + +<p> +<em>Updating</em>: +This is one change where tools cannot help, but breakage is unlikely. +No code in the standard repository was broken by this change, and code +that depended on the previous unspecified behavior was already incorrect. +</p> + +<h3 id="shadowing">Returns and shadowed variables</h3> + +<p> +A common mistake is to use <code>return</code> (without arguments) after an assignment to a variable that has the same name as a result variable but is not the same variable. +This situation is called <em>shadowing</em>: the result variable has been shadowed by another variable with the same name declared in an inner scope. +</p> + +<p> +In functions with named return values, +the Go 1 compilers disallow return statements without arguments if any of the named return values is shadowed at the point of the return statement. +(It isn't part of the specification, because this is one area we are still exploring; +the situation is analogous to the compilers rejecting functions that do not end with an explicit return statement.) +</p> + +<p> +This function implicitly returns a shadowed return value and will be rejected by the compiler: +</p> + +<pre> + func Bug() (i, j, k int) { + for i = 0; i < 5; i++ { + for j := 0; j < 5; j++ { // Redeclares j. + k += i*j + if k > 100 { + return // Rejected: j is shadowed here. + } + } + } + return // OK: j is not shadowed here. + } +</pre> + +<p> +<em>Updating</em>: +Code that shadows return values in this way will be rejected by the compiler and will need to be fixed by hand. +The few cases that arose in the standard repository were mostly bugs. +</p> + +<h3 id="unexported">Copying structs with unexported fields</h3> + +<p> +The old language did not allow a package to make a copy of a struct value containing unexported fields belonging to a different package. +There was, however, a required exception for a method receiver; +also, the implementations of <code>copy</code> and <code>append</code> have never honored the restriction. +</p> + +<p> +Go 1 will allow packages to copy struct values containing unexported fields from other packages. +Besides resolving the inconsistency, +this change admits a new kind of API: a package can return an opaque value without resorting to a pointer or interface. +The new implementations of <code>time.Time</code> and +<code>reflect.Value</code> are examples of types taking advantage of this new property. +</p> + +<p> +As an example, if package <code>p</code> includes the definitions, +</p> + +<pre> + type Struct struct { + Public int + secret int + } + func NewStruct(a int) Struct { // Note: not a pointer. + return Struct{a, f(a)} + } + func (s Struct) String() string { + return fmt.Sprintf("{%d (secret %d)}", s.Public, s.secret) + } +</pre> + +<p> +a package that imports <code>p</code> can assign and copy values of type +<code>p.Struct</code> at will. +Behind the scenes the unexported fields will be assigned and copied just +as if they were exported, +but the client code will never be aware of them. The code +</p> + +<pre> + import "p" + + myStruct := p.NewStruct(23) + copyOfMyStruct := myStruct + fmt.Println(myStruct, copyOfMyStruct) +</pre> + +<p> +will show that the secret field of the struct has been copied to the new value. +</p> + +<p> +<em>Updating</em>: +This is a new feature, so existing code needs no changes. +</p> + +<h3 id="equality">Equality</h3> + +<p> +Before Go 1, the language did not define equality on struct and array values. +This meant, +among other things, that structs and arrays could not be used as map keys. +On the other hand, Go did define equality on function and map values. +Function equality was problematic in the presence of closures +(when are two closures equal?) +while map equality compared pointers, not the maps' content, which was usually +not what the user would want. +</p> + +<p> +Go 1 addressed these issues. +First, structs and arrays can be compared for equality and inequality +(<code>==</code> and <code>!=</code>), +and therefore be used as map keys, +provided they are composed from elements for which equality is also defined, +using element-wise comparison. +</p> + +{{code "/doc/progs/go1.go" `/type Day struct/` `/Printf/`}} + +<p> +Second, Go 1 removes the definition of equality for function values, +except for comparison with <code>nil</code>. +Finally, map equality is gone too, also except for comparison with <code>nil</code>. +</p> + +<p> +Note that equality is still undefined for slices, for which the +calculation is in general infeasible. Also note that the ordered +comparison operators (<code><</code> <code><=</code> +<code>></code> <code>>=</code>) are still undefined for +structs and arrays. + +<p> +<em>Updating</em>: +Struct and array equality is a new feature, so existing code needs no changes. +Existing code that depends on function or map equality will be +rejected by the compiler and will need to be fixed by hand. +Few programs will be affected, but the fix may require some +redesign. +</p> + +<h2 id="packages">The package hierarchy</h2> + +<p> +Go 1 addresses many deficiencies in the old standard library and +cleans up a number of packages, making them more internally consistent +and portable. +</p> + +<p> +This section describes how the packages have been rearranged in Go 1. +Some have moved, some have been renamed, some have been deleted. +New packages are described in later sections. +</p> + +<h3 id="hierarchy">The package hierarchy</h3> + +<p> +Go 1 has a rearranged package hierarchy that groups related items +into subdirectories. For instance, <code>utf8</code> and +<code>utf16</code> now occupy subdirectories of <code>unicode</code>. +Also, <a href="#subrepo">some packages</a> have moved into +subrepositories of +<a href="http://code.google.com/p/go"><code>code.google.com/p/go</code></a> +while <a href="#deleted">others</a> have been deleted outright. +</p> + +<table class="codetable" frame="border" summary="Moved packages"> +<colgroup align="left" width="60%"></colgroup> +<colgroup align="left" width="40%"></colgroup> +<tr> +<th align="left">Old path</th> +<th align="left">New path</th> +</tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>asn1</td> <td>encoding/asn1</td></tr> +<tr><td>csv</td> <td>encoding/csv</td></tr> +<tr><td>gob</td> <td>encoding/gob</td></tr> +<tr><td>json</td> <td>encoding/json</td></tr> +<tr><td>xml</td> <td>encoding/xml</td></tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>exp/template/html</td> <td>html/template</td></tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>big</td> <td>math/big</td></tr> +<tr><td>cmath</td> <td>math/cmplx</td></tr> +<tr><td>rand</td> <td>math/rand</td></tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>http</td> <td>net/http</td></tr> +<tr><td>http/cgi</td> <td>net/http/cgi</td></tr> +<tr><td>http/fcgi</td> <td>net/http/fcgi</td></tr> +<tr><td>http/httptest</td> <td>net/http/httptest</td></tr> +<tr><td>http/pprof</td> <td>net/http/pprof</td></tr> +<tr><td>mail</td> <td>net/mail</td></tr> +<tr><td>rpc</td> <td>net/rpc</td></tr> +<tr><td>rpc/jsonrpc</td> <td>net/rpc/jsonrpc</td></tr> +<tr><td>smtp</td> <td>net/smtp</td></tr> +<tr><td>url</td> <td>net/url</td></tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>exec</td> <td>os/exec</td></tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>scanner</td> <td>text/scanner</td></tr> +<tr><td>tabwriter</td> <td>text/tabwriter</td></tr> +<tr><td>template</td> <td>text/template</td></tr> +<tr><td>template/parse</td> <td>text/template/parse</td></tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>utf8</td> <td>unicode/utf8</td></tr> +<tr><td>utf16</td> <td>unicode/utf16</td></tr> +</table> + +<p> +Note that the package names for the old <code>cmath</code> and +<code>exp/template/html</code> packages have changed to <code>cmplx</code> +and <code>template</code>. +</p> + +<p> +<em>Updating</em>: +Running <code>go</code> <code>fix</code> will update all imports and package renames for packages that +remain inside the standard repository. Programs that import packages +that are no longer in the standard repository will need to be edited +by hand. +</p> + +<h3 id="exp">The package tree exp</h3> + +<p> +Because they are not standardized, the packages under the <code>exp</code> directory will not be available in the +standard Go 1 release distributions, although they will be available in source code form +in <a href="http://code.google.com/p/go/">the repository</a> for +developers who wish to use them. +</p> + +<p> +Several packages have moved under <code>exp</code> at the time of Go 1's release: +</p> + +<ul> +<li><code>ebnf</code></li> +<li><code>html</code><sup>†</sup></li> +<li><code>go/types</code></li> +</ul> + +<p> +(<sup>†</sup>The <code>EscapeString</code> and <code>UnescapeString</code> types remain +in package <code>html</code>.) +</p> + +<p> +All these packages are available under the same names, with the prefix <code>exp/</code>: <code>exp/ebnf</code> etc. +</p> + +<p> +Also, the <code>utf8.String</code> type has been moved to its own package, <code>exp/utf8string</code>. +</p> + +<p> +Finally, the <code>gotype</code> command now resides in <code>exp/gotype</code>, while +<code>ebnflint</code> is now in <code>exp/ebnflint</code>. +If they are installed, they now reside in <code>$GOROOT/bin/tool</code>. +</p> + +<p> +<em>Updating</em>: +Code that uses packages in <code>exp</code> will need to be updated by hand, +or else compiled from an installation that has <code>exp</code> available. +The <code>go</code> <code>fix</code> tool or the compiler will complain about such uses. +</p> + +<h3 id="old">The package tree old</h3> + +<p> +Because they are deprecated, the packages under the <code>old</code> directory will not be available in the +standard Go 1 release distributions, although they will be available in source code form for +developers who wish to use them. +</p> + +<p> +The packages in their new locations are: +</p> + +<ul> +<li><code>old/netchan</code></li> +<li><code>old/regexp</code></li> +<li><code>old/template</code></li> +</ul> + +<p> +<em>Updating</em>: +Code that uses packages now in <code>old</code> will need to be updated by hand, +or else compiled from an installation that has <code>old</code> available. +The <code>go</code> <code>fix</code> tool will warn about such uses. +</p> + +<h3 id="deleted">Deleted packages</h3> + +<p> +Go 1 deletes several packages outright: +</p> + +<ul> +<li><code>container/vector</code></li> +<li><code>exp/datafmt</code></li> +<li><code>go/typechecker</code></li> +<li><code>try</code></li> +</ul> + +<p> +and also the command <code>gotry</code>. +</p> + +<p> +<em>Updating</em>: +Code that uses <code>container/vector</code> should be updated to use +slices directly. See +<a href="http://code.google.com/p/go-wiki/wiki/SliceTricks">the Go +Language Community Wiki</a> for some suggestions. +Code that uses the other packages (there should be almost zero) will need to be rethought. +</p> + +<h3 id="subrepo">Packages moving to subrepositories</h3> + +<p> +Go 1 has moved a number of packages into other repositories, usually sub-repositories of +<a href="http://code.google.com/p/go/">the main Go repository</a>. +This table lists the old and new import paths: + +<table class="codetable" frame="border" summary="Sub-repositories"> +<colgroup align="left" width="40%"></colgroup> +<colgroup align="left" width="60%"></colgroup> +<tr> +<th align="left">Old</th> +<th align="left">New</th> +</tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>crypto/bcrypt</td> <td>code.google.com/p/go.crypto/bcrypt</tr> +<tr><td>crypto/blowfish</td> <td>code.google.com/p/go.crypto/blowfish</tr> +<tr><td>crypto/cast5</td> <td>code.google.com/p/go.crypto/cast5</tr> +<tr><td>crypto/md4</td> <td>code.google.com/p/go.crypto/md4</tr> +<tr><td>crypto/ocsp</td> <td>code.google.com/p/go.crypto/ocsp</tr> +<tr><td>crypto/openpgp</td> <td>code.google.com/p/go.crypto/openpgp</tr> +<tr><td>crypto/openpgp/armor</td> <td>code.google.com/p/go.crypto/openpgp/armor</tr> +<tr><td>crypto/openpgp/elgamal</td> <td>code.google.com/p/go.crypto/openpgp/elgamal</tr> +<tr><td>crypto/openpgp/errors</td> <td>code.google.com/p/go.crypto/openpgp/errors</tr> +<tr><td>crypto/openpgp/packet</td> <td>code.google.com/p/go.crypto/openpgp/packet</tr> +<tr><td>crypto/openpgp/s2k</td> <td>code.google.com/p/go.crypto/openpgp/s2k</tr> +<tr><td>crypto/ripemd160</td> <td>code.google.com/p/go.crypto/ripemd160</tr> +<tr><td>crypto/twofish</td> <td>code.google.com/p/go.crypto/twofish</tr> +<tr><td>crypto/xtea</td> <td>code.google.com/p/go.crypto/xtea</tr> +<tr><td>exp/ssh</td> <td>code.google.com/p/go.crypto/ssh</tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>image/bmp</td> <td>code.google.com/p/go.image/bmp</tr> +<tr><td>image/tiff</td> <td>code.google.com/p/go.image/tiff</tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>net/dict</td> <td>code.google.com/p/go.net/dict</tr> +<tr><td>net/websocket</td> <td>code.google.com/p/go.net/websocket</tr> +<tr><td>exp/spdy</td> <td>code.google.com/p/go.net/spdy</tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>encoding/git85</td> <td>code.google.com/p/go.codereview/git85</tr> +<tr><td>patch</td> <td>code.google.com/p/go.codereview/patch</tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>exp/wingui</td> <td>code.google.com/p/gowingui</tr> +</table> + +<p> +<em>Updating</em>: +Running <code>go</code> <code>fix</code> will update imports of these packages to use the new import paths. +Installations that depend on these packages will need to install them using +a <code>go get</code> command. +</p> + +<h2 id="major">Major changes to the library</h2> + +<p> +This section describes significant changes to the core libraries, the ones that +affect the most programs. +</p> + +<h3 id="errors">The error type and errors package</h3> + +<p> +The placement of <code>os.Error</code> in package <code>os</code> is mostly historical: errors first came up when implementing package <code>os</code>, and they seemed system-related at the time. +Since then it has become clear that errors are more fundamental than the operating system. For example, it would be nice to use <code>Errors</code> in packages that <code>os</code> depends on, like <code>syscall</code>. +Also, having <code>Error</code> in <code>os</code> introduces many dependencies on <code>os</code> that would otherwise not exist. +</p> + +<p> +Go 1 solves these problems by introducing a built-in <code>error</code> interface type and a separate <code>errors</code> package (analogous to <code>bytes</code> and <code>strings</code>) that contains utility functions. +It replaces <code>os.NewError</code> with +<a href="/pkg/errors/#New"><code>errors.New</code></a>, +giving errors a more central place in the environment. +</p> + +<p> +So the widely-used <code>String</code> method does not cause accidental satisfaction +of the <code>error</code> interface, the <code>error</code> interface uses instead +the name <code>Error</code> for that method: +</p> + +<pre> + type error interface { + Error() string + } +</pre> + +<p> +The <code>fmt</code> library automatically invokes <code>Error</code>, as it already +does for <code>String</code>, for easy printing of error values. +</p> + +{{code "/doc/progs/go1.go" `/START ERROR EXAMPLE/` `/END ERROR EXAMPLE/`}} + +<p> +All standard packages have been updated to use the new interface; the old <code>os.Error</code> is gone. +</p> + +<p> +A new package, <a href="/pkg/errors/"><code>errors</code></a>, contains the function +</p> + +<pre> +func New(text string) error +</pre> + +<p> +to turn a string into an error. It replaces the old <code>os.NewError</code>. +</p> + +{{code "/doc/progs/go1.go" `/ErrSyntax/`}} + +<p> +<em>Updating</em>: +Running <code>go</code> <code>fix</code> will update almost all code affected by the change. +Code that defines error types with a <code>String</code> method will need to be updated +by hand to rename the methods to <code>Error</code>. +</p> + +<h3 id="errno">System call errors</h3> + +<p> +The old <code>syscall</code> package, which predated <code>os.Error</code> +(and just about everything else), +returned errors as <code>int</code> values. +In turn, the <code>os</code> package forwarded many of these errors, such +as <code>EINVAL</code>, but using a different set of errors on each platform. +This behavior was unpleasant and unportable. +</p> + +<p> +In Go 1, the +<a href="/pkg/syscall/"><code>syscall</code></a> +package instead returns an <code>error</code> for system call errors. +On Unix, the implementation is done by a +<a href="/pkg/syscall/#Errno"><code>syscall.Errno</code></a> type +that satisfies <code>error</code> and replaces the old <code>os.Errno</code>. +</p> + +<p> +The changes affecting <code>os.EINVAL</code> and relatives are +described <a href="#os">elsewhere</a>. + +<p> +<em>Updating</em>: +Running <code>go</code> <code>fix</code> will update almost all code affected by the change. +Regardless, most code should use the <code>os</code> package +rather than <code>syscall</code> and so will be unaffected. +</p> + +<h3 id="time">Time</h3> + +<p> +Time is always a challenge to support well in a programming language. +The old Go <code>time</code> package had <code>int64</code> units, no +real type safety, +and no distinction between absolute times and durations. +</p> + +<p> +One of the most sweeping changes in the Go 1 library is therefore a +complete redesign of the +<a href="/pkg/time/"><code>time</code></a> package. +Instead of an integer number of nanoseconds as an <code>int64</code>, +and a separate <code>*time.Time</code> type to deal with human +units such as hours and years, +there are now two fundamental types: +<a href="/pkg/time/#Time"><code>time.Time</code></a> +(a value, so the <code>*</code> is gone), which represents a moment in time; +and <a href="/pkg/time/#Duration"><code>time.Duration</code></a>, +which represents an interval. +Both have nanosecond resolution. +A <code>Time</code> can represent any time into the ancient +past and remote future, while a <code>Duration</code> can +span plus or minus only about 290 years. +There are methods on these types, plus a number of helpful +predefined constant durations such as <code>time.Second</code>. +</p> + +<p> +Among the new methods are things like +<a href="/pkg/time/#Time.Add"><code>Time.Add</code></a>, +which adds a <code>Duration</code> to a <code>Time</code>, and +<a href="/pkg/time/#Time.Sub"><code>Time.Sub</code></a>, +which subtracts two <code>Times</code> to yield a <code>Duration</code>. +</p> + +<p> +The most important semantic change is that the Unix epoch (Jan 1, 1970) is now +relevant only for those functions and methods that mention Unix: +<a href="/pkg/time/#Unix"><code>time.Unix</code></a> +and the <a href="/pkg/time/#Time.Unix"><code>Unix</code></a> +and <a href="/pkg/time/#Time.UnixNano"><code>UnixNano</code></a> methods +of the <code>Time</code> type. +In particular, +<a href="/pkg/time/#Now"><code>time.Now</code></a> +returns a <code>time.Time</code> value rather than, in the old +API, an integer nanosecond count since the Unix epoch. +</p> + +{{code "/doc/progs/go1.go" `/sleepUntil/` `/^}/`}} + +<p> +The new types, methods, and constants have been propagated through +all the standard packages that use time, such as <code>os</code> and +its representation of file time stamps. +</p> + +<p> +<em>Updating</em>: +The <code>go</code> <code>fix</code> tool will update many uses of the old <code>time</code> package to use the new +types and methods, although it does not replace values such as <code>1e9</code> +representing nanoseconds per second. +Also, because of type changes in some of the values that arise, +some of the expressions rewritten by the fix tool may require +further hand editing; in such cases the rewrite will include +the correct function or method for the old functionality, but +may have the wrong type or require further analysis. +</p> + +<h2 id="minor">Minor changes to the library</h2> + +<p> +This section describes smaller changes, such as those to less commonly +used packages or that affect +few programs beyond the need to run <code>go</code> <code>fix</code>. +This category includes packages that are new in Go 1. +Collectively they improve portability, regularize behavior, and +make the interfaces more modern and Go-like. +</p> + +<h3 id="archive_zip">The archive/zip package</h3> + +<p> +In Go 1, <a href="/pkg/archive/zip/#Writer"><code>*zip.Writer</code></a> no +longer has a <code>Write</code> method. Its presence was a mistake. +</p> + +<p> +<em>Updating</em>: +What little code is affected will be caught by the compiler and must be updated by hand. +</p> + +<h3 id="bufio">The bufio package</h3> + +<p> +In Go 1, <a href="/pkg/bufio/#NewReaderSize"><code>bufio.NewReaderSize</code></a> +and +<a href="/pkg/bufio/#NewWriterSize"><code>bufio.NewWriterSize</code></a> +functions no longer return an error for invalid sizes. +If the argument size is too small or invalid, it is adjusted. +</p> + +<p> +<em>Updating</em>: +Running <code>go</code> <code>fix</code> will update calls that assign the error to _. +Calls that aren't fixed will be caught by the compiler and must be updated by hand. +</p> + +<h3 id="compress">The compress/flate, compress/gzip and compress/zlib packages</h3> + +<p> +In Go 1, the <code>NewWriterXxx</code> functions in +<a href="/pkg/compress/flate"><code>compress/flate</code></a>, +<a href="/pkg/compress/gzip"><code>compress/gzip</code></a> and +<a href="/pkg/compress/zlib"><code>compress/zlib</code></a> +all return <code>(*Writer, error)</code> if they take a compression level, +and <code>*Writer</code> otherwise. Package <code>gzip</code>'s +<code>Compressor</code> and <code>Decompressor</code> types have been renamed +to <code>Writer</code> and <code>Reader</code>. Package <code>flate</code>'s +<code>WrongValueError</code> type has been removed. +</p> + +<p> +<em>Updating</em> +Running <code>go</code> <code>fix</code> will update old names and calls that assign the error to _. +Calls that aren't fixed will be caught by the compiler and must be updated by hand. +</p> + +<h3 id="crypto_aes_des">The crypto/aes and crypto/des packages</h3> + +<p> +In Go 1, the <code>Reset</code> method has been removed. Go does not guarantee +that memory is not copied and therefore this method was misleading. +</p> + +<p> +The cipher-specific types <code>*aes.Cipher</code>, <code>*des.Cipher</code>, +and <code>*des.TripleDESCipher</code> have been removed in favor of +<code>cipher.Block</code>. +</p> + +<p> +<em>Updating</em>: +Remove the calls to Reset. Replace uses of the specific cipher types with +cipher.Block. +</p> + +<h3 id="crypto_elliptic">The crypto/elliptic package</h3> + +<p> +In Go 1, <a href="/pkg/crypto/elliptic/#Curve"><code>elliptic.Curve</code></a> +has been made an interface to permit alternative implementations. The curve +parameters have been moved to the +<a href="/pkg/crypto/elliptic/#CurveParams"><code>elliptic.CurveParams</code></a> +structure. +</p> + +<p> +<em>Updating</em>: +Existing users of <code>*elliptic.Curve</code> will need to change to +simply <code>elliptic.Curve</code>. Calls to <code>Marshal</code>, +<code>Unmarshal</code> and <code>GenerateKey</code> are now functions +in <code>crypto/elliptic</code> that take an <code>elliptic.Curve</code> +as their first argument. +</p> + +<h3 id="crypto_hmac">The crypto/hmac package</h3> + +<p> +In Go 1, the hash-specific functions, such as <code>hmac.NewMD5</code>, have +been removed from <code>crypto/hmac</code>. Instead, <code>hmac.New</code> takes +a function that returns a <code>hash.Hash</code>, such as <code>md5.New</code>. +</p> + +<p> +<em>Updating</em>: +Running <code>go</code> <code>fix</code> will perform the needed changes. +</p> + +<h3 id="crypto_x509">The crypto/x509 package</h3> + +<p> +In Go 1, the +<a href="/pkg/crypto/x509/#CreateCertificate"><code>CreateCertificate</code></a> +and +<a href="/pkg/crypto/x509/#CreateCRL"><code>CreateCRL</code></a> +functions in <code>crypto/x509</code> have been altered to take an +<code>interface{}</code> where they previously took a <code>*rsa.PublicKey</code> +or <code>*rsa.PrivateKey</code>. This will allow other public key algorithms +to be implemented in the future. +</p> + +<p> +<em>Updating</em>: +No changes will be needed. +</p> + +<h3 id="encoding_binary">The encoding/binary package</h3> + +<p> +In Go 1, the <code>binary.TotalSize</code> function has been replaced by +<a href="/pkg/encoding/binary/#Size"><code>Size</code></a>, +which takes an <code>interface{}</code> argument rather than +a <code>reflect.Value</code>. +</p> + +<p> +<em>Updating</em>: +What little code is affected will be caught by the compiler and must be updated by hand. +</p> + +<h3 id="encoding_xml">The encoding/xml package</h3> + +<p> +In Go 1, the <a href="/pkg/encoding/xml/"><code>xml</code></a> package +has been brought closer in design to the other marshaling packages such +as <a href="/pkg/encoding/gob/"><code>encoding/gob</code></a>. +</p> + +<p> +The old <code>Parser</code> type is renamed +<a href="/pkg/encoding/xml/#Decoder"><code>Decoder</code></a> and has a new +<a href="/pkg/encoding/xml/#Decoder.Decode"><code>Decode</code></a> method. An +<a href="/pkg/encoding/xml/#Encoder"><code>Encoder</code></a> type was also introduced. +</p> + +<p> +The functions <a href="/pkg/encoding/xml/#Marshal"><code>Marshal</code></a> +and <a href="/pkg/encoding/xml/#Unmarshal"><code>Unmarshal</code></a> +work with <code>[]byte</code> values now. To work with streams, +use the new <a href="/pkg/encoding/xml/#Encoder"><code>Encoder</code></a> +and <a href="/pkg/encoding/xml/#Decoder"><code>Decoder</code></a> types. +</p> + +<p> +When marshaling or unmarshaling values, the format of supported flags in +field tags has changed to be closer to the +<a href="/pkg/encoding/json"><code>json</code></a> package +(<code>`xml:"name,flag"`</code>). The matching done between field tags, field +names, and the XML attribute and element names is now case-sensitive. +The <code>XMLName</code> field tag, if present, must also match the name +of the XML element being marshaled. +</p> + +<p> +<em>Updating</em>: +Running <code>go</code> <code>fix</code> will update most uses of the package except for some calls to +<code>Unmarshal</code>. Special care must be taken with field tags, +since the fix tool will not update them and if not fixed by hand they will +misbehave silently in some cases. For example, the old +<code>"attr"</code> is now written <code>",attr"</code> while plain +<code>"attr"</code> remains valid but with a different meaning. +</p> + +<h3 id="expvar">The expvar package</h3> + +<p> +In Go 1, the <code>RemoveAll</code> function has been removed. +The <code>Iter</code> function and Iter method on <code>*Map</code> have +been replaced by +<a href="/pkg/expvar/#Do"><code>Do</code></a> +and +<a href="/pkg/expvar/#Map.Do"><code>(*Map).Do</code></a>. +</p> + +<p> +<em>Updating</em>: +Most code using <code>expvar</code> will not need changing. The rare code that used +<code>Iter</code> can be updated to pass a closure to <code>Do</code> to achieve the same effect. +</p> + +<h3 id="flag">The flag package</h3> + +<p> +In Go 1, the interface <a href="/pkg/flag/#Value"><code>flag.Value</code></a> has changed slightly. +The <code>Set</code> method now returns an <code>error</code> instead of +a <code>bool</code> to indicate success or failure. +</p> + +<p> +There is also a new kind of flag, <code>Duration</code>, to support argument +values specifying time intervals. +Values for such flags must be given units, just as <code>time.Duration</code> +formats them: <code>10s</code>, <code>1h30m</code>, etc. +</p> + +{{code "/doc/progs/go1.go" `/timeout/`}} + +<p> +<em>Updating</em>: +Programs that implement their own flags will need minor manual fixes to update their +<code>Set</code> methods. +The <code>Duration</code> flag is new and affects no existing code. +</p> + + +<h3 id="go">The go/* packages</h3> + +<p> +Several packages under <code>go</code> have slightly revised APIs. +</p> + +<p> +A concrete <code>Mode</code> type was introduced for configuration mode flags +in the packages +<a href="/pkg/go/scanner/"><code>go/scanner</code></a>, +<a href="/pkg/go/parser/"><code>go/parser</code></a>, +<a href="/pkg/go/printer/"><code>go/printer</code></a>, and +<a href="/pkg/go/doc/"><code>go/doc</code></a>. +</p> + +<p> +The modes <code>AllowIllegalChars</code> and <code>InsertSemis</code> have been removed +from the <a href="/pkg/go/scanner/"><code>go/scanner</code></a> package. They were mostly +useful for scanning text other then Go source files. Instead, the +<a href="/pkg/text/scanner/"><code>text/scanner</code></a> package should be used +for that purpose. +</p> + +<p> +The <a href="/pkg/go/scanner/#ErrorHandler"><code>ErrorHandler</code></a> provided +to the scanner's <a href="/pkg/go/scanner/#Scanner.Init"><code>Init</code></a> method is +now simply a function rather than an interface. The <code>ErrorVector</code> type has +been removed in favor of the (existing) <a href="/pkg/go/scanner/#ErrorList"><code>ErrorList</code></a> +type, and the <code>ErrorVector</code> methods have been migrated. Instead of embedding +an <code>ErrorVector</code> in a client of the scanner, now a client should maintain +an <code>ErrorList</code>. +</p> + +<p> +The set of parse functions provided by the <a href="/pkg/go/parser/"><code>go/parser</code></a> +package has been reduced to the primary parse function +<a href="/pkg/go/parser/#ParseFile"><code>ParseFile</code></a>, and a couple of +convenience functions <a href="/pkg/go/parser/#ParseDir"><code>ParseDir</code></a> +and <a href="/pkg/go/parser/#ParseExpr"><code>ParseExpr</code></a>. +</p> + +<p> +The <a href="/pkg/go/printer/"><code>go/printer</code></a> package supports an additional +configuration mode <a href="/pkg/go/printer/#Mode"><code>SourcePos</code></a>; +if set, the printer will emit <code>//line</code> comments such that the generated +output contains the original source code position information. The new type +<a href="/pkg/go/printer/#CommentedNode"><code>CommentedNode</code></a> can be +used to provide comments associated with an arbitrary +<a href="/pkg/go/ast/#Node"><code>ast.Node</code></a> (until now only +<a href="/pkg/go/ast/#File"><code>ast.File</code></a> carried comment information). +</p> + +<p> +The type names of the <a href="/pkg/go/doc/"><code>go/doc</code></a> package have been +streamlined by removing the <code>Doc</code> suffix: <code>PackageDoc</code> +is now <code>Package</code>, <code>ValueDoc</code> is <code>Value</code>, etc. +Also, all types now consistently have a <code>Name</code> field (or <code>Names</code>, +in the case of type <code>Value</code>) and <code>Type.Factories</code> has become +<code>Type.Funcs</code>. +Instead of calling <code>doc.NewPackageDoc(pkg, importpath)</code>, +documentation for a package is created with: +</p> + +<pre> + doc.New(pkg, importpath, mode) +</pre> + +<p> +where the new <code>mode</code> parameter specifies the operation mode: +if set to <a href="/pkg/go/doc/#AllDecls"><code>AllDecls</code></a>, all declarations +(not just exported ones) are considered. +The function <code>NewFileDoc</code> was removed, and the function +<code>CommentText</code> has become the method +<a href="/pkg/go/ast/#Text"><code>Text</code></a> of +<a href="/pkg/go/ast/#CommentGroup"><code>ast.CommentGroup</code></a>. +</p> + +<p> +In package <a href="/pkg/go/token/"><code>go/token</code></a>, the +<a href="/pkg/go/token/#FileSet"><code>token.FileSet</code></a> method <code>Files</code> +(which originally returned a channel of <code>*token.File</code>s) has been replaced +with the iterator <a href="/pkg/go/token/#FileSet.Iterate"><code>Iterate</code></a> that +accepts a function argument instead. +</p> + +<p> +In package <a href="/pkg/go/build/"><code>go/build</code></a>, the API +has been nearly completely replaced. +The package still computes Go package information +but it does not run the build: the <code>Cmd</code> and <code>Script</code> +types are gone. +(To build code, use the new +<a href="/cmd/go/"><code>go</code></a> command instead.) +The <code>DirInfo</code> type is now named +<a href="/pkg/go/build/#Package"><code>Package</code></a>. +<code>FindTree</code> and <code>ScanDir</code> are replaced by +<a href="/pkg/go/build/#Import"><code>Import</code></a> +and +<a href="/pkg/go/build/#ImportDir"><code>ImportDir</code></a>. +</p> + +<p> +<em>Updating</em>: +Code that uses packages in <code>go</code> will have to be updated by hand; the +compiler will reject incorrect uses. Templates used in conjunction with any of the +<code>go/doc</code> types may need manual fixes; the renamed fields will lead +to run-time errors. +</p> + +<h3 id="hash">The hash package</h3> + +<p> +In Go 1, the definition of <a href="/pkg/hash/#Hash"><code>hash.Hash</code></a> includes +a new method, <code>BlockSize</code>. This new method is used primarily in the +cryptographic libraries. +</p> + +<p> +The <code>Sum</code> method of the +<a href="/pkg/hash/#Hash"><code>hash.Hash</code></a> interface now takes a +<code>[]byte</code> argument, to which the hash value will be appended. +The previous behavior can be recreated by adding a <code>nil</code> argument to the call. +</p> + +<p> +<em>Updating</em>: +Existing implementations of <code>hash.Hash</code> will need to add a +<code>BlockSize</code> method. Hashes that process the input one byte at +a time can implement <code>BlockSize</code> to return 1. +Running <code>go</code> <code>fix</code> will update calls to the <code>Sum</code> methods of the various +implementations of <code>hash.Hash</code>. +</p> + +<p> +<em>Updating</em>: +Since the package's functionality is new, no updating is necessary. +</p> + +<h3 id="http">The http package</h3> + +<p> +In Go 1 the <a href="/pkg/net/http/"><code>http</code></a> package is refactored, +putting some of the utilities into a +<a href="/pkg/net/httputil/"><code>httputil</code></a> subdirectory. +These pieces are only rarely needed by HTTP clients. +The affected items are: +</p> + +<ul> +<li>ClientConn</li> +<li>DumpRequest</li> +<li>DumpRequest</li> +<li>DumpRequestOut</li> +<li>DumpResponse</li> +<li>NewChunkedReader</li> +<li>NewChunkedWriter</li> +<li>NewClientConn</li> +<li>NewProxyClientConn</li> +<li>NewServerConn</li> +<li>NewSingleHostReverseProxy</li> +<li>ReverseProxy</li> +<li>ServerConn</li> +</ul> + +<p> +The <code>Request.RawURL</code> field has been removed; it was a +historical artifact. +</p> + +<p> +The <code>Handle</code> and <code>HandleFunc</code> +functions, and the similarly-named methods of <code>ServeMux</code>, +now panic if an attempt is made to register the same pattern twice. +</p> + +<p> +<em>Updating</em>: +Running <code>go</code> <code>fix</code> will update the few programs that are affected except for +uses of <code>RawURL</code>, which must be fixed by hand. +</p> + +<h3 id="image">The image package</h3> + +<p> +The <a href="/pkg/image/"><code>image</code></a> package has had a number of +minor changes, rearrangements and renamings. +</p> + +<p> +Most of the color handling code has been moved into its own package, +<a href="/pkg/image/color/"><code>image/color</code></a>. +For the elements that moved, a symmetry arises; for instance, +each pixel of an +<a href="/pkg/image/#RGBA"><code>image.RGBA</code></a> +is a +<a href="/pkg/image/color/#RGBA"><code>color.RGBA</code></a>. +</p> + +<p> +The old <code>image/ycbcr</code> package has been folded, with some +renamings, into the +<a href="/pkg/image/"><code>image</code></a> +and +<a href="/pkg/image/color/"><code>image/color</code></a> +packages. +</p> + +<p> +The old <code>image.ColorImage</code> type is still in the <code>image</code> +package but has been renamed +<a href="/pkg/image/#Uniform"><code>image.Uniform</code></a>, +while <code>image.Tiled</code> has been removed. +</p> + +<p> +This table lists the renamings. +</p> + +<table class="codetable" frame="border" summary="image renames"> +<colgroup align="left" width="50%"></colgroup> +<colgroup align="left" width="50%"></colgroup> +<tr> +<th align="left">Old</th> +<th align="left">New</th> +</tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>image.Color</td> <td>color.Color</td></tr> +<tr><td>image.ColorModel</td> <td>color.Model</td></tr> +<tr><td>image.ColorModelFunc</td> <td>color.ModelFunc</td></tr> +<tr><td>image.PalettedColorModel</td> <td>color.Palette</td></tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>image.RGBAColor</td> <td>color.RGBA</td></tr> +<tr><td>image.RGBA64Color</td> <td>color.RGBA64</td></tr> +<tr><td>image.NRGBAColor</td> <td>color.NRGBA</td></tr> +<tr><td>image.NRGBA64Color</td> <td>color.NRGBA64</td></tr> +<tr><td>image.AlphaColor</td> <td>color.Alpha</td></tr> +<tr><td>image.Alpha16Color</td> <td>color.Alpha16</td></tr> +<tr><td>image.GrayColor</td> <td>color.Gray</td></tr> +<tr><td>image.Gray16Color</td> <td>color.Gray16</td></tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>image.RGBAColorModel</td> <td>color.RGBAModel</td></tr> +<tr><td>image.RGBA64ColorModel</td> <td>color.RGBA64Model</td></tr> +<tr><td>image.NRGBAColorModel</td> <td>color.NRGBAModel</td></tr> +<tr><td>image.NRGBA64ColorModel</td> <td>color.NRGBA64Model</td></tr> +<tr><td>image.AlphaColorModel</td> <td>color.AlphaModel</td></tr> +<tr><td>image.Alpha16ColorModel</td> <td>color.Alpha16Model</td></tr> +<tr><td>image.GrayColorModel</td> <td>color.GrayModel</td></tr> +<tr><td>image.Gray16ColorModel</td> <td>color.Gray16Model</td></tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>ycbcr.RGBToYCbCr</td> <td>color.RGBToYCbCr</td></tr> +<tr><td>ycbcr.YCbCrToRGB</td> <td>color.YCbCrToRGB</td></tr> +<tr><td>ycbcr.YCbCrColorModel</td> <td>color.YCbCrModel</td></tr> +<tr><td>ycbcr.YCbCrColor</td> <td>color.YCbCr</td></tr> +<tr><td>ycbcr.YCbCr</td> <td>image.YCbCr</td></tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>ycbcr.SubsampleRatio444</td> <td>image.YCbCrSubsampleRatio444</td></tr> +<tr><td>ycbcr.SubsampleRatio422</td> <td>image.YCbCrSubsampleRatio422</td></tr> +<tr><td>ycbcr.SubsampleRatio420</td> <td>image.YCbCrSubsampleRatio420</td></tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>image.ColorImage</td> <td>image.Uniform</td></tr> +</table> + +<p> +The image package's <code>New</code> functions +(<a href="/pkg/image/#NewRGBA"><code>NewRGBA</code></a>, +<a href="/pkg/image/#NewRGBA64"><code>NewRGBA64</code></a>, etc.) +take an <a href="/pkg/image/#Rectangle"><code>image.Rectangle</code></a> as an argument +instead of four integers. +</p> + +<p> +Finally, there are new predefined <code>color.Color</code> variables +<a href="/pkg/image/color/#Black"><code>color.Black</code></a>, +<a href="/pkg/image/color/#White"><code>color.White</code></a>, +<a href="/pkg/image/color/#Opaque"><code>color.Opaque</code></a> +and +<a href="/pkg/image/color/#Transparent"><code>color.Transparent</code></a>. +</p> + +<p> +<em>Updating</em>: +Running <code>go</code> <code>fix</code> will update almost all code affected by the change. +</p> + +<h3 id="log_syslog">The log/syslog package</h3> + +<p> +In Go 1, the <a href="/pkg/log/syslog/#NewLogger"><code>syslog.NewLogger</code></a> +function returns an error as well as a <code>log.Logger</code>. +</p> + +<p> +<em>Updating</em>: +What little code is affected will be caught by the compiler and must be updated by hand. +</p> + +<h3 id="mime">The mime package</h3> + +<p> +In Go 1, the <a href="/pkg/mime/#FormatMediaType"><code>FormatMediaType</code></a> function +of the <code>mime</code> package has been simplified to make it +consistent with +<a href="/pkg/mime/#ParseMediaType"><code>ParseMediaType</code></a>. +It now takes <code>"text/html"</code> rather than <code>"text"</code> and <code>"html"</code>. +</p> + +<p> +<em>Updating</em>: +What little code is affected will be caught by the compiler and must be updated by hand. +</p> + +<h3 id="net">The net package</h3> + +<p> +In Go 1, the various <code>SetTimeout</code>, +<code>SetReadTimeout</code>, and <code>SetWriteTimeout</code> methods +have been replaced with +<a href="/pkg/net/#IPConn.SetDeadline"><code>SetDeadline</code></a>, +<a href="/pkg/net/#IPConn.SetReadDeadline"><code>SetReadDeadline</code></a>, and +<a href="/pkg/net/#IPConn.SetWriteDeadline"><code>SetWriteDeadline</code></a>, +respectively. Rather than taking a timeout value in nanoseconds that +apply to any activity on the connection, the new methods set an +absolute deadline (as a <code>time.Time</code> value) after which +reads and writes will time out and no longer block. +</p> + +<p> +There are also new functions +<a href="/pkg/net/#DialTimeout"><code>net.DialTimeout</code></a> +to simplify timing out dialing a network address and +<a href="/pkg/net/#ListenMulticastUDP"><code>net.ListenMulticastUDP</code></a> +to allow multicast UDP to listen concurrently across multiple listeners. +The <code>net.ListenMulticastUDP</code> function replaces the old +<code>JoinGroup</code> and <code>LeaveGroup</code> methods. +</p> + +<p> +<em>Updating</em>: +Code that uses the old methods will fail to compile and must be updated by hand. +The semantic change makes it difficult for the fix tool to update automatically. +</p> + +<h3 id="os">The os package</h3> + +<p> +The <code>Time</code> function has been removed; callers should use +the <a href="/pkg/time/#Time"><code>Time</code></a> type from the +<code>time</code> package. +</p> + +<p> +The <code>Exec</code> function has been removed; callers should use +<code>Exec</code> from the <code>syscall</code> package, where available. +</p> + +<p> +The <code>ShellExpand</code> function has been renamed to <a +href="/pkg/os/#ExpandEnv"><code>ExpandEnv</code></a>. +</p> + +<p> +The <a href="/pkg/os/#NewFile"><code>NewFile</code></a> function +now takes a <code>uintptr</code> fd, instead of an <code>int</code>. +The <a href="/pkg/os/#File.Fd"><code>Fd</code></a> method on files now +also returns a <code>uintptr</code>. +</p> + +<p> +There are no longer error constants such as <code>EINVAL</code> +in the <code>os</code> package, since the set of values varied with +the underlying operating system. There are new portable functions like +<a href="/pkg/os/#IsPermission"><code>IsPermission</code></a> +to test common error properties, plus a few new error values +with more Go-like names, such as +<a href="/pkg/os/#ErrPermission"><code>ErrPermission</code></a> +and +<a href="/pkg/os/#ErrNoEnv"><code>ErrNoEnv</code></a>. +</p> + +<p> +The <code>Getenverror</code> function has been removed. To distinguish +between a non-existent environment variable and an empty string, +use <a href="/pkg/os/#Environ"><code>os.Environ</code></a> or +<a href="/pkg/syscall/#Getenv"><code>syscall.Getenv</code></a>. +</p> + + +<p> +The <a href="/pkg/os/#Process.Wait"><code>Process.Wait</code></a> method has +dropped its option argument and the associated constants are gone +from the package. +Also, the function <code>Wait</code> is gone; only the method of +the <code>Process</code> type persists. +</p> + +<p> +The <code>Waitmsg</code> type returned by +<a href="/pkg/os/#Process.Wait"><code>Process.Wait</code></a> +has been replaced with a more portable +<a href="/pkg/os/#ProcessState"><code>ProcessState</code></a> +type with accessor methods to recover information about the +process. +Because of changes to <code>Wait</code>, the <code>ProcessState</code> +value always describes an exited process. +Portability concerns simplified the interface in other ways, but the values returned by the +<a href="/pkg/os/#ProcessState.Sys"><code>ProcessState.Sys</code></a> and +<a href="/pkg/os/#ProcessState.SysUsage"><code>ProcessState.SysUsage</code></a> +methods can be type-asserted to underlying system-specific data structures such as +<a href="/pkg/syscall/#WaitStatus"><code>syscall.WaitStatus</code></a> and +<a href="/pkg/syscall/#Rusage"><code>syscall.Rusage</code></a> on Unix. +</p> + +<p> +<em>Updating</em>: +Running <code>go</code> <code>fix</code> will drop a zero argument to <code>Process.Wait</code>. +All other changes will be caught by the compiler and must be updated by hand. +</p> + +<h4 id="os_fileinfo">The os.FileInfo type</h4> + +<p> +Go 1 redefines the <a href="/pkg/os/#FileInfo"><code>os.FileInfo</code></a> type, +changing it from a struct to an interface: +</p> + +<pre> + type FileInfo interface { + Name() string // base name of the file + Size() int64 // length in bytes + Mode() FileMode // file mode bits + ModTime() time.Time // modification time + IsDir() bool // abbreviation for Mode().IsDir() + Sys() interface{} // underlying data source (can return nil) + } +</pre> + +<p> +The file mode information has been moved into a subtype called +<a href="/pkg/os/#FileMode"><code>os.FileMode</code></a>, +a simple integer type with <code>IsDir</code>, <code>Perm</code>, and <code>String</code> +methods. +</p> + +<p> +The system-specific details of file modes and properties such as (on Unix) +i-number have been removed from <code>FileInfo</code> altogether. +Instead, each operating system's <code>os</code> package provides an +implementation of the <code>FileInfo</code> interface, which +has a <code>Sys</code> method that returns the +system-specific representation of file metadata. +For instance, to discover the i-number of a file on a Unix system, unpack +the <code>FileInfo</code> like this: +</p> + +<pre> + fi, err := os.Stat("hello.go") + if err != nil { + log.Fatal(err) + } + // Check that it's a Unix file. + unixStat, ok := fi.Sys().(*syscall.Stat_t) + if !ok { + log.Fatal("hello.go: not a Unix file") + } + fmt.Printf("file i-number: %d\n", unixStat.Ino) +</pre> + +<p> +Assuming (which is unwise) that <code>"hello.go"</code> is a Unix file, +the i-number expression could be contracted to +</p> + +<pre> + fi.Sys().(*syscall.Stat_t).Ino +</pre> + +<p> +The vast majority of uses of <code>FileInfo</code> need only the methods +of the standard interface. +</p> + +<p> +The <code>os</code> package no longer contains wrappers for the POSIX errors +such as <code>ENOENT</code>. +For the few programs that need to verify particular error conditions, there are +now the boolean functions +<a href="/pkg/os/#IsExist"><code>IsExist</code></a>, +<a href="/pkg/os/#IsNotExist"><code>IsNotExist</code></a> +and +<a href="/pkg/os/#IsPermission"><code>IsPermission</code></a>. +</p> + +{{code "/doc/progs/go1.go" `/os\.Open/` `/}/`}} + +<p> +<em>Updating</em>: +Running <code>go</code> <code>fix</code> will update code that uses the old equivalent of the current <code>os.FileInfo</code> +and <code>os.FileMode</code> API. +Code that needs system-specific file details will need to be updated by hand. +Code that uses the old POSIX error values from the <code>os</code> package +will fail to compile and will also need to be updated by hand. +</p> + +<h3 id="os_signal">The os/signal package</h3> + +<p> +The <code>os/signal</code> package in Go 1 replaces the +<code>Incoming</code> function, which returned a channel +that received all incoming signals, +with the selective <code>Notify</code> function, which asks +for delivery of specific signals on an existing channel. +</p> + +<p> +<em>Updating</em>: +Code must be updated by hand. +A literal translation of +</p> +<pre> +c := signal.Incoming() +</pre> +<p> +is +</p> +<pre> +c := make(chan os.Signal) +signal.Notify(c) // ask for all signals +</pre> +<p> +but most code should list the specific signals it wants to handle instead: +</p> +<pre> +c := make(chan os.Signal) +signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT) +</pre> + +<h3 id="path_filepath">The path/filepath package</h3> + +<p> +In Go 1, the <a href="/pkg/path/filepath/#Walk"><code>Walk</code></a> function of the +<code>path/filepath</code> package +has been changed to take a function value of type +<a href="/pkg/path/filepath/#WalkFunc"><code>WalkFunc</code></a> +instead of a <code>Visitor</code> interface value. +<code>WalkFunc</code> unifies the handling of both files and directories. +</p> + +<pre> + type WalkFunc func(path string, info os.FileInfo, err error) error +</pre> + +<p> +The <code>WalkFunc</code> function will be called even for files or directories that could not be opened; +in such cases the error argument will describe the failure. +If a directory's contents are to be skipped, +the function should return the value <a href="/pkg/path/filepath/#variables"><code>filepath.SkipDir</code></a> +</p> + +{{code "/doc/progs/go1.go" `/STARTWALK/` `/ENDWALK/`}} + +<p> +<em>Updating</em>: +The change simplifies most code but has subtle consequences, so affected programs +will need to be updated by hand. +The compiler will catch code using the old interface. +</p> + +<h3 id="regexp">The regexp package</h3> + +<p> +The <a href="/pkg/regexp/"><code>regexp</code></a> package has been rewritten. +It has the same interface but the specification of the regular expressions +it supports has changed from the old "egrep" form to that of +<a href="http://code.google.com/p/re2/">RE2</a>. +</p> + +<p> +<em>Updating</em>: +Code that uses the package should have its regular expressions checked by hand. +</p> + +<h3 id="runtime">The runtime package</h3> + +<p> +In Go 1, much of the API exported by package +<code>runtime</code> has been removed in favor of +functionality provided by other packages. +Code using the <code>runtime.Type</code> interface +or its specific concrete type implementations should +now use package <a href="/pkg/reflect/"><code>reflect</code></a>. +Code using <code>runtime.Semacquire</code> or <code>runtime.Semrelease</code> +should use channels or the abstractions in package <a href="/pkg/sync/"><code>sync</code></a>. +The <code>runtime.Alloc</code>, <code>runtime.Free</code>, +and <code>runtime.Lookup</code> functions, an unsafe API created for +debugging the memory allocator, have no replacement. +</p> + +<p> +Before, <code>runtime.MemStats</code> was a global variable holding +statistics about memory allocation, and calls to <code>runtime.UpdateMemStats</code> +ensured that it was up to date. +In Go 1, <code>runtime.MemStats</code> is a struct type, and code should use +<a href="/pkg/runtime/#ReadMemStats"><code>runtime.ReadMemStats</code></a> +to obtain the current statistics. +</p> + +<p> +The package adds a new function, +<a href="/pkg/runtime/#NumCPU"><code>runtime.NumCPU</code></a>, that returns the number of CPUs available +for parallel execution, as reported by the operating system kernel. +Its value can inform the setting of <code>GOMAXPROCS</code>. +The <code>runtime.Cgocalls</code> and <code>runtime.Goroutines</code> functions +have been renamed to <code>runtime.NumCgoCall</code> and <code>runtime.NumGoroutine</code>. +</p> + +<p> +<em>Updating</em>: +Running <code>go</code> <code>fix</code> will update code for the function renamings. +Other code will need to be updated by hand. +</p> + +<h3 id="strconv">The strconv package</h3> + +<p> +In Go 1, the +<a href="/pkg/strconv/"><code>strconv</code></a> +package has been significantly reworked to make it more Go-like and less C-like, +although <code>Atoi</code> lives on (it's similar to +<code>int(ParseInt(x, 10, 0))</code>, as does +<code>Itoa(x)</code> (<code>FormatInt(int64(x), 10)</code>). +There are also new variants of some of the functions that append to byte slices rather than +return strings, to allow control over allocation. +</p> + +<p> +This table summarizes the renamings; see the +<a href="/pkg/strconv/">package documentation</a> +for full details. +</p> + +<table class="codetable" frame="border" summary="strconv renames"> +<colgroup align="left" width="50%"></colgroup> +<colgroup align="left" width="50%"></colgroup> +<tr> +<th align="left">Old call</th> +<th align="left">New call</th> +</tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>Atob(x)</td> <td>ParseBool(x)</td></tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>Atof32(x)</td> <td>ParseFloat(x, 32)§</td></tr> +<tr><td>Atof64(x)</td> <td>ParseFloat(x, 64)</td></tr> +<tr><td>AtofN(x, n)</td> <td>ParseFloat(x, n)</td></tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>Atoi(x)</td> <td>Atoi(x)</td></tr> +<tr><td>Atoi(x)</td> <td>ParseInt(x, 10, 0)§</td></tr> +<tr><td>Atoi64(x)</td> <td>ParseInt(x, 10, 64)</td></tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>Atoui(x)</td> <td>ParseUint(x, 10, 0)§</td></tr> +<tr><td>Atoi64(x)</td> <td>ParseInt(x, 10, 64)</td></tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>Btoi64(x, b)</td> <td>ParseInt(x, b, 64)</td></tr> +<tr><td>Btoui64(x, b)</td> <td>ParseUint(x, b, 64)</td></tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>Btoa(x)</td> <td>FormatBool(x)</td></tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>Ftoa32(x, f, p)</td> <td>FormatFloat(float64(x), f, p, 32)</td></tr> +<tr><td>Ftoa64(x, f, p)</td> <td>FormatFloat(x, f, p, 64)</td></tr> +<tr><td>FtoaN(x, f, p, n)</td> <td>FormatFloat(x, f, p, n)</td></tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>Itoa(x)</td> <td>Itoa(x)</td></tr> +<tr><td>Itoa(x)</td> <td>FormatInt(int64(x), 10)</td></tr> +<tr><td>Itoa64(x)</td> <td>FormatInt(x, 10)</td></tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>Itob(x, b)</td> <td>FormatInt(int64(x), b)</td></tr> +<tr><td>Itob64(x, b)</td> <td>FormatInt(x, b)</td></tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>Uitoa(x)</td> <td>FormatUint(uint64(x), 10)</td></tr> +<tr><td>Uitoa64(x)</td> <td>FormatUint(x, 10)</td></tr> +<tr> +<td colspan="2"><hr></td> +</tr> +<tr><td>Uitob(x, b)</td> <td>FormatUint(uint64(x), b)</td></tr> +<tr><td>Uitob64(x, b)</td> <td>FormatUint(x, b)</td></tr> +</table> + +<p> +<em>Updating</em>: +Running <code>go</code> <code>fix</code> will update almost all code affected by the change. +<br> +§ <code>Atoi</code> persists but <code>Atoui</code> and <code>Atof32</code> do not, so +they may require +a cast that must be added by hand; the <code>go</code> <code>fix</code> tool will warn about it. +</p> + + +<h3 id="templates">The template packages</h3> + +<p> +The <code>template</code> and <code>exp/template/html</code> packages have moved to +<a href="/pkg/text/template/"><code>text/template</code></a> and +<a href="/pkg/html/template/"><code>html/template</code></a>. +More significant, the interface to these packages has been simplified. +The template language is the same, but the concept of "template set" is gone +and the functions and methods of the packages have changed accordingly, +often by elimination. +</p> + +<p> +Instead of sets, a <code>Template</code> object +may contain multiple named template definitions, +in effect constructing +name spaces for template invocation. +A template can invoke any other template associated with it, but only those +templates associated with it. +The simplest way to associate templates is to parse them together, something +made easier with the new structure of the packages. +</p> + +<p> +<em>Updating</em>: +The imports will be updated by fix tool. +Single-template uses will be otherwise be largely unaffected. +Code that uses multiple templates in concert will need to be updated by hand. +The <a href="/pkg/text/template/#examples">examples</a> in +the documentation for <code>text/template</code> can provide guidance. +</p> + +<h3 id="testing">The testing package</h3> + +<p> +The testing package has a type, <code>B</code>, passed as an argument to benchmark functions. +In Go 1, <code>B</code> has new methods, analogous to those of <code>T</code>, enabling +logging and failure reporting. +</p> + +{{code "/doc/progs/go1.go" `/func.*Benchmark/` `/^}/`}} + +<p> +<em>Updating</em>: +Existing code is unaffected, although benchmarks that use <code>println</code> +or <code>panic</code> should be updated to use the new methods. +</p> + +<h3 id="testing_script">The testing/script package</h3> + +<p> +The testing/script package has been deleted. It was a dreg. +</p> + +<p> +<em>Updating</em>: +No code is likely to be affected. +</p> + +<h3 id="unsafe">The unsafe package</h3> + +<p> +In Go 1, the functions +<code>unsafe.Typeof</code>, <code>unsafe.Reflect</code>, +<code>unsafe.Unreflect</code>, <code>unsafe.New</code>, and +<code>unsafe.NewArray</code> have been removed; +they duplicated safer functionality provided by +package <a href="/pkg/reflect/"><code>reflect</code></a>. +</p> + +<p> +<em>Updating</em>: +Code using these functions must be rewritten to use +package <a href="/pkg/reflect/"><code>reflect</code></a>. +The changes to <a href="http://code.google.com/p/go/source/detail?r=2646dc956207">encoding/gob</a> and the <a href="http://code.google.com/p/goprotobuf/source/detail?r=5340ad310031">protocol buffer library</a> +may be helpful as examples. +</p> + +<h3 id="url">The url package</h3> + +<p> +In Go 1 several fields from the <a href="/pkg/net/url/#URL"><code>url.URL</code></a> type +were removed or replaced. +</p> + +<p> +The <a href="/pkg/net/url/#URL.String"><code>String</code></a> method now +predictably rebuilds an encoded URL string using all of <code>URL</code>'s +fields as necessary. The resulting string will also no longer have +passwords escaped. +</p> + +<p> +The <code>Raw</code> field has been removed. In most cases the <code>String</code> +method may be used in its place. +</p> + +<p> +The old <code>RawUserinfo</code> field is replaced by the <code>User</code> +field, of type <a href="/pkg/net/url/#Userinfo"><code>*net.Userinfo</code></a>. +Values of this type may be created using the new <a href="/pkg/net/url/#User"><code>net.User</code></a> +and <a href="/pkg/net/url/#UserPassword"><code>net.UserPassword</code></a> +functions. The <code>EscapeUserinfo</code> and <code>UnescapeUserinfo</code> +functions are also gone. +</p> + +<p> +The <code>RawAuthority</code> field has been removed. The same information is +available in the <code>Host</code> and <code>User</code> fields. +</p> + +<p> +The <code>RawPath</code> field and the <code>EncodedPath</code> method have +been removed. The path information in rooted URLs (with a slash following the +schema) is now available only in decoded form in the <code>Path</code> field. +Occasionally, the encoded data may be required to obtain information that +was lost in the decoding process. These cases must be handled by accessing +the data the URL was built from. +</p> + +<p> +URLs with non-rooted paths, such as <code>"mailto:dev@golang.org?subject=Hi"</code>, +are also handled differently. The <code>OpaquePath</code> boolean field has been +removed and a new <code>Opaque</code> string field introduced to hold the encoded +path for such URLs. In Go 1, the cited URL parses as: +</p> + +<pre> + URL{ + Scheme: "mailto", + Opaque: "dev@golang.org", + RawQuery: "subject=Hi", + } +</pre> + +<p> +A new <a href="/pkg/net/url/#URL.RequestURI"><code>RequestURI</code></a> method was +added to <code>URL</code>. +</p> + +<p> +The <code>ParseWithReference</code> function has been renamed to <code>ParseWithFragment</code>. +</p> + +<p> +<em>Updating</em>: +Code that uses the old fields will fail to compile and must be updated by hand. +The semantic changes make it difficult for the fix tool to update automatically. +</p> + +<h2 id="cmd_go">The go command</h2> + +<p> +Go 1 introduces the <a href="/cmd/go/">go command</a>, a tool for fetching, +building, and installing Go packages and commands. The <code>go</code> command +does away with makefiles, instead using Go source code to find dependencies and +determine build conditions. Most existing Go programs will no longer require +makefiles to be built. +</p> + +<p> +See <a href="/doc/code.html">How to Write Go Code</a> for a primer on the +<code>go</code> command and the <a href="/cmd/go/">go command documentation</a> +for the full details. +</p> + +<p> +<em>Updating</em>: +Projects that depend on the Go project's old makefile-based build +infrastructure (<code>Make.pkg</code>, <code>Make.cmd</code>, and so on) should +switch to using the <code>go</code> command for building Go code and, if +necessary, rewrite their makefiles to perform any auxiliary build tasks. +</p> + +<h2 id="cmd_cgo">The cgo command</h2> + +<p> +In Go 1, the <a href="/cmd/cgo">cgo command</a> +uses a different <code>_cgo_export.h</code> +file, which is generated for packages containing <code>//export</code> lines. +The <code>_cgo_export.h</code> file now begins with the C preamble comment, +so that exported function definitions can use types defined there. +This has the effect of compiling the preamble multiple times, so a +package using <code>//export</code> must not put function definitions +or variable initializations in the C preamble. +</p> + +<h2 id="releases">Packaged releases</h2> + +<p> +One of the most significant changes associated with Go 1 is the availability +of prepackaged, downloadable distributions. +They are available for many combinations of architecture and operating system +(including Windows) and the list will grow. +Installation details are described on the +<a href="/doc/install">Getting Started</a> page, while +the distributions themselves are listed on the +<a href="http://code.google.com/p/go/downloads/list">downloads page</a>. diff --git a/doc/go1compat.html b/doc/go1compat.html new file mode 100644 index 000000000..1dfd382c2 --- /dev/null +++ b/doc/go1compat.html @@ -0,0 +1,166 @@ +<!--{ + "Title": "Go 1 and the Future of Go Programs" +}--> + +<h2 id="introduction">Introduction</h2> +<p> +The release of Go version 1, Go 1 for short, is a major milestone +in the development of the language. Go 1 is a stable platform for +the growth of programs and projects written in Go. +</p> + +<p> +Go 1 defines two things: first, the specification of the language; +and second, the specification of a set of core APIs, the "standard +packages" of the Go library. The Go 1 release includes their +implementation in the form of two compiler suites (gc and gccgo), +and the core libraries themselves. +</p> + +<p> +It is intended that programs written to the Go 1 specification will +continue to compile and run correctly, unchanged, over the lifetime +of that specification. At some indefinite point, a Go 2 specification +may arise, but until that time, Go programs that work today should +continue to work even as future "point" releases of Go 1 arise (Go +1.1, Go 1.2, etc.). +</p> + +<p> +Compatibility is at the source level. Binary compatibility for +compiled packages is not guaranteed between releases. After a point +release, Go source will need to be recompiled to link against the +new release. +</p> + +<p> +The APIs may grow, acquiring new packages and features, but not in +a way that breaks existing Go 1 code. +</p> + +<h2 id="expectations">Expectations</h2> + +<p> +Although we expect that the vast majority of programs will maintain +this compatibility over time, it is impossible to guarantee that +no future change will break any program. This document is an attempt +to set expectations for the compatibility of Go 1 software in the +future. There are a number of ways in which a program that compiles +and runs today may fail to do so after a future point release. They +are all unlikely but worth recording. +</p> + +<ul> +<li> +Security. A security issue in the specification or implementation +may come to light whose resolution requires breaking compatibility. +We reserve the right to address such security issues. +</li> + +<li> +Unspecified behavior. The Go specification tries to be explicit +about most properties of the language, but there are some aspects +that are undefined. Programs that depend on such unspecified behavior +may break in future releases. +</li> + +<li> +Specification errors. If it becomes necessary to address an +inconsistency or incompleteness in the specification, resolving the +issue could affect the meaning or legality of existing programs. +We reserve the right to address such issues, including updating the +implementations. Except for security issues, no incompatible changes +to the specification would be made. +</li> + +<li> +Bugs. If a compiler or library has a bug that violates the +specification, a program that depends on the buggy behavior may +break if the bug is fixed. We reserve the right to fix such bugs. +</li> + +<li> +Struct literals. For the addition of features in later point +releases, it may be necessary to add fields to exported structs in +the API. Code that uses untagged struct literals (such as pkg.T{3, +"x"}) to create values of these types would fail to compile after +such a change. However, code that uses tagged literals (pkg.T{A: +3, B: "x"}) will continue to compile after such a change. We will +update such data structures in a way that allows tagged struct +literals to remain compatible, although untagged literals may fail +to compile. (There are also more intricate cases involving nested +data structures or interfaces, but they have the same resolution.) +We therefore recommend that composite literals whose type is defined +in a separate package should use the tagged notation. +</li> + +<li> +Dot imports. If a program imports a standard package +using <code>import . "path"</code>, additional names defined in the +imported package in future releases may conflict with other names +defined in the program. We do not recommend the use of <code>import .</code> +outside of tests, and using it may cause a program to fail +to compile in future releases. +</li> + +</ul> + +<p> +Of course, for all of these possibilities, should they arise, we +would endeavor whenever feasible to update the specification, +compilers, or libraries without affecting existing code. +</p> + +<p> +These same considerations apply to successive point releases. For +instance, code that runs under Go 1.2 should be compatible with Go +1.2.1, Go 1.3, Go 1.4, etc., although not necessarily with Go 1.1 +since it may use features added only in Go 1.2 +</p> + +<p> +Features added between releases, available in the source repository +but not part of the numbered binary releases, are under active +development. No promise of compatibility is made for software using +such features until they have been released. +</p> + +<p> +Finally, although it is not a correctness issue, it is possible +that the performance of a program may be affected by +changes in the implementation of the compilers or libraries upon +which it depends. +No guarantee can be made about the performance of a +given program between releases. +</p> + +<p> +Although these expectations apply to Go 1 itself, we hope similar +considerations would be made for the development of externally +developed software based on Go 1. +</p> + +<h2 id="subrepos">Sub-repositories</h2> + +<p> +Code in sub-repositories of the main go tree, such as +<a href="http://code.google.com/p/go.net">code.google.com/p/go.net</a>, +may be developed under +looser compatibility requirements. However, the sub-repositories +will be tagged as appropriate to identify versions that are compatible +with the Go 1 point releases. +</p> + +<h2 id="tools">Tools</h2> + +<p> +Finally, the Go tool chain (compilers, linkers, build tools, and so +on) are under active development and may change behavior. This +means, for instance, that scripts that depend on the location and +properties of the tools may be broken by a point release. +</p> + +<p> +These caveats aside, we believe that Go 1 will be a firm foundation +for the development of Go and its ecosystem. +</p> diff --git a/doc/go_faq.html b/doc/go_faq.html index aeed53795..b5b7cc656 100644 --- a/doc/go_faq.html +++ b/doc/go_faq.html @@ -1,4 +1,6 @@ -<!-- FAQ --> +<!--{ + "Title": "FAQ" +}--> <h2 id="Origins">Origins</h2> @@ -74,20 +76,6 @@ The logo and mascot are covered by the license. </p> -<h3 id="What_kind_of_a_name_is_6g"> -What kind of a name is 6g?</h3> - -<p> -The <code>6g</code> (and <code>8g</code> and <code>5g</code>) compiler is named in the -tradition of the Plan 9 C compilers, described in -<a href="http://plan9.bell-labs.com/sys/doc/compiler.html"> -http://plan9.bell-labs.com/sys/doc/compiler.html</a> -(see the table in section 2). - -<code>6</code> is the architecture letter for amd64 (or x86-64, if you prefer), while -<code>g</code> stands for Go. -</p> - <h3 id="history"> What is the history of the project?</h3> <p> @@ -188,18 +176,19 @@ easier to understand what happens when things combine. <p> Yes. There are now several Go programs deployed in -production inside Google. For instance, the server behind -<a href="http://golang.org">http://golang.org</a> is a Go program; -in fact it's just the <a href="/cmd/godoc"><code>godoc</code></a> -document server running in a production configuration. +production inside Google. A public example is the server behind +<a href="http://golang.org">http://golang.org</a>. +It's just the <a href="/cmd/godoc"><code>godoc</code></a> +document server running in a production configuration on +<a href="http://code.google.com/appengine/">Google App Engine</a>. </p> <h3 id="Do_Go_programs_link_with_Cpp_programs"> Do Go programs link with C/C++ programs?</h3> <p> -There are two Go compiler implementations, <code>6g</code> and friends, -generically called <code>gc</code>, and <code>gccgo</code>. +There are two Go compiler implementations, <code>gc</code> +(the <code>6g</code> program and friends) and <code>gccgo</code>. <code>Gc</code> uses a different calling convention and linker and can therefore only be linked with C programs using the same convention. There is such a C compiler but no C++ compiler. @@ -317,10 +306,9 @@ exceptional. <p> Go takes a different approach. For plain error handling, Go's multi-value returns make it easy to report an error without overloading the return value. -<a href="http://blog.golang.org/2011/07/error-handling-and-go.html">A -canonical error type, coupled -with Go's other features</a>, makes error -handling pleasant but quite different from that in other languages. +<a href="/doc/articles/error_handling.html">A canonical error type, coupled +with Go's other features</a>, makes error handling pleasant but quite different +from that in other languages. </p> <p> @@ -333,7 +321,7 @@ when used well, can result in clean error-handling code. </p> <p> -See the <a href="http://blog.golang.org/2010/08/defer-panic-and-recover.html">Defer, Panic, and Recover</a> article for details. +See the <a href="/doc/articles/defer_panic_recover.html">Defer, Panic, and Recover</a> article for details. </p> <h3 id="assertions"> @@ -351,26 +339,6 @@ not familiar with the code. </p> <p> -The same arguments apply to the use of <code>assert()</code> in test programs. Proper -error handling means letting other tests run after one has failed, so -that the person debugging the failure gets a complete picture of what is -wrong. It is more useful for a test to report that -<code>isPrime</code> gives the wrong answer for 2, 3, 5, and 7 (or for -2, 4, 8, and 16) than to report that <code>isPrime</code> gives the wrong -answer for 2 and therefore no more tests were run. The programmer who -triggers the test failure may not be familiar with the code that fails. -Time invested writing a good error message now pays off later when the -test breaks. -</p> - -<p> -In testing, if the amount of extra code required to write -good errors seems repetitive and overwhelming, it might work better as a -table-driven test instead. -Go has excellent support for data structure literals. -</p> - -<p> We understand that this is a point of contention. There are many things in the Go language and libraries that differ from modern practices, simply because we feel it's sometimes worth trying a different approach. @@ -380,7 +348,7 @@ because we feel it's sometimes worth trying a different approach. Why build concurrency on the ideas of CSP?</h3> <p> Concurrency and multi-threaded programming have a reputation -for difficulty. We believe the problem is due partly to complex +for difficulty. We believe this is due partly to complex designs such as pthreads and partly to overemphasis on low-level details such as mutexes, condition variables, and memory barriers. Higher-level interfaces enable much simpler code, even if there are still @@ -451,7 +419,9 @@ we believe is easy to use and in some ways more general. There are also ways to embed types in other types to provide something analogous—but not identical—to subclassing. Moreover, methods in Go are more general than in C++ or Java: -they can be defined for any sort of data, not just structs. +they can be defined for any sort of data, even built-in types such +as plain, “unboxed” integers. +They are not restricted to structs (classes). </p> <p> @@ -464,7 +434,7 @@ How do I get dynamic dispatch of methods?</h3> <p> The only way to have dynamically dispatched methods is through an -interface. Methods on structs or other types are always resolved statically. +interface. Methods on a struct or any other concrete type are always resolved statically. </p> <h3 id="inheritance"> @@ -496,10 +466,11 @@ It's possible to use these ideas to construct something analogous to type-safe Unix pipes. For instance, see how <code>fmt.Fprintf</code> enables formatted printing to any output, not just a file, or how the <code>bufio</code> package can be completely separate from file I/O, -or how the <code>crypto</code> packages stitch together block and -stream ciphers. All these ideas stem from a single interface +or how the <code>image</code> packages generate compressed +image files. All these ideas stem from a single interface (<code>io.Writer</code>) representing a single method (<code>Write</code>). And that's only scratching the surface. +Go's interfaces have a profound influence on how programs are structured. </p> <p> @@ -559,7 +530,7 @@ interface <code>I</code> by attempting an assignment: <pre> type T struct{} -var _ I = T{} +var _ I = T{} // Verify that T implements I. </pre> <p> @@ -575,8 +546,8 @@ For example: <pre> type Fooer interface { - Foo() - ImplementsFooer() + Foo() + ImplementsFooer() } </pre> @@ -608,7 +579,7 @@ itself with another value: <pre> type Equaler interface { - Equal(Equaler) bool + Equal(Equaler) bool } </pre> @@ -681,7 +652,7 @@ examples and also have them be statically checked. Can I convert a []T to an []interface{}?</h3> <p> -Not directly because they do not have the same representation in memory. +Not directly, because they do not have the same representation in memory. It is necessary to copy the elements individually to the destination slice. This example converts a slice of <code>int</code> to a slice of <code>interface{}</code>: @@ -691,10 +662,89 @@ slice. This example converts a slice of <code>int</code> to a slice of t := []int{1, 2, 3, 4} s := make([]interface{}, len(t)) for i, v := range t { - s[i] = v + s[i] = v +} +</pre> + +<h3 id="nil_error"> +Why is my nil error value not equal to nil? +</h3> + +<p> +Under the covers, interfaces are implemented as two elements, a type and a value. +The value, called the interface's dynamic value, +is an arbitrary concrete value and the type is that of the value. +For the <code>int</code> value 3, an interface value contains, +schematically, (<code>int</code>, <code>3</code>). +</p> + +<p> +An interface value is <code>nil</code> only if the inner value and type are both unset, +(<code>nil</code>, <code>nil</code>). +In particular, a <code>nil</code> interface will always hold a <code>nil</code> type. +If we store a pointer of type <code>*int</code> inside +an interface value, the inner type will be <code>*int</code> regardless of the value of the pointer: +(<code>*int</code>, <code>nil</code>). +Such an interface value will therefore be non-<code>nil</code> +<em>even when the pointer inside is</em> <code>nil</code>. +</p> + +<p> +This situation can be confusing, and often arises when a <code>nil</code> value is +stored inside an interface value such as an <code>error</code> return: +</p> + +<pre> +func returnsError() error { + var p *MyError = nil + if bad() { + p = ErrBad + } + return p // Will always return a non-nil error. +} +</pre> + +<p> +If all goes well, the function returns a <code>nil</code> <code>p</code>, +so the return value is an <code>error</code> interface +value holding (<code>*MyError</code>, <code>nil</code>). +This means that if the caller compares the returned error to <code>nil</code>, +it will always look as if there was an error even if nothing bad happened. +To return a proper <code>nil</code> <code>error</code> to the caller, +the function must return an explicit <code>nil</code>: +</p> + + +<pre> +func returnsError() error { + if bad() { + return ErrBad + } + return nil } </pre> +<p> +It's a good idea for functions +that return errors always to use the <code>error</code> type in +their signature (as we did above) rather than a concrete type such +as <code>*MyError</code>, to help guarantee the error is +created correctly. As an example, +<a href="/pkg/os/#Open"><code>os.Open</code></a> +returns an <code>error</code> even though, if not <code>nil</code>, +it's always of concrete type +<a href="/pkg/os/#PathError"><code>*os.PathError</code></a>. +</p> + +<p> +Similar situations to those described here can arise whenever interfaces are used. +Just keep in mind that if any concrete value +has been stored in the interface, the interface will not be <code>nil</code>. +For more information, see +<a href="/doc/articles/laws_of_reflection.html">The Laws of Reflection</a>. +</p> + + <h3 id="unions"> Why are there no untagged unions, as in C?</h3> @@ -768,15 +818,20 @@ to write one but it will not be as convenient syntactically; this seems a reason </p> <h3 id="map_keys"> -Why don't maps allow structs and arrays as keys?</h3> +Why don't maps allow slices as keys?</h3> <p> -Map lookup requires an equality operator, which structs and arrays do not implement. +Map lookup requires an equality operator, which slices do not implement. They don't implement equality because equality is not well defined on such types; there are multiple considerations involving shallow vs. deep comparison, pointer vs. -value comparison, how to deal with recursive structures, and so on. -We may revisit this issue—and implementing equality for structs and arrays +value comparison, how to deal with recursive types, and so on. +We may revisit this issue—and implementing equality for slices will not invalidate any existing programs—but without a clear idea of what -equality of structs and arrays should mean, it was simpler to leave it out for now. +equality of slices should mean, it was simpler to leave it out for now. +</p> + +<p> +In Go 1, unlike prior releases, equality is defined for structs and arrays, so such +types can be used as map keys. Slices still do not have a definition of equality, though. </p> <h3 id="references"> @@ -841,14 +896,17 @@ for more information about how to proceed. When are function parameters passed by value?</h3> <p> -Everything in Go is passed by value. A function always gets a copy of the +As in all languages in the C family, everything in Go is passed by value. +That is, a function always gets a copy of the thing being passed, as if there were an assignment statement assigning the -value to the parameter. For instance, copying a pointer value makes a copy of -the pointer, not the data it points to. +value to the parameter. For instance, passing an <code>int</code> value +to a function makes a copy of the <code>int</code>, and passing a pointer +value makes a copy of the pointer, but not the data it points to. +(See the next section for a discussion of how this affects method receivers.) </p> <p> -Map and slice values behave like pointers; they are descriptors that +Map and slice values behave like pointers: they are descriptors that contain pointers to the underlying map or slice data. Copying a map or slice value doesn't copy the data it points to. Copying an interface value makes a copy of the thing stored in the interface value. If the interface @@ -869,7 +927,7 @@ func (s MyStruct) valueMethod() { } // method on value For programmers unaccustomed to pointers, the distinction between these two examples can be confusing, but the situation is actually very simple. When defining a method on a type, the receiver (<code>s</code> in the above -example) behaves exactly as if it were an argument to the method. +examples) behaves exactly as if it were an argument to the method. Whether to define the receiver as a value or as a pointer is the same question, then, as whether a function argument should be a value or a pointer. @@ -936,7 +994,7 @@ Why is <code>int</code> 32 bits on 64 bit machines?</h3> <p> The sizes of <code>int</code> and <code>uint</code> are implementation-specific but the same as each other on a given platform. -The 64 bit Go compilers (both 6g and gccgo) use a 32 bit representation for +The 64 bit Go compilers (both gc and gccgo) use a 32 bit representation for <code>int</code>. Code that relies on a particular size of value should use an explicitly sized type, like <code>int64</code>. On the other hand, floating-point scalars and complex @@ -946,6 +1004,12 @@ floating-point numbers. The default size of a floating-point constant is <code>float64</code>. </p> +<p> +At the moment, all implementations use 32-bit ints, an essentially arbitrary decision. +However, we expect that <code>int</code> will be increased to 64 bits on 64-bit +architectures in a future release of Go. +</p> + <h3 id="stack_or_heap"> How do I know whether a variable is allocated on the heap or the stack?</h3> @@ -963,12 +1027,15 @@ local to a function in that function's stack frame. However, if the compiler cannot prove that the variable is not referenced after the function returns, then the compiler must allocate the variable on the garbage-collected heap to avoid dangling pointer errors. +Also, if a local variable is very large, it might make more sense +to store it on the heap rather than the stack. </p> <p> -In the current compilers, the analysis is crude: if a variable has its address -taken, that variable is allocated on the heap. We are working to improve this -analysis so that more data is kept on the stack. +In the current compilers, if a variable has its address taken, that variable +is a candidate for allocation on the heap. However, a basic <em>escape +analysis</em> recognizes some cases when such variables will not +live past the return from the function and can reside on the stack. </p> <h2 id="Concurrency">Concurrency</h2> @@ -978,7 +1045,7 @@ What operations are atomic? What about mutexes?</h3> <p> We haven't fully defined it all yet, but some details about atomicity are -available in the <a href="go_mem.html">Go Memory Model specification</a>. +available in the <a href="/ref/mem">Go Memory Model specification</a>. </p> <p> @@ -1001,17 +1068,15 @@ See the <a href="/doc/codewalk/sharemem/">Share Memory By Communicating</a> code Why doesn't my multi-goroutine program use multiple CPUs?</h3> <p> -Under the gc compilers you must set <code>GOMAXPROCS</code> to allow the -run-time support to utilise more than one OS thread. Under <code>gccgo</code> an OS -thread will be created for each goroutine, and <code>GOMAXPROCS</code> is -effectively equal to the number of running goroutines. +You must set the <code>GOMAXPROCS</code> shell environment variable +or use the similarly-named <a href="/pkg/runtime/#GOMAXPROCS"><code>function</code></a> +of the runtime package to allow the +run-time support to utilize more than one OS thread. </p> <p> -Programs that perform concurrent computation should benefit from an increase in -<code>GOMAXPROCS</code>. (See the <a -href="http://golang.org/pkg/runtime/#GOMAXPROCS"><code>runtime</code> package's -documentation</a>.) +Programs that perform parallel computation should benefit from an increase in +<code>GOMAXPROCS</code>. </p> <h3 id="Why_GOMAXPROCS"> @@ -1019,15 +1084,24 @@ Why does using <code>GOMAXPROCS</code> > 1 sometimes make my program slower?</h3> <p> -(This is specific to the gc compilers. See above.) +It depends on the nature of your program. +Problems that are intrinsically sequential cannot be sped up by adding +more goroutines. +Concurrency only becomes parallelism when the problem is +intrinsically parallel. </p> <p> -It depends on the nature of your program. -Programs that contain several goroutines that spend a lot of time -communicating on channels will experience performance degradation when using -multiple OS threads. This is because of the significant context-switching -penalty involved in sending data between threads. +In practical terms, programs that spend more time +communicating on channels than doing computation +will experience performance degradation when using +multiple OS threads. +This is because sending data between threads involves switching +contexts, which has significant cost. +For instance, the <a href="/ref/spec#An_example_package">prime sieve example</a> +from the Go specification has no significant parallelism although it launches many +goroutines; increasing <code>GOMAXPROCS</code> is more likely to slow it down than +to speed it up. </p> <p> @@ -1042,7 +1116,7 @@ should recognize such cases and optimize its use of OS threads. For now, Why do T and *T have different method sets?</h3> <p> -From the <a href="http://golang.org/doc/go_spec.html#Types">Go Spec</a>: +From the <a href="/ref/spec#Types">Go Spec</a>: </p> <blockquote> @@ -1060,7 +1134,10 @@ there is no useful way for a method call to obtain a pointer. </p> <p> -If not for this restriction, this code: +Even in cases where the compiler could take the address of a value +to pass to the method, if the method modifies the value the changes +will be lost in the caller. +As a common example, this code: </p> <pre> @@ -1075,7 +1152,7 @@ This is almost never the desired behavior. </p> <h3 id="closures_and_goroutines"> -Why am I confused by the way my closures behave as goroutines?</h3> +What happens with closures running as goroutines?</h3> <p> Some confusion may arise when using closures with concurrency. @@ -1084,29 +1161,30 @@ Consider the following program: <pre> func main() { - done := make(chan bool) - - values := []string{ "a", "b", "c" } - for _, v := range values { - go func() { - fmt.Println(v) - done <- true - }() - } - - // wait for all goroutines to complete before exiting - for _ = range values { - <-done - } + done := make(chan bool) + + values := []string{"a", "b", "c"} + for _, v := range values { + go func() { + fmt.Println(v) + done <- true + }() + } + + // wait for all goroutines to complete before exiting + for _ = range values { + <-done + } } </pre> <p> One might mistakenly expect to see <code>a, b, c</code> as the output. What you'll probably see instead is <code>c, c, c</code>. This is because -each closure shares the same variable <code>v</code>. Each closure prints the -value of <code>v</code> at the time <code>fmt.Println</code> is executed, -rather than the value of <code>v</code> when the goroutine was launched. +each iteration of the loop uses the same instance of the variable <code>v</code>, so +each closure shares that single variable. When the closure runs, it prints the +value of <code>v</code> at the time <code>fmt.Println</code> is executed, +but <code>v</code> may have been modified since the goroutine was launched. </p> <p> @@ -1115,12 +1193,12 @@ could modify the inner loop to read: </p> <pre> - for _, v := range values { - go func(<b>u</b> string) { - fmt.Println(<b>u</b>) - done <- true - }(<b>v</b>) - } + for _, v := range values { + go func(<b>u</b> string) { + fmt.Println(<b>u</b>) + done <- true + }(<b>v</b>) + } </pre> <p> @@ -1141,9 +1219,9 @@ result: <pre> if expr { - n = trueVal + n = trueVal } else { - n = falseVal + n = falseVal } </pre> @@ -1179,12 +1257,53 @@ func TestFoo(t *testing.T) { </pre> <p> -Run <code>gotest</code> in that directory. +Run <code>go test</code> in that directory. That script finds the <code>Test</code> functions, builds a test binary, and runs it. </p> -<p>See the <a href="/doc/code.html">How to Write Go Code</a> document for more details.</p> +<p>See the <a href="/doc/code.html">How to Write Go Code</a> document, +the <a href="/pkg/testing/"><code>testing</code></a> package +and the <a href="/cmd/go/#Test_packages"><code>go test</code></a> subcommand for more details. +</p> + +<h3 id="testing_framework"> +Where is my favorite helper function for testing?</h3> + +<p> +Go's standard <a href="/pkg/testing/"><code>testing</code></a> package makes it easy to write unit tests, but it lacks +features provided in other language's testing frameworks such as assertion functions. +An <a href="#assertions">earlier section</a> of this document explained why Go +doesn't have assertions, and +the same arguments apply to the use of <code>assert</code> in tests. +Proper error handling means letting other tests run after one has failed, so +that the person debugging the failure gets a complete picture of what is +wrong. It is more useful for a test to report that +<code>isPrime</code> gives the wrong answer for 2, 3, 5, and 7 (or for +2, 4, 8, and 16) than to report that <code>isPrime</code> gives the wrong +answer for 2 and therefore no more tests were run. The programmer who +triggers the test failure may not be familiar with the code that fails. +Time invested writing a good error message now pays off later when the +test breaks. +</p> + +<p> +A related point is that testing frameworks tend to develop into mini-languages +of their own, with conditionals and controls and printing mechanisms, +but Go already has all those capabilities; why recreate them? +We'd rather write tests in Go; it's one fewer language to learn and the +approach keeps the tests straightforward and easy to understand. +</p> + +<p> +If the amount of extra code required to write +good errors seems repetitive and overwhelming, the test might work better if +table-driven, iterating over a list of inputs and outputs defined +in a data structure (Go has excellent support for data structure literals). +The work to write a good test and good error messages will then be amortized over many +test cases. The standard Go library is full of illustrative examples, such as in +<a href="/src/pkg/fmt/fmt_test.go">the formatting tests for the <code>fmt</code> package</a>. +</p> <h2 id="Implementation">Implementation</h2> @@ -1198,21 +1317,21 @@ 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 (<a href="http://plan9.bell-labs.com/sys/doc/compiler.html">http://plan9.bell-labs.com/sys/doc/compiler.html</a>) -and uses a variant of the Plan 9 loader to generate ELF binaries. +and uses a variant of the Plan 9 loader to generate ELF/Mach-O/PE binaries. </p> <p> -We considered writing <code>6g</code>, the original Go compiler, in Go itself but +We considered writing <code>gc</code>, the original Go compiler, in Go itself but elected not to do so because of the difficulties of bootstrapping and especially of open source distribution—you'd need a Go compiler to set up a Go environment. <code>Gccgo</code>, which came later, makes it possible to consider writing a compiler in Go, which might well happen. (Go would be a fine language in which to implement a compiler; a native lexer and -parser are already available in <a href="/pkg/go/"><code>/pkg/go</code></a>.) +parser are already available in the <a href="/pkg/go/"><code>go</code></a> package.) </p> <p> -We also considered using LLVM for <code>6g</code> but we felt it was too large and +We also considered using LLVM for <code>gc</code> but we felt it was too large and slow to meet our performance goals. </p> @@ -1227,25 +1346,27 @@ it now. <code>Gccgo</code>'s run-time support uses <code>glibc</code>. control; it is compiled with a version of the Plan 9 C compiler that supports segmented stacks for goroutines. -Work is underway to provide the same stack management in -<code>gccgo</code>. +The <code>gccgo</code> compiler implements segmented +stacks on Linux only, supported by recent modifications to the gold linker. </p> <h3 id="Why_is_my_trivial_program_such_a_large_binary"> Why is my trivial program such a large binary?</h3> <p> -The gc tool chain (<code>5l</code>, <code>6l</code>, and <code>8l</code>) only -generate statically linked binaries. All Go binaries therefore include the Go +The linkers in the gc tool chain (<code>5l</code>, <code>6l</code>, and <code>8l</code>) +do static linking. All Go binaries therefore include the Go run-time, along with the run-time type information necessary to support dynamic type checks, reflection, and even panic-time stack traces. </p> <p> -A trivial C "hello, world" program compiled and linked statically using gcc -on Linux is around 750 kB. An equivalent Go program is around 1.1 MB, but -that includes more powerful run-time support. We believe that with some effort -the size of Go binaries can be reduced. +A simple C "hello, world" program compiled and linked statically using gcc +on Linux is around 750 kB, +including an implementation of <code>printf</code>. +An equivalent Go program using <code>fmt.Printf</code> +is around 1.2 MB, but +that includes more powerful run-time support. </p> <h3 id="unused_variables_and_imports"> @@ -1296,9 +1417,9 @@ import "unused" var _ = unused.Item // TODO: Delete before committing! func main() { - debugData := debug.Profile() - _ = debugData // Used only during debugging. - .... + debugData := debug.Profile() + _ = debugData // Used only during debugging. + .... } </pre> @@ -1310,20 +1431,23 @@ Why does Go perform badly on benchmark X?</h3> <p> One of Go's design goals is to approach the performance of C for comparable programs, yet on some benchmarks it does quite poorly, including several -in <a href="/test/bench/">test/bench</a>. The slowest depend on libraries +in <a href="/test/bench/shootout/">test/bench/shootout</a>. The slowest depend on libraries for which versions of comparable performance are not available in Go. -For instance, pidigits depends on a multi-precision math package, and the C +For instance, <a href="/test/bench/shootout/pidigits.go">pidigits.go</a> +depends on a multi-precision math package, and the C versions, unlike Go's, use <a href="http://gmplib.org/">GMP</a> (which is written in optimized assembler). -Benchmarks that depend on regular expressions (regex-dna, for instance) are -essentially comparing Go's stopgap <a href="/pkg/regexp">regexp package</a> to +Benchmarks that depend on regular expressions +(<a href="/test/bench/shootout/regex-dna.go">regex-dna.go</a>, for instance) are +essentially comparing Go's native <a href="/pkg/regexp">regexp package</a> to mature, highly optimized regular expression libraries like PCRE. </p> <p> Benchmark games are won by extensive tuning and the Go versions of most of the benchmarks need attention. If you measure comparable C -and Go programs (reverse-complement is one example), you'll see the two +and Go programs +(<a href="/test/bench/shootout/reverse-complement.go">reverse-complement.go</a> is one example), you'll see the two languages are much closer in raw performance than this suite would indicate. </p> @@ -1331,12 +1455,15 @@ indicate. <p> Still, there is room for improvement. The compilers are good but could be better, many libraries need major performance work, and the garbage collector -isn't fast enough yet (even if it were, taking care not to generate unnecessary -garbage can have a huge effect). +isn't fast enough yet. (Even if it were, taking care not to generate unnecessary +garbage can have a huge effect.) </p> <p> -In any case, Go can often be very competitive. See the blog post about +In any case, Go can often be very competitive. +There has been significant improvement in the performance of many programs +as the language and tools have developed. +See the blog post about <a href="http://blog.golang.org/2011/06/profiling-go-programs.html">profiling Go programs</a> for an informative example. @@ -1367,13 +1494,13 @@ prefix <code>*</code> for pointers is an exception that proves the rule). In C, the declaration </p> <pre> - int* a, b; + int* a, b; </pre> <p> declares <code>a</code> to be a pointer but not <code>b</code>; in Go </p> <pre> - var a, b *int; + var a, b *int </pre> <p> declares both to be pointers. This is clearer and more regular. @@ -1381,11 +1508,13 @@ Also, the <code>:=</code> short declaration form argues that a full variable declaration should present the same order as <code>:=</code> so </p> <pre> - var a uint64 = 1; + var a uint64 = 1 </pre> +<p> has the same effect as +</p> <pre> - a := uint64(1); + a := uint64(1) </pre> <p> Parsing is also simplified by having a distinct grammar for types that @@ -1395,7 +1524,7 @@ and <code>chan</code> keep things clear. <p> See the article about -<a href="http://blog.golang.org/2010/07/gos-declaration-syntax.html">Go's Declaration Syntax</a> +<a href="/doc/articles/gos_declaration_syntax.html">Go's Declaration Syntax</a> for more details. </p> @@ -1445,7 +1574,7 @@ appear on a line by itself. Some have argued that the lexer should do lookahead to permit the brace to live on the next line. We disagree. Since Go code is meant to be formatted automatically by -<a href="http://golang.org/cmd/gofmt/"><code>gofmt</code></a>, +<a href="/cmd/gofmt/"><code>gofmt</code></a>, <i>some</i> style must be chosen. That style may differ from what you've used in C or Java, but Go is a new language and <code>gofmt</code>'s style is as good as any other. More @@ -1464,8 +1593,7 @@ memory management. We feel it's critical to eliminate that programmer overhead, and advances in garbage collection technology in the last few years give us confidence that we can implement it with low enough overhead and no significant -latency. (The current implementation is a plain mark-and-sweep -collector but a replacement is in the works.) +latency. </p> <p> @@ -1485,6 +1613,11 @@ simpler because they don't need to specify how memory is managed across them. </p> <p> +The current implementation is a parallel mark-and-sweep +collector but a future version might take a different approach. +</p> + +<p> On the topic of performance, keep in mind that Go gives the programmer considerable control over memory layout and allocation, much more than is typical in garbage-collected languages. A careful programmer can reduce diff --git a/doc/go_for_cpp_programmers.html b/doc/go_for_cpp_programmers.html deleted file mode 100644 index 7168f1d05..000000000 --- a/doc/go_for_cpp_programmers.html +++ /dev/null @@ -1,707 +0,0 @@ -<!-- Go For C++ Programmers --> - -<p> -Go is a systems programming language intended to be a general-purpose -systems language, like C++. -These are some notes on Go for experienced C++ programmers. This -document discusses the differences between Go and C++, and says little -to nothing about the similarities. - -<p> -For a more general introduction to Go, see the -<a href="go_tutorial.html">Go tutorial</a> and -<a href="effective_go.html">Effective Go</a>. - -<p> -For a detailed description of the Go language, see the -<a href="go_spec.html">Go spec</a>. - -<h2 id="Conceptual_Differences">Conceptual Differences</h2> - -<ul> -<li>Go does not have classes with constructors or destructors. - Instead of class methods, a class inheritance hierarchy, - and virtual functions, Go provides <em>interfaces</em>, which are - <a href="#Interfaces">discussed in more detail below</a>. - Interfaces are also used where C++ uses templates. - -<li>Go uses garbage collection. It is not necessary (or possible) - to release memory explicitly. The garbage collection is (intended to be) - incremental and highly efficient on modern processors. - -<li>Go has pointers but not pointer arithmetic. You cannot - use a pointer variable to walk through the bytes of a string. - -<li>Arrays in Go are first class values. When an array is used as a - function parameter, the function receives a copy of the array, not - a pointer to it. However, in practice functions often use slices - for parameters; slices hold pointers to underlying arrays. Slices - are <a href="#Slices">discussed further below</a>. - -<li>Strings are provided by the language. They may not be changed once they - have been created. - -<li>Hash tables are provided by the language. They are called maps. - -<li>Separate threads of execution, and communication channels between - them, are provided by the language. This - is <a href="#Goroutines">discussed further below</a>. - -<li>Certain types (maps and channels, described further below) - are passed by reference, not by value. That is, passing a map to a - function does not copy the map, and if the function changes the map - the change will be seen by the caller. In C++ terms, one can - think of these as being reference types. - -<li>Go does not use header files. Instead, each source file is part of a - defined <em>package</em>. When a package defines an object - (type, constant, variable, function) with a name starting with an - upper case letter, that object is visible to any other file which - imports that package. - -<li>Go does not support implicit type conversion. Operations that mix - different types require casts (called conversions in Go). - -<li>Go does not support function overloading and does not support user - defined operators. - -<li>Go does not support <code>const</code> or <code>volatile</code> qualifiers. - -<li>Go uses <code>nil</code> for invalid pointers, where C++ uses - <code>NULL</code> or simply <code>0</code>. -</ul> - -<h2 id="Syntax">Syntax</h2> - -<p> -The declaration syntax is reversed compared to C++. You write the name -followed by the type. Unlike in C++, the syntax for a type does not match -the way in which the variable is used. Type declarations may be read -easily from left to right. - -<pre> -<b>Go C++</b> -var v1 int // int v1; -var v2 string // const std::string v2; (approximately) -var v3 [10]int // int v3[10]; -var v4 []int // int* v4; (approximately) -var v5 struct { f int } // struct { int f; } v5; -var v6 *int // int* v6; (but no pointer arithmetic) -var v7 map[string]int // unordered_map<string, int>* v7; (approximately) -var v8 func(a int) int // int (*v8)(int a); -</pre> - -<p> -Declarations generally take the form of a keyword followed by the name -of the object being declared. The keyword is one of <code>var</code>, -<code>func</code>, -<code>const</code>, or <code>type</code>. Method declarations are a minor -exception in that -the receiver appears before the name of the object being declared; see -the <a href="#Interfaces">discussion of interfaces</a>. - -<p> -You can also use a keyword followed by a series of declarations in -parentheses. - -<pre> -var ( - i int - m float64 -) -</pre> - -<p> -When declaring a function, you must either provide a name for each parameter -or not provide a name for any parameter; you can't omit some names -and provide others. You may group several names with the same type: - -<pre> -func f(i, j, k int, s, t string) -</pre> - -<p> -A variable may be initialized when it is declared. When this is done, -specifying the type is permitted but not required. When the type is -not specified, the type of the variable is the type of the -initialization expression. - -<pre> -var v = *p -</pre> - -<p> -See also the <a href="#Constants">discussion of constants, below</a>. -If a variable is not initialized explicitly, the type must be specified. -In that case it will be -implicitly initialized to the type's zero value (0, nil, etc.). There are no -uninitialized variables in Go. - -<p> -Within a function, a short declaration syntax is available with -<code>:=</code> . - -<pre> -v1 := v2 -</pre> - -<p> -This is equivalent to - -<pre> -var v1 = v2 -</pre> - -<p> -Go permits multiple assignments, which are done in parallel. - -<pre> -i, j = j, i // Swap i and j. -</pre> - -<p> -Functions may have multiple return values, indicated by a list in -parentheses. The returned values can be stored by assignment -to a list of variables. - -<pre> -func f() (i int, j int) { ... } -v1, v2 = f() -</pre> - -<p> -Go code uses very few semicolons in practice. Technically, all Go -statements are terminated by a semicolon. However, Go treats the end -of a non-blank line as a semicolon unless the line is clearly -incomplete (the exact rules are -in <a href="go_spec.html#Semicolons">the language specification</a>). -A consequence of this is that in some cases Go does not permit you to -use a line break. For example, you may not write -<pre> -func g() -{ // INVALID -} -</pre> -A semicolon will be inserted after <code>g()</code>, causing it to be -a function declaration rather than a function definition. Similarly, -you may not write -<pre> -if x { -} -else { // INVALID -} -</pre> -A semicolon will be inserted after the <code>}</code> preceding -the <code>else</code>, causing a syntax error. - -<p> -Since semicolons do end statements, you may continue using them as in -C++. However, that is not the recommended style. Idiomatic Go code -omits unnecessary semicolons, which in practice is all of them other -than the initial <code>for</code> loop clause and cases where you want several -short statements on a single line. - -<p> -While we're on the topic, we recommend that rather than worry about -semicolons and brace placement, you format your code with -the <code>gofmt</code> program. That will produce a single standard -Go style, and let you worry about your code rather than your -formatting. While the style may initially seem odd, it is as good as -any other style, and familiarity will lead to comfort. - -<p> -When using a pointer to a struct, you use <code>.</code> instead -of <code>-></code>. -Thus syntactically speaking a structure and a pointer to a structure -are used in the same way. - -<pre> -type myStruct struct { i int } -var v9 myStruct // v9 has structure type -var p9 *myStruct // p9 is a pointer to a structure -f(v9.i, p9.i) -</pre> - -<p> -Go does not require parentheses around the condition of a <code>if</code> -statement, or the expressions of a <code>for</code> statement, or the value of a -<code>switch</code> statement. On the other hand, it does require curly braces -around the body of an <code>if</code> or <code>for</code> statement. - -<pre> -if a < b { f() } // Valid -if (a < b) { f() } // Valid (condition is a parenthesized expression) -if (a < b) f() // INVALID -for i = 0; i < 10; i++ {} // Valid -for (i = 0; i < 10; i++) {} // INVALID -</pre> - -<p> -Go does not have a <code>while</code> statement nor does it have a -<code>do/while</code> -statement. The <code>for</code> statement may be used with a single condition, -which makes it equivalent to a <code>while</code> statement. Omitting the -condition entirely is an endless loop. - -<p> -Go permits <code>break</code> and <code>continue</code> to specify a label. -The label must -refer to a <code>for</code>, <code>switch</code>, or <code>select</code> -statement. - -<p> -In a <code>switch</code> statement, <code>case</code> labels do not fall -through. You can -make them fall through using the <code>fallthrough</code> keyword. This applies -even to adjacent cases. - -<pre> -switch i { -case 0: // empty case body -case 1: - f() // f is not called when i == 0! -} -</pre> - -<p> -But a <code>case</code> can have multiple values. - -<pre> -switch i { -case 0, 1: - f() // f is called if i == 0 || i == 1. -} -</pre> - -<p> -The values in a <code>case</code> need not be constants—or even integers; -any type -that supports the equality comparison operator, such as strings or -pointers, can be used—and if the <code>switch</code> -value is omitted it defaults to <code>true</code>. - -<pre> -switch { -case i < 0: - f1() -case i == 0: - f2() -case i > 0: - f3() -} -</pre> - -<p> -The <code>++</code> and <code>--</code> operators may only be used in -statements, not in expressions. -You cannot write <code>c = *p++</code>. <code>*p++</code> is parsed as -<code>(*p)++</code>. - -<p> -The <code>defer</code> statement may be used to call a function after -the function containing the <code>defer</code> statement returns. - -<pre> -fd := open("filename") -defer close(fd) // fd will be closed when this function returns. -</pre> - -<h2 id="Constants">Constants </h2> - -<p> -In Go constants may be <i>untyped</i>. This applies even to constants -named with a <code>const</code> declaration, if no -type is given in the declaration and the initializer expression uses only -untyped constants. -A value derived from an untyped constant becomes typed when it -is used within a context that -requires a typed value. This permits constants to be used relatively -freely without requiring general implicit type conversion. - -<pre> -var a uint -f(a + 1) // untyped numeric constant "1" becomes typed as uint -</pre> - -<p> -The language does not impose any limits on the size of an untyped -numeric constant or constant expression. A limit is only applied when -a constant is used where a type is required. - -<pre> -const huge = 1 << 100 -f(huge >> 98) -</pre> - -<p> -Go does not support enums. Instead, you can use the special name -<code>iota</code> in a single <code>const</code> declaration to get a -series of increasing -value. When an initialization expression is omitted for a <code>const</code>, -it reuses the preceding expression. - -<pre> -const ( - red = iota // red == 0 - blue // blue == 1 - green // green == 2 -) -</pre> - -<h2 id="Slices">Slices</h2> - -<p> -A slice is conceptually a struct with three fields: a -pointer to an array, a length, and a capacity. -Slices support -the <code>[]</code> operator to access elements of the underlying array. -The builtin -<code>len</code> function returns the -length of the slice. The builtin <code>cap</code> function returns the -capacity. - -<p> -Given an array, or another slice, a new slice is created via -<code>a[I:J]</code>. This -creates a new slice which refers to <code>a</code>, starts at -index <code>I</code>, and ends before index -<code>J</code>. It has length <code>J - I</code>. -The new slice refers to the same array -to which <code>a</code> -refers. That is, changes made using the new slice may be seen using -<code>a</code>. The -capacity of the new slice is simply the capacity of <code>a</code> minus -<code>I</code>. The capacity -of an array is the length of the array. You may also assign an array pointer -to a variable of slice type; given <code>var s []int; var a[10] int</code>, -the assignment <code>s = &a</code> is equivalent to -<code>s = a[0:len(a)]</code>. - -<p> -What this means is that Go uses slices for some cases where C++ uses pointers. -If you create a value of type <code>[100]byte</code> (an array of 100 bytes, -perhaps a -buffer) and you want to pass it to a function without copying it, you should -declare the function parameter to have type <code>[]byte</code>, and pass the -address -of the array. Unlike in C++, it is not -necessary to pass the length of the buffer; it is efficiently accessible via -<code>len</code>. - -<p> -The slice syntax may also be used with a string. It returns a new string, -whose value is a substring of the original string. -Because strings are immutable, string slices can be implemented -without allocating new storage for the slices's contents. - -<h2 id="Making_values">Making values</h2> - -<p> -Go has a builtin function <code>new</code> which takes a type and -allocates space -on the heap. The allocated space will be zero-initialized for the type. -For example, <code>new(int)</code> allocates a new int on the heap, -initializes it with the value <code>0</code>, -and returns its address, which has type <code>*int</code>. -Unlike in C++, <code>new</code> is a function, not an operator; -<code>new int</code> is a syntax error. - -<p> -Map and channel values must be allocated using the builtin function -<code>make</code>. -A variable declared with map or channel type without an initializer will be -automatically initialized to <code>nil</code>. -Calling <code>make(map[int]int)</code> returns a newly allocated value of -type <code>map[int]int</code>. -Note that <code>make</code> returns a value, not a pointer. This is -consistent with -the fact that map and channel values are passed by reference. Calling -<code>make</code> with -a map type takes an optional argument which is the expected capacity of the -map. Calling <code>make</code> with a channel type takes an optional -argument which sets the -buffering capacity of the channel; the default is 0 (unbuffered). - -<p> -The <code>make</code> function may also be used to allocate a slice. -In this case it -allocates memory for the underlying array and returns a slice referring to it. -There is one required argument, which is the number of elements in the slice. -A second, optional, argument is the capacity of the slice. For example, -<code>make([]int, 10, 20)</code>. This is identical to -<code>new([20]int)[0:10]</code>. Since -Go uses garbage collection, the newly allocated array will be discarded -sometime after there are no references to the returned slice. - -<h2 id="Interfaces">Interfaces</h2> - -<p> -Where C++ provides classes, subclasses and templates, -Go provides interfaces. A -Go interface is similar to a C++ pure abstract class: a class with no -data members, with methods which are all pure virtual. However, in -Go, any type which provides the methods named in the interface may be -treated as an implementation of the interface. No explicitly declared -inheritance is required. The implementation of the interface is -entirely separate from the interface itself. - -<p> -A method looks like an ordinary function definition, except that it -has a <em>receiver</em>. The receiver is similar to -the <code>this</code> pointer in a C++ class method. - -<pre> -type myType struct { i int } -func (p *myType) get() int { return p.i } -</pre> - -<p> -This declares a method <code>get</code> associated with <code>myType</code>. -The receiver is named <code>p</code> in the body of the function. - -<p> -Methods are defined on named types. If you convert the value -to a different type, the new value will have the methods of the new type, -not the old type. - -<p> -You may define methods on a builtin type by declaring a new named type -derived from it. The new type is distinct from the builtin type. - -<pre> -type myInteger int -func (p myInteger) get() int { return int(p) } // Conversion required. -func f(i int) { } -var v myInteger -// f(v) is invalid. -// f(int(v)) is valid; int(v) has no defined methods. -</pre> - -<p> -Given this interface: - -<pre> -type myInterface interface { - get() int - set(i int) -} -</pre> - -<p> -we can make <code>myType</code> satisfy the interface by adding - -<pre> -func (p *myType) set(i int) { p.i = i } -</pre> - -<p> -Now any function which takes <code>myInterface</code> as a parameter -will accept a -variable of type <code>*myType</code>. - -<pre> -func getAndSet(x myInterface) {} -func f1() { - var p myType - getAndSet(&p) -} -</pre> - -<p> -In other words, if we view <code>myInterface</code> as a C++ pure abstract -base -class, defining <code>set</code> and <code>get</code> for -<code>*myType</code> made <code>*myType</code> automatically -inherit from <code>myInterface</code>. A type may satisfy multiple interfaces. - -<p> -An anonymous field may be used to implement something much like a C++ child -class. - -<pre> -type myChildType struct { myType; j int } -func (p *myChildType) get() int { p.j++; return p.myType.get() } -</pre> - -<p> -This effectively implements <code>myChildType</code> as a child of -<code>myType</code>. - -<pre> -func f2() { - var p myChildType - getAndSet(&p) -} -</pre> - -<p> -The <code>set</code> method is effectively inherited from -<code>myChildType</code>, because -methods associated with the anonymous field are promoted to become methods -of the enclosing type. In this case, because <code>myChildType</code> has an -anonymous field of type <code>myType</code>, the methods of -<code>myType</code> also become methods of <code>myChildType</code>. -In this example, the <code>get</code> method was -overridden, and the <code>set</code> method was inherited. - -<p> -This is not precisely the same as a child class in C++. -When a method of an anonymous field is called, -its receiver is the field, not the surrounding struct. -In other words, methods on anonymous fields are not virtual functions. -When you want the equivalent of a virtual function, use an interface. - -<p> -A variable which has an interface type may be converted to have a -different interface type using a special construct called a type assertion. -This is implemented dynamically -at run time, like C++ <code>dynamic_cast</code>. Unlike -<code>dynamic_cast</code>, there does -not need to be any declared relationship between the two interfaces. - -<pre> -type myPrintInterface interface { - print() -} -func f3(x myInterface) { - x.(myPrintInterface).print() // type assertion to myPrintInterface -} -</pre> - -<p> -The conversion to <code>myPrintInterface</code> is entirely dynamic. -It will -work as long as the underlying type of x (the <em>dynamic type</em>) defines -a <code>print</code> method. - -<p> -Because the conversion is dynamic, it may be used to implement generic -programming similar to templates in C++. This is done by -manipulating values of the minimal interface. - -<pre> -type Any interface { } -</pre> - -<p> -Containers may be written in terms of <code>Any</code>, but the caller -must unbox using a type assertion to recover -values of the contained type. As the typing is dynamic rather -than static, there is no equivalent of the way that a C++ template may -inline the relevant operations. The operations are fully type-checked -at run time, but all operations will involve a function call. - -<pre> -type iterator interface { - get() Any - set(v Any) - increment() - equal(arg *iterator) bool -} -</pre> - -<h2 id="Goroutines">Goroutines</h2> - -<p> -Go permits starting a new thread of execution (a <em>goroutine</em>) -using the <code>go</code> -statement. The <code>go</code> statement runs a function in a -different, newly created, goroutine. -All goroutines in a single program share the same address space. - -<p> -Internally, goroutines act like coroutines that are multiplexed among -multiple operating system threads. You do not have to worry -about these details. - -<pre> -func server(i int) { - for { - print(i) - sys.sleep(10) - } -} -go server(1) -go server(2) -</pre> - -<p> -(Note that the <code>for</code> statement in the <code>server</code> -function is equivalent to a C++ <code>while (true)</code> loop.) - -<p> -Goroutines are (intended to be) cheap. - -<p> -Function literals (which Go implements as closures) -can be useful with the <code>go</code> statement. - -<pre> -var g int -go func(i int) { - s := 0 - for j := 0; j < i; j++ { s += j } - g = s -}(1000) // Passes argument 1000 to the function literal. -</pre> - -<h2 id="Channels">Channels</h2> - -<p> -Channels are used to communicate between goroutines. Any value may be -sent over a channel. Channels are (intended to be) efficient and -cheap. To send a value on a channel, use <code><-</code> as a binary -operator. To -receive a value on a channel, use <code><-</code> as a unary operator. -When calling -functions, channels are passed by reference. - -<p> -The Go library provides mutexes, but you can also use -a single goroutine with a shared channel. -Here is an example of using a manager function to control access to a -single value. - -<pre> -type cmd struct { get bool; val int } -func manager(ch chan cmd) { - var val int = 0 - for { - c := <- ch - if c.get { c.val = val; ch <- c } - else { val = c.val } - } -} -</pre> - -<p> -In that example the same channel is used for input and output. -This is incorrect if there are multiple goroutines communicating -with the manager at once: a goroutine waiting for a response -from the manager might receive a request from another goroutine -instead. -A solution is to pass in a channel. - -<pre> -type cmd2 struct { get bool; val int; ch <- chan int } -func manager2(ch chan cmd2) { - var val int = 0 - for { - c := <- ch - if c.get { c.ch <- val } - else { val = c.val } - } -} -</pre> - -<p> -To use <code>manager2</code>, given a channel to it: - -<pre> -func f4(ch <- chan cmd2) int { - myCh := make(chan int) - c := cmd2{ true, 0, myCh } // Composite literal syntax. - ch <- c - return <-myCh -} -</pre> diff --git a/doc/go_mem.html b/doc/go_mem.html index a38828358..ece230638 100644 --- a/doc/go_mem.html +++ b/doc/go_mem.html @@ -1,5 +1,8 @@ -<!-- The Go Memory Model --> -<!-- subtitle Version of June 10, 2011 --> +<!--{ + "Title": "The Go Memory Model", + "Subtitle": "Version of March 6, 2012", + "Path": "/ref/mem" +}--> <style> p.rule { @@ -54,7 +57,7 @@ if both of the following hold: </p> <ol> -<li><span class="event">w</span> happens before <span class="event">r</span>.</li> +<li><span class="event">r</span> does not happen before <span class="event">w</span>.</li> <li>There is no other write <span class="event">w'</span> to <code>v</code> that happens after <span class="event">w</span> but before <span class="event">r</span>.</li> </ol> @@ -104,9 +107,9 @@ unspecified order. <h3>Initialization</h3> <p> -Program initialization runs in a single goroutine and -new goroutines created during initialization do not -start running until initialization ends. +Program initialization runs in a single goroutine, +but that goroutine may create other goroutines, +which run concurrently. </p> <p class="rule"> @@ -119,11 +122,6 @@ The start of the function <code>main.main</code> happens after all <code>init</code> functions have finished. </p> -<p class="rule"> -The execution of any goroutines created during <code>init</code> -functions happens after all <code>init</code> functions have finished. -</p> - <h3>Goroutine creation</h3> <p class="rule"> @@ -285,7 +283,7 @@ The <code>sync</code> package implements two lock data types, <p class="rule"> For any <code>sync.Mutex</code> or <code>sync.RWMutex</code> variable <code>l</code> and <i>n</i> < <i>m</i>, -the <i>n</i>'th call to <code>l.Unlock()</code> happens before the <i>m</i>'th call to <code>l.Lock()</code> returns. +call <i>n</i> of <code>l.Unlock()</code> happens before call <i>m</i> of <code>l.Lock()</code> returns. </p> <p> @@ -318,9 +316,9 @@ which happens before the <code>print</code>. <p class="rule"> For any call to <code>l.RLock</code> on a <code>sync.RWMutex</code> variable <code>l</code>, -there is an <i>n</i> such that the <code>l.RLock</code> happens (returns) after the <i>n</i>'th call to +there is an <i>n</i> such that the <code>l.RLock</code> happens (returns) after call <i>n</i> to <code>l.Unlock</code> and the matching <code>l.RUnlock</code> happens -before the <i>n</i>+1'th call to <code>l.Lock</code>. +before call <i>n</i>+1 to <code>l.Lock</code>. </p> <h3>Once</h3> diff --git a/doc/go_spec.html b/doc/go_spec.html index 82c7ed419..2c905c723 100644 --- a/doc/go_spec.html +++ b/doc/go_spec.html @@ -1,5 +1,8 @@ -<!-- title The Go Programming Language Specification --> -<!-- subtitle Version of July 14, 2011 --> +<!--{ + "Title": "The Go Programming Language Specification", + "Subtitle": "Version of March 17, 2012", + "Path": "/ref/spec" +}--> <!-- TODO @@ -13,7 +16,6 @@ TODO [ ] should probably write something about evaluation order of statements even though obvious [ ] review language on implicit dereferencing -[ ] clarify what it means for two functions to be "the same" when comparing them --> @@ -66,15 +68,15 @@ operators, in increasing precedence: <p> Lower-case production names are used to identify lexical tokens. -Non-terminals are in CamelCase. Lexical symbols are enclosed in +Non-terminals are in CamelCase. Lexical tokens are enclosed in double quotes <code>""</code> or back quotes <code>``</code>. </p> <p> The form <code>a … b</code> represents the set of characters from <code>a</code> through <code>b</code> as alternatives. The horizontal -ellipis … is also used elsewhere in the spec to informally denote various -enumerations or code snippets that are not further specified. The character … +ellipsis <code>…</code> is also used elsewhere in the spec to informally denote various +enumerations or code snippets that are not further specified. The character <code>…</code> (as opposed to the three characters <code>...</code>) is not a token of the Go language. </p> @@ -146,7 +148,7 @@ and stop at the end of the line. A line comment acts like a newline. <li> <i>General comments</i> start with the character sequence <code>/*</code> and continue through the character sequence <code>*/</code>. A general -comment that spans multiple lines acts like a newline, otherwise it acts +comment containing one or more newlines acts like a newline, otherwise it acts like a space. </li> </ol> @@ -191,7 +193,7 @@ token is <li>an <a href="#Identifiers">identifier</a> </li> - + <li>an <a href="#Integer_literals">integer</a>, <a href="#Floating-point_literals">floating-point</a>, @@ -199,14 +201,14 @@ token is <a href="#Character_literals">character</a>, or <a href="#String_literals">string</a> literal </li> - + <li>one of the <a href="#Keywords">keywords</a> <code>break</code>, <code>continue</code>, <code>fallthrough</code>, or <code>return</code> </li> - + <li>one of the <a href="#Operators_and_Delimiters">operators and delimiters</a> <code>++</code>, <code>--</code>, @@ -361,7 +363,7 @@ imaginary_lit = (decimals | float_lit) "i" . <h3 id="Character_literals">Character literals</h3> <p> -A character literal represents an <a href="#Constants">integer constant</a>, +A character literal represents a <a href="#Constants">character constant</a>, typically a Unicode code point, as one or more characters enclosed in single quotes. Within the quotes, any character may appear except single quote and newline. A single quoted character represents itself, @@ -453,12 +455,14 @@ Raw string literals are character sequences between back quotes back quote. The value of a raw string literal is the string composed of the uninterpreted characters between the quotes; in particular, backslashes have no special meaning and the string may -span multiple lines. +contain newlines. +Carriage returns inside raw string literals +are discarded from the raw string value. </p> <p> Interpreted string literals are character sequences between double quotes <code>""</code>. The text between the quotes, -which may not span multiple lines, forms the +which may not contain newlines, forms the value of the literal, with backslash escapes interpreted as they are in character literals (except that <code>\'</code> is illegal and <code>\"</code> is legal). The three-digit octal (<code>\</code><i>nnn</i>) @@ -513,19 +517,22 @@ literal. <h2 id="Constants">Constants</h2> -<p>There are <i>boolean constants</i>, <i>integer constants</i>, +<p>There are <i>boolean constants</i>, +<i>character constants</i>, +<i>integer constants</i>, <i>floating-point constants</i>, <i>complex constants</i>, -and <i>string constants</i>. Integer, floating-point, +and <i>string constants</i>. Character, integer, floating-point, and complex constants are collectively called <i>numeric constants</i>. </p> <p> -A constant value is represented by an +A constant value is represented by a +<a href="#Character_literals">character</a>, <a href="#Integer_literals">integer</a>, <a href="#Floating-point_literals">floating-point</a>, <a href="#Imaginary_literals">imaginary</a>, -<a href="#Character_literals">character</a>, or +or <a href="#String_literals">string</a> literal, an identifier denoting a constant, a <a href="#Constant_expressions">constant expression</a>, @@ -583,11 +590,33 @@ functions return and test for those values at run time. </p> <p> -Implementation restriction: A compiler may implement numeric constants by choosing -an internal representation with at least twice as many bits as any machine type; -for floating-point values, both the mantissa and exponent must be twice as large. +Implementation restriction: Although numeric constants have arbitrary +precision in the language, a compiler may implement them using an +internal representation with limited precision. That said, every +implementation must: </p> +<ul> + <li>Represent integer constants with at least 256 bits.</li> + + <li>Represent floating-point constants, including the parts of + a complex constant, with a mantissa of at least 256 bits + and a signed exponent of at least 32 bits.</li> + + <li>Give an error if unable to represent an integer constant + precisely.</li> + <li>Give an error if unable to represent a floating-point or + complex constant due to overflow.</li> + + <li>Round to the nearest representable constant if unable to + represent a floating-point or complex constant due to limits + on precision.</li> +</ul> +<p> +These requirements apply both to literal constants and to the result +of evaluating <a href="#Constant_expressions">constant +expressions</a>. +</p> <h2 id="Types">Types</h2> @@ -650,22 +679,30 @@ and <code>T4</code> is <code>[]T1</code>. A type may have a <i>method set</i> associated with it (§<a href="#Interface_types">Interface types</a>, §<a href="#Method_declarations">Method declarations</a>). The method set of an <a href="#Interface_types">interface type</a> is its interface. -The method set of any other named type <code>T</code> +The method set of any other type <code>T</code> consists of all methods with receiver type <code>T</code>. The method set of the corresponding pointer type <code>*T</code> is the set of all methods with receiver <code>*T</code> or <code>T</code> (that is, it also contains the method set of <code>T</code>). Any other type has an empty method set. -In a method set, each method must have a unique name. +In a method set, each method must have a +<a href="#Uniqueness_of_identifiers">unique</a> <a href="#MethodName">method name</a>. </p> +<p> +The method set of a type determines the interfaces that the +type <a href="#Interface_types">implements</a> +and the methods that can be <a href="#Calls">called</a> +using a receiver of that type. +</p> <h3 id="Boolean_types">Boolean types</h3> +<p> A <i>boolean type</i> represents the set of Boolean truth values denoted by the predeclared constants <code>true</code> and <code>false</code>. The predeclared boolean type is <code>bool</code>. - +</p> <h3 id="Numeric_types">Numeric types</h3> @@ -691,7 +728,8 @@ float64 the set of all IEEE-754 64-bit floating-point numbers complex64 the set of all complex numbers with float32 real and imaginary parts complex128 the set of all complex numbers with float64 real and imaginary parts -byte familiar alias for uint8 +byte alias for uint8 +rune alias for int32 </pre> <p> @@ -711,7 +749,8 @@ uintptr an unsigned integer large enough to store the uninterpreted bits of a p <p> To avoid portability issues all numeric types are distinct except -<code>byte</code>, which is an alias for <code>uint8</code>. +<code>byte</code>, which is an alias for <code>uint8</code>, and +<code>rune</code>, which is an alias for <code>int32</code>. Conversions are required when different numeric types are mixed in an expression or assignment. For instance, <code>int32</code> and <code>int</code> @@ -723,7 +762,7 @@ particular architecture. <p> A <i>string type</i> represents the set of string values. -Strings behave like arrays of bytes but are immutable: once created, +Strings behave like slices of bytes but are immutable: once created, it is impossible to change the contents of a string. The predeclared string type is <code>string</code>. @@ -760,7 +799,7 @@ The length is part of the array's type and must be a integer value. The length of array <code>a</code> can be discovered using the built-in function <a href="#Length_and_capacity"><code>len(a)</code></a>. The elements can be indexed by integer -indices 0 through the <code>len(a)-1</code> (§<a href="#Indexes">Indexes</a>). +indices 0 through <code>len(a)-1</code> (§<a href="#Indexes">Indexes</a>). Array types are always one-dimensional but may be composed to form multi-dimensional types. </p> @@ -858,7 +897,7 @@ A struct is a sequence of named elements, called fields, each of which has a name and a type. Field names may be specified explicitly (IdentifierList) or implicitly (AnonymousField). Within a struct, non-<a href="#Blank_identifier">blank</a> field names must -be unique. +be <a href="#Uniqueness_of_identifiers">unique</a>. </p> <pre class="ebnf"> @@ -883,9 +922,9 @@ struct { </pre> <p> -A field declared with a type but no explicit field name is an <i>anonymous field</i> -(colloquially called an embedded field). -Such a field type must be specified as +A field declared with a type but no explicit field name is an <i>anonymous field</i>, +also called an <i>embedded</i> field or an embedding of the type in the struct. +An embedded type must be specified as a type name <code>T</code> or as a pointer to a non-interface type name <code>*T</code>, and <code>T</code> itself may not be a pointer type. The unqualified type name acts as the field name. @@ -909,16 +948,16 @@ in a struct type: <pre> struct { - T // conflicts with anonymous field *T and *P.T - *T // conflicts with anonymous field T and *P.T - *P.T // conflicts with anonymous field T and *T + T // conflicts with anonymous field *T and *P.T + *T // conflicts with anonymous field T and *P.T + *P.T // conflicts with anonymous field T and *T } </pre> <p> Fields and methods (§<a href="#Method_declarations">Method declarations</a>) of an anonymous field are promoted to be ordinary fields and methods of the struct (§<a href="#Selectors">Selectors</a>). -The following rules apply for a struct type named <code>S</code> and +The following rules apply for a struct type <code>S</code> and a type named <code>T</code>: </p> <ul> @@ -970,8 +1009,8 @@ BaseType = Type . </pre> <pre> -*int -*map[string] *chan int +*Point +*[4]int </pre> <h3 id="Function_types">Function types</h3> @@ -1009,11 +1048,10 @@ may be invoked with zero or more arguments for that parameter. <pre> func() -func(x int) -func() int -func(prefix string, values ...int) -func(a, b int, z float32) bool +func(x int) int +func(a, _ int, z float32) bool func(a, b int, z float32) (bool) +func(prefix string, values ...int) func(a, b int, z float64, opt ...interface{}) (success bool) func(int, int, float64) (float64, *[]int) func(n int) func(p *T) @@ -1038,7 +1076,8 @@ InterfaceTypeName = TypeName . </pre> <p> -As with all method sets, in an interface type, each method must have a unique name. +As with all method sets, in an interface type, each method must have a +<a href="#Uniqueness_of_identifiers">unique</a> name. </p> <pre> @@ -1106,9 +1145,10 @@ they implement the <code>Lock</code> interface as well as the <code>File</code> interface. </p> <p> -An interface may contain an interface type name <code>T</code> +An interface may use an interface type name <code>T</code> in place of a method specification. -The effect is equivalent to enumerating the methods of <code>T</code> explicitly +The effect, called embedding an interface, +is equivalent to enumerating the methods of <code>T</code> explicitly in the interface. </p> @@ -1125,6 +1165,26 @@ type File interface { } </pre> +<p> +An interface type <code>T</code> may not embed itself +or any interface type that embeds <code>T</code>, recursively. +</p> + +<pre> +// illegal: Bad cannot embed itself +type Bad interface { + Bad +} + +// illegal: Bad1 cannot embed itself using Bad2 +type Bad1 interface { + Bad2 +} +type Bad2 interface { + Bad1 +} +</pre> + <h3 id="Map_types">Map types</h3> <p> @@ -1142,7 +1202,8 @@ KeyType = Type . <p> The comparison operators <code>==</code> and <code>!=</code> (§<a href="#Comparison_operators">Comparison operators</a>) must be fully defined -for operands of the key type; thus the key type must not be a struct, array or slice. +for operands of the key type; thus the key type must not be a function, map, or +slice. If the key type is an interface type, these comparison operators must be defined for the dynamic key values; failure will cause a <a href="#Run_time_panics">run-time panic</a>. @@ -1150,18 +1211,19 @@ failure will cause a <a href="#Run_time_panics">run-time panic</a>. </p> <pre> -map [string] int -map [*T] struct { x, y float64 } -map [string] interface {} +map[string]int +map[*T]struct{ x, y float64 } +map[string]interface{} </pre> <p> The number of map elements is called its length. For a map <code>m</code>, it can be discovered using the built-in function <a href="#Length_and_capacity"><code>len(m)</code></a> -and may change during execution. Elements may be added and removed -during execution using special forms of <a href="#Assignments">assignment</a>; -and they may be accessed with <a href="#Indexes">index</a> expressions. +and may change during execution. Elements may be added during execution +using <a href="#Assignments">assignments</a> and retrieved with +<a href="#Indexes">index</a> expressions; they may be removed with the +<a href="#Deletion_of_map_elements"><code>delete</code></a> built-in function. </p> <p> A new, empty map value is made using the built-in @@ -1170,8 +1232,8 @@ which takes the map type and an optional capacity hint as arguments: </p> <pre> -make(map[string] int) -make(map[string] int, 100) +make(map[string]int) +make(map[string]int, 100) </pre> <p> @@ -1203,9 +1265,9 @@ A channel may be constrained only to send or only to receive by </p> <pre> -chan T // can be used to send and receive values of type T -chan<- float64 // can only be used to send float64s -<-chan int // can only be used to receive ints +chan T // can be used to send and receive values of type T +chan<- float64 // can only be used to send float64s +<-chan int // can only be used to receive ints </pre> <p> @@ -1214,9 +1276,9 @@ possible: </p> <pre> -chan<- chan int // same as chan<- (chan int) -chan<- <-chan int // same as chan<- (<-chan int) -<-chan <-chan int // same as <-chan (<-chan int) +chan<- chan int // same as chan<- (chan int) +chan<- <-chan int // same as chan<- (<-chan int) +<-chan <-chan int // same as <-chan (<-chan int) chan (<-chan int) </pre> @@ -1233,7 +1295,7 @@ make(chan int, 100) <p> The capacity, in number of elements, sets the size of the buffer in the channel. If the -capacity is greater than zero, the channel is asynchronous: communication operations +capacity is greater than zero, the channel is asynchronous: communication operations succeed without blocking if the buffer is not full (sends) or not empty (receives), and elements are received in the order they are sent. If the capacity is zero or absent, the communication succeeds only when both a sender and @@ -1259,7 +1321,7 @@ Two types are either <i>identical</i> or <i>different</i>. <p> Two named types are identical if their type names originate in the same -type <a href="#Declarations_and_scope">declaration</a>. +<a href="#Type_declarations">TypeSpec</a>. A named and an unnamed type are always different. Two unnamed types are identical if the corresponding type literals are identical, that is, if they have the same literal structure and corresponding components have identical types. In detail: @@ -1302,8 +1364,8 @@ Given the declarations type ( T0 []string T1 []string - T2 struct { a, b int } - T3 struct { a, c int } + T2 struct{ a, b int } + T3 struct{ a, c int } T4 func(int, float64) *T0 T5 func(x int, y float64) *[]string ) @@ -1316,7 +1378,7 @@ these types are identical: <pre> T0 and T0 []int and []int -struct { a, b *T5 } and struct { a, b *T5 } +struct{ a, b *T5 } and struct{ a, b *T5 } func(x int, y float64) *[]string and func(int, float64) (result *[]string) </pre> @@ -1364,15 +1426,6 @@ by a value of type <code>T</code>. </ul> <p> -If <code>T</code> is a struct type with non-<a href="#Exported_identifiers">exported</a> -fields, the assignment must be in the same package in which <code>T</code> is declared, -or <code>x</code> must be the receiver of a method call. -In other words, a struct value can be assigned to a struct variable only if -every field of the struct may be legally assigned individually by the program, -or if the assignment is initializing the receiver of a method of the struct type. -</p> - -<p> Any value may be assigned to the <a href="#Blank_identifier">blank identifier</a>. </p> @@ -1488,18 +1541,25 @@ the body of any nested function. </p> +<h3 id="Blank_identifier">Blank identifier</h3> + +<p> +The <i>blank identifier</i>, represented by the underscore character <code>_</code>, may be used in a declaration like +any other identifier but the declaration does not introduce a new binding. +</p> + + <h3 id="Predeclared_identifiers">Predeclared identifiers</h3> <p> -The following identifiers are implicitly declared in the universe block: +The following identifiers are implicitly declared in the +<a href="#Blocks">universe block</a>: </p> <pre class="grammar"> -Basic types: - bool byte complex64 complex128 float32 float64 - int8 int16 int32 int64 string uint8 uint16 uint32 uint64 - -Architecture-specific convenience types: - int uint uintptr +Types: + bool byte complex64 complex128 error float32 float64 + int int8 int16 int32 int64 rune string + uint uint8 uint16 uint32 uint64 uintptr Constants: true false iota @@ -1508,7 +1568,7 @@ Zero value: nil Functions: - append cap close complex copy imag len + append cap close complex copy delete imag len make new panic print println real recover </pre> @@ -1516,28 +1576,31 @@ Functions: <h3 id="Exported_identifiers">Exported identifiers</h3> <p> -An identifier may be <i>exported</i> to permit access to it from another package -using a <a href="#Qualified_identifiers">qualified identifier</a>. An identifier -is exported if both: +An identifier may be <i>exported</i> to permit access to it from another package. +An identifier is exported if both: </p> <ol> - <li>the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu"); and</li> - <li>the identifier is declared in the <a href="#Blocks">package block</a> or denotes a field or method of a type - declared in that block.</li> + <li>the first character of the identifier's name is a Unicode upper case + letter (Unicode class "Lu"); and</li> + <li>the identifier is declared in the <a href="#Blocks">package block</a> + or it is a <a href="#Struct_types">field name</a> or + <a href="#MethodName">method name</a>.</li> </ol> <p> All other identifiers are not exported. </p> -<h3 id="Blank_identifier">Blank identifier</h3> +<h3 id="Uniqueness_of_identifiers">Uniqueness of identifiers</h3> <p> -The <i>blank identifier</i>, represented by the underscore character <code>_</code>, may be used in a declaration like -any other identifier but the declaration does not introduce a new binding. +Given a set of identifiers, an identifier is called <i>unique</i> if it is +<i>different</i> from every other in the set. +Two identifiers are different if they are spelled differently, or if they +appear in different <a href="#Packages">packages</a> and are not +<a href="Exported_identifiers">exported</a>. Otherwise, they are the same. </p> - <h3 id="Constant_declarations">Constant declarations</h3> <p> @@ -1571,10 +1634,10 @@ constant, even if the literal's fractional part is zero. <pre> const Pi float64 = 3.14159265358979323846 -const zero = 0.0 // untyped floating-point constant +const zero = 0.0 // untyped floating-point constant const ( size int64 = 1024 - eof = -1 // untyped integer constant + eof = -1 // untyped integer constant ) const a, b, c = 3, 4, "foo" // a = 3, b = 4, c = "foo", untyped integer and string constants const u, v float32 = 0, 3 // u = 0.0, v = 3.0 @@ -1646,10 +1709,10 @@ it is only incremented after each ConstSpec: <pre> const ( - bit0, mask0 = 1 << iota, 1 << iota - 1 // bit0 == 1, mask0 == 0 - bit1, mask1 // bit1 == 2, mask1 == 1 - _, _ // skips iota == 2 - bit3, mask3 // bit3 == 8, mask3 == 7 + bit0, mask0 = 1 << iota, 1<<iota - 1 // bit0 == 1, mask0 == 0 + bit1, mask1 // bit1 == 2, mask1 == 1 + _, _ // skips iota == 2 + bit3, mask3 // bit3 == 8, mask3 == 7 ) </pre> @@ -1677,7 +1740,7 @@ TypeSpec = identifier Type . type IntArray [16]int type ( - Point struct { x, y float64 } + Point struct{ x, y float64 } Polar Point ) @@ -1686,7 +1749,7 @@ type TreeNode struct { value *Comparable } -type Cipher interface { +type Block interface { BlockSize() int Encrypt(src, dst []byte) Decrypt(src, dst []byte) @@ -1718,8 +1781,8 @@ type PrintableMutex struct { Mutex } -// MyCipher is an interface type that has the same method set as Cipher. -type MyCipher Cipher +// MyBlock is an interface type that has the same method set as Block. +type MyBlock Block </pre> <p> @@ -1760,7 +1823,7 @@ var U, V, W float64 var k = 0 var x, y float32 = -1, -2 var ( - i int + i int u, v, s = 2.0, 3.0, "bar" ) var re, im = complexSqrt(-1) @@ -1783,17 +1846,14 @@ of the expression list. <p> If the type is absent and the corresponding expression evaluates to an untyped <a href="#Constants">constant</a>, the type of the declared variable -is <code>bool</code>, <code>int</code>, <code>float64</code>, or <code>string</code> -respectively, depending on whether the value is a boolean, integer, -floating-point, or string constant: +is as described in §<a href="#Assignments">Assignments</a>. </p> -<pre> -var b = true // t has type bool -var i = 0 // i has type int -var f = 3.0 // f has type float64 -var s = "OMDB" // s has type string -</pre> +<p> +Implementation restriction: A compiler may make it illegal to declare a variable +inside a <a href="#Function_declarations">function body</a> if the variable is +never used. +</p> <h3 id="Short_variable_declarations">Short variable declarations</h3> @@ -1806,8 +1866,8 @@ ShortVarDecl = IdentifierList ":=" ExpressionList . </pre> <p> -It is a shorthand for a regular variable declaration with -initializer expressions but no types: +It is a shorthand for a regular <a href="#Variable_declarations">variable declaration</a> +with initializer expressions but no types: </p> <pre class="grammar"> @@ -1846,11 +1906,13 @@ they can be used to declare local temporary variables (§<a href="#Statements">S <h3 id="Function_declarations">Function declarations</h3> <p> -A function declaration binds an identifier to a function (§<a href="#Function_types">Function types</a>). +A function declaration binds an identifier, the <i>function name</i>, +to a function. </p> <pre class="ebnf"> -FunctionDecl = "func" identifier Signature [ Body ] . +FunctionDecl = "func" FunctionName Signature [ Body ] . +FunctionName = identifier . Body = Block . </pre> @@ -1874,8 +1936,10 @@ func flushICache(begin, end uintptr) // implemented externally <p> A method is a function with a <i>receiver</i>. -A method declaration binds an identifier to a method. +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>. </p> + <pre class="ebnf"> MethodDecl = "func" Receiver MethodName Signature [ Body ] . Receiver = "(" [ identifier ] [ "*" ] BaseTypeName ")" . @@ -1884,13 +1948,18 @@ BaseTypeName = identifier . <p> The receiver type must be of the form <code>T</code> or <code>*T</code> where -<code>T</code> is a type name. <code>T</code> is called the -<i>receiver base type</i> or just <i>base type</i>. -The base type must not be a pointer or interface type and must be -declared in the same package as the method. -The method is said to be <i>bound</i> to the base type -and is visible only within selectors for that type -(§<a href="#Type_declarations">Type declarations</a>, §<a href="#Selectors">Selectors</a>). +<code>T</code> is a type name. The type denoted by <code>T</code> is called +the receiver <i>base type</i>; it must not be a pointer or interface type and +it must be declared in the same package as the method. +The method is said to be <i>bound</i> to the base type and the method name +is visible only within selectors for that type. +</p> + +<p> +For a base type, the non-<a href="#Blank_identifier">blank</a> names of +methods bound to it must be <a href="#Uniqueness_of_identifiers">unique</a>. +If the base type is a <a href="#Struct_types">struct type</a>, +the non-blank method and field names must be distinct. </p> <p> @@ -1957,7 +2026,8 @@ BasicLit = int_lit | float_lit | imaginary_lit | char_lit | string_lit . <h3 id="Qualified_identifiers">Qualified identifiers</h3> <p> -A qualified identifier is a non-<a href="#Blank_identifier">blank</a> identifier qualified by a package name prefix. +A qualified identifier is a non-<a href="#Blank_identifier">blank</a> identifier +qualified by a package name prefix. </p> <pre class="ebnf"> @@ -1965,21 +2035,16 @@ QualifiedIdent = [ PackageName "." ] identifier . </pre> <p> -A qualified identifier accesses an identifier in a separate package. -The identifier must be <a href="#Exported_identifiers">exported</a> by that -package, which means that it must begin with a Unicode upper case letter. +A qualified identifier accesses an identifier in a different package, which +must be <a href="#Import_declarations">imported</a>. +The identifier must be <a href="#Exported_identifiers">exported</a> and +declared in the <a href="#Blocks">package block</a> of that package. </p> <pre> -math.Sin +math.Sin // denotes the Sin function in package math </pre> -<!-- -<p> -<span class="alert">TODO: Unify this section with Selectors - it's the same syntax.</span> -</p> ---> - <h3 id="Composite_literals">Composite literals</h3> <p> @@ -2091,9 +2156,9 @@ to the maximum element index plus one. </p> <pre> -buffer := [10]string{} // len(buffer) == 10 -intSet := [6]int{1, 2, 3, 5} // len(intSet) == 6 -days := [...]string{"Sat", "Sun"} // len(days) == 2 +buffer := [10]string{} // len(buffer) == 10 +intSet := [6]int{1, 2, 3, 5} // len(intSet) == 6 +days := [...]string{"Sat", "Sun"} // len(days) == 2 </pre> <p> @@ -2107,22 +2172,29 @@ element index plus one. A slice literal has the form </pre> <p> -and is a shortcut for a slice operation applied to an array literal: +and is a shortcut for a slice operation applied to an array: </p> <pre> -[n]T{x1, x2, … xn}[0 : n] +tmp := [n]T{x1, x2, … xn} +tmp[0 : n] </pre> <p> Within a composite literal of array, slice, or map type <code>T</code>, elements that are themselves composite literals may elide the respective literal type if it is identical to the element type of <code>T</code>. +Similarly, elements that are addresses of composite literals may elide +the <code>&T</code> when the the element type is <code>*T</code>. </p> + + <pre> -[...]Point{{1.5, -3.5}, {0, 0}} // same as [...]Point{Point{1.5, -3.5}, Point{0, 0}} -[][]int{{1, 2, 3}, {4, 5}} // same as [][]int{[]int{1, 2, 3}, []int{4, 5}} +[...]Point{{1.5, -3.5}, {0, 0}} // same as [...]Point{Point{1.5, -3.5}, Point{0, 0}} +[][]int{{1, 2, 3}, {4, 5}} // same as [][]int{[]int{1, 2, 3}, []int{4, 5}} + +[...]*Point{{1.5, -3.5}, {0, 0}} // same as [...]*Point{&Point{1.5, -3.5}, &Point{0, 0}} </pre> <p> @@ -2147,7 +2219,7 @@ Examples of valid array, slice, and map literals: <pre> // list of prime numbers -primes := []int{2, 3, 5, 7, 9, 11, 13, 17, 19, 991} +primes := []int{2, 3, 5, 7, 9, 2147483647} // vowels[ch] is true if ch is a vowel vowels := [128]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true, 'y': true} @@ -2184,7 +2256,7 @@ A function literal can be assigned to a variable or invoked directly. <pre> f := func(x, y int) int { return x + y } -func(ch chan int) { ch <- ACK } (reply_chan) +func(ch chan int) { ch <- ACK }(replyChan) </pre> <p> @@ -2275,8 +2347,8 @@ where <code>T</code> is not an interface type, <code>x.f</code> denotes the field or method at the shallowest depth in <code>T</code> where there is such an <code>f</code>. -If there is not exactly one <code>f</code> with shallowest depth, the selector -expression is illegal. +If there is not exactly <a href="#Uniqueness_of_identifiers">one <code>f</code></a> +with shallowest depth, the selector expression is illegal. </li> <li> For a variable <code>x</code> of type <code>I</code> @@ -2332,13 +2404,13 @@ one may write: </p> <pre> -p.z // (*p).z -p.y // ((*p).T1).y -p.x // (*(*p).T0).x +p.z // (*p).z +p.y // ((*p).T1).y +p.x // (*(*p).T0).x -p.M2 // (*p).M2 -p.M1 // ((*p).T1).M1 -p.M0 // ((*p).T0).M0 +p.M2 // (*p).M2 +p.M1 // ((*p).T1).M1 +p.M0 // ((*p).T0).M0 </pre> @@ -2432,21 +2504,6 @@ where the result of the index expression is a pair of values with types </p> <p> -Similarly, if an assignment to a map element has the special form -</p> - -<pre> -a[x] = v, ok -</pre> - -<p> -and boolean <code>ok</code> has the value <code>false</code>, -the entry for key <code>x</code> is deleted from the map; if -<code>ok</code> is <code>true</code>, the construct acts like -a regular assignment to an element of the map. -</p> - -<p> Assigning to an element of a <code>nil</code> map causes a <a href="#Run_time_panics">run-time panic</a>. </p> @@ -2455,7 +2512,7 @@ Assigning to an element of a <code>nil</code> map causes a <h3 id="Slices">Slices</h3> <p> -For a string, array, or slice <code>a</code>, the primary expression +For a string, array, pointer to array, or slice <code>a</code>, the primary expression </p> <pre> @@ -2492,9 +2549,9 @@ sliced operand: </p> <pre> -a[2:] // same a[2 : len(a)] -a[:3] // same as a[0 : 3] -a[:] // same as a[0 : len(a)] +a[2:] // same a[2 : len(a)] +a[:3] // same as a[0 : 3] +a[:] // same as a[0 : len(a)] </pre> <p> @@ -2587,12 +2644,26 @@ the method. </p> <pre> -math.Atan2(x, y) // function call +math.Atan2(x, y) // function call var pt *Point pt.Scale(3.5) // method call with receiver pt </pre> <p> +In a function call, the function value and arguments are evaluated in +<a href="#Order_of_evaluation">the usual order</a>. +After they are evaluated, the parameters of the call are passed by value to the function +and the called function begins execution. +The return parameters of the function are passed by value +back to the calling function when the function returns. +</p> + +<p> +Calling a <code>nil</code> function value +causes a <a href="#Run_time_panics">run-time panic</a>. +</p> + +<p> As a special case, if the return parameters of a function or method <code>g</code> are equal in number and individually assignable to the parameters of another function or method @@ -2731,13 +2802,13 @@ var s uint = 33 var i = 1<<s // 1 has type int var j int32 = 1<<s // 1 has type int32; j == 0 var k = uint64(1<<s) // 1 has type uint64; k == 1<<33 -var m int = 1.0<<s // legal: 1.0 has type int -var n = 1.0<<s != 0 // legal: 1.0 has type int; n == false if ints are 32bits in size -var o = 1<<s == 2<<s // legal: 1 and 2 have type int; o == true if ints are 32bits in size +var m int = 1.0<<s // 1.0 has type int +var n = 1.0<<s != 0 // 1.0 has type int; n == false if ints are 32bits in size +var o = 1<<s == 2<<s // 1 and 2 have type int; o == true if ints are 32bits in size var p = 1<<s == 1<<33 // illegal if ints are 32bits in size: 1 has type int, but 1<<33 overflows int var u = 1.0<<s // illegal: 1.0 has type float64, cannot shift var v float32 = 1<<s // illegal: 1 has type float32, cannot shift -var w int64 = 1.0<<33 // legal: 1.0<<33 is a constant shift expression +var w int64 = 1.0<<33 // 1.0<<33 is a constant shift expression </pre> <h3 id="Operator_precedence">Operator precedence</h3> @@ -2774,7 +2845,7 @@ For instance, <code>x / y * z</code> is the same as <code>(x / y) * z</code>. x <= f() ^a >> b f() || g() -x == y+1 && <-chan_ptr > 0 +x == y+1 && <-chanPtr > 0 </pre> @@ -2924,7 +2995,7 @@ not occur. For instance, it may not assume that <code>x < x + 1</code> is alw <h3 id="Comparison_operators">Comparison operators</h3> <p> -Comparison operators compare two operands and yield a value of type <code>bool</code>. +Comparison operators compare two operands and yield a boolean value. </p> <pre class="grammar"> @@ -2932,76 +3003,122 @@ Comparison operators compare two operands and yield a value of type <code>bool</ != not equal < less <= less or equal -> greater ->= greater or equal +> greater +>= greater or equal </pre> <p> -The operands must be <i>comparable</i>; that is, the first operand +In any comparison, the first operand must be <a href="#Assignability">assignable</a> to the type of the second operand, or vice versa. </p> <p> -The operators <code>==</code> and <code>!=</code> apply -to operands of all types except arrays and structs. -All other comparison operators apply only to integer, floating-point -and string values. The result of a comparison is defined as follows: +The equality operators <code>==</code> and <code>!=</code> apply +to operands that are <i>comparable</i>. +The ordering operators <code><</code>, <code><=</code>, <code>></code>, and <code>>=</code> +apply to operands that are <i>ordered</i>. +These terms and the result of the comparisons are defined as follows: </p> <ul> <li> - Integer values are compared in the usual way. - </li> - <li> - Floating point values are compared as defined by the IEEE-754 - standard. + Boolean values are comparable. + Two boolean values are equal if they are either both + <code>true</code> or both <code>false</code>. </li> + <li> - Two complex values <code>u</code>, <code>v</code> are - equal if both <code>real(u) == real(v)</code> and - <code>imag(u) == imag(v)</code>. + Integer values are comparable and ordered, in the usual way. </li> + <li> - String values are compared byte-wise (lexically). + Floating point values are comparable and ordered, + as defined by the IEEE-754 standard. </li> + <li> - Boolean values are equal if they are either both - <code>true</code> or both <code>false</code>. + Complex values are comparable. + Two complex values <code>u</code> and <code>v</code> are + equal if both <code>real(u) == real(v)</code> and + <code>imag(u) == imag(v)</code>. </li> + <li> - Pointer values are equal if they point to the same location - or if both are <code>nil</code>. + String values are comparable and ordered, lexically byte-wise. </li> + <li> - Function values are equal if they refer to the same function - or if both are <code>nil</code>. + Pointer values are comparable. + Two pointer values are equal if they point to the same variable or if both have value <code>nil</code>. + Pointers to distinct <a href="#Size_and_alignment_guarantees">zero-size</a> variables may or may not be equal. </li> + <li> - A slice value may only be compared to <code>nil</code>. + 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>) + or if both have value <code>nil</code>. </li> + <li> - Channel and map 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>) - or if both are <code>nil</code>. + Interface values are comparable. + Two interface values are equal if they have <a href="#Type_identity">identical</a> dynamic types + and equal dynamic values or if both have value <code>nil</code>. </li> + <li> - Interface values are equal if they have <a href="#Type_identity">identical</a> dynamic types and - equal dynamic values or if both are <code>nil</code>. + A value <code>x</code> of non-interface type <code>X</code> and + a value <code>t</code> of interface type <code>T</code> are comparable when values + of type <code>X</code> are comparable and + <code>X</code> implements <code>T</code>. + They are equal if <code>t</code>'s dynamic type is identical to <code>X</code> + and <code>t</code>'s dynamic value is equal to <code>x</code>. </li> + <li> - An interface value <code>x</code> is equal to a non-interface value - <code>y</code> if the dynamic type of <code>x</code> is identical to - the static type of <code>y</code> and the dynamic value of <code>x</code> - is equal to <code>y</code>. + Struct values are comparable if all their fields are comparable. + Two struct values are equal if their corresponding + non-<a href="#Blank_identifier">blank</a> fields are equal. </li> + <li> - A pointer, function, slice, channel, map, or interface value is equal - to <code>nil</code> if it has been assigned the explicit value - <code>nil</code>, if it is uninitialized, or if it has been assigned - another value equal to <code>nil</code>. + Array values are comparable if values of the array element type are comparable. + Two array values are equal if their corresponding elements are equal. </li> </ul> +<p> +A comparison of two interface values with identical dynamic types +causes a <a href="#Run_time_panics">run-time panic</a> if values +of that type are not comparable. This behavior applies not only to direct interface +value comparisons but also when comparing arrays of interface values +or structs with interface-valued fields. +</p> + +<p> +Slice, map, and function values are not comparable. +However, as a special case, a slice, map, or function value may +be compared to the predeclared identifier <code>nil</code>. +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 + +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 +) +</pre> <h3 id="Logical_operators">Logical operators</h3> @@ -3034,6 +3151,8 @@ As an exception to the addressability requirement, <code>x</code> may also be a For an operand <code>x</code> of pointer type <code>*T</code>, the pointer indirection <code>*x</code> denotes the value of type <code>T</code> pointed to by <code>x</code>. +If <code>x</code> is <code>nil</code>, an attempt to evaluate <code>*x</code> +will cause a <a href="#Run_time_panics">run-time panic</a>. </p> <pre> @@ -3111,7 +3230,7 @@ Consider a struct type <code>T</code> with two methods, type T struct { a int } -func (tv T) Mv(a int) int { return 0 } // value receiver +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> @@ -3288,11 +3407,11 @@ in any of these cases: </li> <li> <code>x</code> is an integer or has type <code>[]byte</code> or - <code>[]int</code> and <code>T</code> is a string type. + <code>[]rune</code> and <code>T</code> is a string type. </li> <li> <code>x</code> is a string and <code>T</code> is <code>[]byte</code> or - <code>[]int</code>. + <code>[]rune</code>. </li> </ul> @@ -3357,51 +3476,59 @@ string containing the UTF-8 representation of the integer. Values outside the range of valid Unicode code points are converted to <code>"\uFFFD"</code>. <pre> -string('a') // "a" -string(-1) // "\ufffd" == "\xef\xbf\xbd " -string(0xf8) // "\u00f8" == "ø" == "\xc3\xb8" +string('a') // "a" +string(-1) // "\ufffd" == "\xef\xbf\xbd " +string(0xf8) // "\u00f8" == "ø" == "\xc3\xb8" type MyString string -MyString(0x65e5) // "\u65e5" == "日" == "\xe6\x97\xa5" +MyString(0x65e5) // "\u65e5" == "日" == "\xe6\x97\xa5" </pre> </li> <li> -Converting a value of type <code>[]byte</code> (or -the equivalent <code>[]uint8</code>) to a string type yields a -string whose successive bytes are the elements of the slice. If +Converting a slice of bytes to a string type yields +a string whose successive bytes are the elements of the slice. If the slice value is <code>nil</code>, the result is the empty string. <pre> string([]byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hellø" + +type MyBytes []byte +string(MyBytes{'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hellø" </pre> </li> <li> -Converting a value of type <code>[]int</code> to a string type yields -a string that is the concatenation of the individual integers +Converting a slice of runes to a string type yields +a string that is the concatenation of the individual rune values converted to strings. If the slice value is <code>nil</code>, the result is the empty string. + <pre> -string([]int{0x767d, 0x9d6c, 0x7fd4}) // "\u767d\u9d6c\u7fd4" == "白鵬翔" +string([]rune{0x767d, 0x9d6c, 0x7fd4}) // "\u767d\u9d6c\u7fd4" == "白鵬翔" + +type MyRunes []rune +string(MyRunes{0x767d, 0x9d6c, 0x7fd4}) // "\u767d\u9d6c\u7fd4" == "白鵬翔" </pre> </li> <li> -Converting a value of a string type to <code>[]byte</code> (or <code>[]uint8</code>) +Converting a value of a string type to a slice of bytes type yields a slice whose successive elements are the bytes of the string. If the string is empty, the result is <code>[]byte(nil)</code>. <pre> -[]byte("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'} +[]byte("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'} +MyBytes("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'} </pre> </li> <li> -Converting a value of a string type to <code>[]int</code> yields a -slice containing the individual Unicode code points of the string. -If the string is empty, the result is <code>[]int(nil)</code>. +Converting a value of a string type to a slice of runes type +yields a slice containing the individual Unicode code points of the string. +If the string is empty, the result is <code>[]rune(nil)</code>. <pre> -[]int(MyString("白鵬翔")) // []int{0x767d, 0x9d6c, 0x7fd4} +[]rune(MyString("白鵬翔")) // []rune{0x767d, 0x9d6c, 0x7fd4} +MyRunes("白鵬翔") // []rune{0x767d, 0x9d6c, 0x7fd4} </pre> </li> </ol> @@ -3417,19 +3544,17 @@ operands and are evaluated at compile-time. <p> Untyped boolean, numeric, and string constants may be used as operands wherever it is legal to use an operand of boolean, numeric, or string type, -respectively. Except for shift operations, if the operands of a binary operation -are an untyped integer constant and an untyped floating-point constant, -the integer constant is converted to an untyped floating-point constant -(relevant for <code>/</code> and <code>%</code>). -Similarly, untyped integer or floating-point constants may be used as operands -wherever it is legal to use an operand of complex type; -the integer or floating point constant is converted to a -complex constant with a zero imaginary part. +respectively. +Except for shift operations, if the operands of a binary operation are +different kinds of untyped constants, the operation and, for non-boolean operations, the result use +the kind that appears later in this list: integer, character, floating-point, complex. +For example, an untyped integer constant divided by an +untyped complex constant yields an untyped complex constant. </p> <p> A constant <a href="#Comparison_operators">comparison</a> always yields -a constant of type <code>bool</code>. If the left operand of a constant +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 @@ -3440,32 +3565,33 @@ complex, or string constant). </p> <pre> -const a = 2 + 3.0 // a == 5.0 (floating-point constant) -const b = 15 / 4 // b == 3 (integer constant) -const c = 15 / 4.0 // c == 3.75 (floating-point constant) -const d = 1 << 3.0 // d == 8 (integer constant) -const e = 1.0 << 3 // e == 8 (integer constant) +const a = 2 + 3.0 // a == 5.0 (untyped floating-point constant) +const b = 15 / 4 // b == 3 (untyped integer constant) +const c = 15 / 4.0 // c == 3.75 (untyped floating-point constant) +const Θ float64 = 3/2 // Θ == 1.5 (type float64) +const d = 1 << 3.0 // d == 8 (untyped integer constant) +const e = 1.0 << 3 // e == 8 (untyped integer constant) const f = int32(1) << 33 // f == 0 (type int32) const g = float64(2) >> 1 // illegal (float64(2) is a typed floating-point constant) -const h = "foo" > "bar" // h == true (type bool) +const h = "foo" > "bar" // h == true (untyped boolean constant) +const j = true // j == true (untyped boolean constant) +const k = 'w' + 1 // k == 'x' (untyped character constant) +const l = "hi" // l == "hi" (untyped string constant) +const m = string(k) // m == "x" (type string) +const Σ = 1 - 0.707i // (untyped complex constant) +const Δ = Σ + 2.0e-4 // (untyped complex constant) +const Φ = iota*1i - 1/1i // (untyped complex constant) </pre> <p> -Imaginary literals are untyped complex constants (with zero real part) -and may be combined in binary -operations with untyped integer and floating-point constants; the -result is an untyped complex constant. -Complex constants are always constructed from -constant expressions involving imaginary -literals or constants derived from them, or calls of the built-in function -<a href="#Complex_numbers"><code>complex</code></a>. +Applying the built-in function <code>complex</code> to untyped +integer, character, or floating-point constants yields +an untyped complex constant. </p> <pre> -const Σ = 1 - 0.707i -const Δ = Σ + 2.0e-4 - 1/1i -const Φ = iota * 1i -const iΓ = complex(0, Γ) +const ic = complex(0, c) // ic == 3.75i (untyped complex constant) +const iΘ = complex(0, Θ) // iΘ == 1.5i (type complex128) </pre> <p> @@ -3485,11 +3611,11 @@ of the constant type. The following constant expressions are illegal: </p> <pre> -uint(-1) // -1 cannot be represented as a uint -int(3.14) // 3.14 cannot be represented as an int -int64(Huge) // 1<<100 cannot be represented as an int64 -Four * 300 // 300 cannot be represented as an int8 -Four * 100 // 400 cannot be represented as an int8 +uint(-1) // -1 cannot be represented as a uint +int(3.14) // 3.14 cannot be represented as an int +int64(Huge) // 1<<100 cannot be represented as an int64 +Four * 300 // 300 cannot be represented as an int8 +Four * 100 // 400 cannot be represented as an int8 </pre> <p> @@ -3499,13 +3625,23 @@ and -1 for signed and untyped constants. </p> <pre> -^1 // untyped integer constant, equal to -2 -uint8(^1) // error, same as uint8(-2), out of range -^uint8(1) // typed uint8 constant, same as 0xFF ^ uint8(1) = uint8(0xFE) -int8(^1) // same as int8(-2) -^int8(1) // same as -1 ^ int8(1) = -2 +^1 // untyped integer constant, equal to -2 +uint8(^1) // error, same as uint8(-2), out of range +^uint8(1) // typed uint8 constant, same as 0xFF ^ uint8(1) = uint8(0xFE) +int8(^1) // same as int8(-2) +^int8(1) // same as -1 ^ int8(1) = -2 </pre> +<p> +Implementation restriction: A compiler may use rounding while +computing untyped floating-point or complex constant expressions; see +the implementation restriction in the section +on <a href="#Constants">constants</a>. This rounding may cause a +floating-point constant expression to be invalid in an integer +context, even if it would be integral when calculated using infinite +precision. +</p> + <!-- <p> <span class="alert"> @@ -3529,7 +3665,7 @@ order. For example, in the assignment </p> <pre> -y[f()], ok = g(h(), i() + x[j()], <-c), k() +y[f()], ok = g(h(), i()+x[j()], <-c), k() </pre> <p> the function calls and communication happen in the order @@ -3628,10 +3764,10 @@ Channel = Expression . <p> Both the channel and the value expression are evaluated before communication -begins. Communication blocks until the send can proceed, at which point the -value is transmitted on the channel. +begins. Communication blocks until the send can proceed. A send on an unbuffered channel can proceed if a receiver is ready. A send on a buffered channel can proceed if there is room in the buffer. +A send on a closed channel proceeds by causing a <a href="#Run_time_panics">run-time panic</a>. A send on a <code>nil</code> channel blocks forever. </p> @@ -3730,14 +3866,32 @@ x, _ = f() // ignore second value returned by f() In the second form, the number of operands on the left must equal the number of expressions on the right, each of which must be single-valued, and the <i>n</i>th expression on the right is assigned to the <i>n</i>th -operand on the left. -The expressions on the right are evaluated before assigning to -any of the operands on the left, but otherwise the evaluation -order is unspecified beyond <a href="#Order_of_evaluation">the usual rules</a>. +operand on the left. The assignment proceeds in two phases. +First, the operands of <a href="#Indexes">index expressions</a> +and <a href="#Address_operators">pointer indirections</a> +(including implicit pointer indirections in <a href="#Selectors">selectors</a>) +on the left and the expressions on the right are all +<a href="#Order_of_evaluation">evaluated in the usual order</a>. +Second, the assignments are carried out in left-to-right order. </p> <pre> a, b = b, a // exchange a and b + +x := []int{1, 2, 3} +i := 0 +i, x[i] = 1, 2 // set i = 1, x[0] = 2 + +i = 0 +x[i], i = 2, 1 // set x[0] = 2, i = 1 + +x[0], x[0] = 1, 2 // set x[0] = 1, then x[0] = 2 (so x[0] = 2 at end) + +x[1], x[3] = 4, 5 // set x[1] = 4, then panic setting x[3] = 5. + +type Point struct { x, y int } +var p *Point +x[2], p.x = 6, 7 // set x[2] = 6, then panic setting p.x = 7 </pre> <p> @@ -3745,10 +3899,10 @@ In assignments, each value must be <a href="#Assignability">assignable</a> to the type of the operand to which it is assigned. If an untyped <a href="#Constants">constant</a> is assigned to a variable of interface type, the constant is <a href="#Conversions">converted</a> -to type <code>bool</code>, <code>int</code>, <code>float64</code>, +to type <code>bool</code>, <code>rune</code>, <code>int</code>, <code>float64</code>, <code>complex128</code> or <code>string</code> -respectively, depending on whether the value is a boolean, integer, floating-point, -complex, or string constant. +respectively, depending on whether the value is a +boolean, character, integer, floating-point, complex, or string constant. </p> @@ -3887,7 +4041,8 @@ TypeList = Type { "," Type } . <p> The TypeSwitchGuard may include a <a href="#Short_variable_declarations">short variable declaration</a>. -When that form is used, the variable is declared in each clause. +When that form is used, the variable is declared at the beginning of +the <a href="#Blocks">implicit block</a> in each clause. In clauses with a case listing exactly one type, the variable has that type; otherwise, the variable has the type of the expression in the TypeSwitchGuard. @@ -3930,16 +4085,16 @@ could be rewritten: v := x // x is evaluated exactly once if v == nil { printString("x is nil") -} else if i, is_int := v.(int); is_int { +} else if i, isInt := v.(int); isInt { printInt(i) // i is an int -} else if i, is_float64 := v.(float64); is_float64 { +} else if i, isFloat64 := v.(float64); isFloat64 { printFloat64(i) // i is a float64 -} else if i, is_func := v.(func(int) float64); is_func { +} else if i, isFunc := v.(func(int) float64); isFunc { printFunction(i) // i is a function } else { - i1, is_bool := v.(bool) - i2, is_string := v.(string) - if is_bool || is_string { + i1, isBool := v.(bool) + i2, isString := v.(string) + if isBool || isString { i := v printString("type is bool or string") // i is an interface{} } else { @@ -4053,7 +4208,7 @@ For each iteration, iteration values are produced as follows: Range expression 1st value 2nd value (if 2nd variable is present) array or slice a [n]E, *[n]E, or []E index i int a[i] E -string s string type index i int see below int +string s string type index i int see below rune map m map[K]V key k K m[k] V channel c chan E element e E </pre> @@ -4071,7 +4226,7 @@ or slice itself. For a <code>nil</code> slice, the number of iterations is 0. For a string value, the "range" clause iterates over the Unicode code points in the string starting at byte index 0. On successive iterations, the index value will be the index of the first byte of successive UTF-8-encoded code points in the string, -and the second value, of type <code>int</code>, will be the value of +and the second value, of type <code>rune</code>, will be the value of the corresponding code point. If the iteration encounters an invalid UTF-8 sequence, the second value will be <code>0xFFFD</code>, the Unicode replacement character, and the next iteration will advance @@ -4079,7 +4234,8 @@ a single byte in the string. </li> <li> -The iteration order over maps is not specified. +The iteration order over maps is not specified +and is not guaranteed to be the same from one iteration to the next. If map entries that have not yet been reached are deleted during iteration, the corresponding iteration values will not be produced. If map entries are inserted during iteration, the behavior is implementation-dependent, but the @@ -4100,7 +4256,9 @@ iteration variables as in an <a href="#Assignments">assignment statement</a>. </p> <p> -The iteration variables may be declared by the "range" clause (<code>:=</code>). +The iteration variables may be declared by the "range" clause using a form of +<a href="#Short_variable_declarations">short variable declaration</a> +(<code>:=</code>). In this case their types are set to the types of the respective iteration values and their <a href="#Declarations_and_scope">scope</a> ends at the end of the "for" statement; they are re-used in each iteration. @@ -4155,9 +4313,17 @@ GoStmt = "go" Expression . </pre> <p> -The expression must be a call, and +The expression must be a call. +The function value and parameters are +<a href="#Calls">evaluated as usual</a> +in the calling goroutine, but unlike with a regular call, program execution does not wait for the invoked function to complete. +Instead, the function begins executing independently +in a new goroutine. +When the function terminates, its goroutine also terminates. +If the function has any return values, they are discarded when the +function completes. </p> <pre> @@ -4208,7 +4374,7 @@ effects in that evaluation will occur for all the communications in the "select" statement. </p> <p> -If multiple cases can proceed, a pseudo-random fair choice is made to decide +If multiple cases can proceed, a uniform pseudo-random choice is made to decide which single communication will execute. <p> The receive case may declare one or two new variables using a @@ -4240,7 +4406,7 @@ for { // send random sequence of bits to c } } -select { } // block forever +select {} // block forever </pre> @@ -4260,7 +4426,7 @@ In a function without a result type, a "return" statement must not specify any result values. </p> <pre> -func no_result() { +func noResult() { return } </pre> @@ -4276,11 +4442,11 @@ type: and <a href="#Assignability">assignable</a> to the corresponding element of the function's result type. <pre> -func simple_f() int { +func simpleF() int { return 2 } -func complex_f1() (re float64, im float64) { +func complexF1() (re float64, im float64) { return -7.0, -4.0 } </pre> @@ -4292,8 +4458,8 @@ func complex_f1() (re float64, im float64) { "return" statement listing these variables, at which point the rules of the previous case apply. <pre> -func complex_f2() (re float64, im float64) { - return complex_f1() +func complexF2() (re float64, im float64) { + return complexF1() } </pre> </li> @@ -4303,16 +4469,16 @@ func complex_f2() (re float64, im float64) { and the function may assign values to them as necessary. The "return" statement returns the values of these variables. <pre> -func complex_f3() (re float64, im float64) { +func complexF3() (re float64, im float64) { re = 7.0 im = 4.0 return } -func (devnull) Write(p []byte) (n int, _ os.Error) { +func (devnull) Write(p []byte) (n int, _ error) { n = len(p) return -} +} </pre> </li> </ol> @@ -4325,8 +4491,6 @@ Regardless of how they are declared, all the result values are initialized to th <p> <span class="alert"> TODO: Define when return is required.<br /> -TODO: Language about result parameters needs to go into a section on - function/method invocation<br /> </span> </p> --> @@ -4427,7 +4591,7 @@ L1: </pre> <p> -is erroneous because the label <code>L1</code> is inside +is erroneous because the label <code>L1</code> is inside the "for" statement's block but the <code>goto</code> is not. </p> @@ -4459,9 +4623,11 @@ DeferStmt = "defer" Expression . <p> The expression must be a function or method call. Each time the "defer" statement -executes, the parameters to the function call are evaluated and saved anew but the -function is not invoked. -Deferred function calls are executed in LIFO order +executes, the function value and parameters to the call are +<a href="#Calls">evaluated as usual</a> +and saved anew but the +actual function is not invoked. +Instead, deferred calls are executed in LIFO order immediately before the surrounding function returns, after the return values, if any, have been evaluated, but before they are returned to the caller. For instance, if the deferred function is @@ -4469,6 +4635,8 @@ a <a href="#Function_literals">function literal</a> and the surrounding function has <a href="#Function_types">named result parameters</a> that are in scope within the literal, the deferred function may access and modify the result parameters before they are returned. +If the deferred function has any return values, they are discarded when +the function completes. </p> <pre> @@ -4513,12 +4681,13 @@ BuiltinArgs = Type [ "," ExpressionList ] | ExpressionList . <p> For a channel <code>c</code>, the built-in function <code>close(c)</code> -marks the channel as unable to accept more values through a send operation; -sending to or closing a closed channel causes a <a href="#Run_time_panics">run-time panic</a>. +records that no more values will be sent on the channel. +It is an error if <code>c</code> is a receive-only channel. +Sending to or closing a closed channel causes a <a href="#Run_time_panics">run-time panic</a>. +Closing the nil channel also causes a <a href="#Run_time_panics">run-time panic</a>. After calling <code>close</code>, and after any previously sent values have been received, receive operations will return the zero value for the channel's type without blocking. - The multi-valued <a href="#Receive_operator">receive operation</a> returns a received value along with an indication of whether the channel is closed. </p> @@ -4636,10 +4805,10 @@ is negative or larger than <code>m</code>, or if <code>n</code> or </p> <pre> -s := make([]int, 10, 100) // slice with len(s) == 10, cap(s) == 100 -s := make([]int, 10) // slice with len(s) == cap(s) == 10 -c := make(chan int, 10) // channel with a buffer size of 10 -m := make(map[string] int, 100) // map with initial space for 100 elements +s := make([]int, 10, 100) // slice with len(s) == 10, cap(s) == 100 +s := make([]int, 10) // slice with len(s) == cap(s) == 10 +c := make(chan int, 10) // channel with a buffer size of 10 +m := make(map[string]int, 100) // map with initial space for 100 elements </pre> @@ -4658,6 +4827,10 @@ The values <code>x</code> are passed to a parameter of type <code>...T</code> where <code>T</code> is the <a href="#Slice_types">element type</a> of <code>S</code> and the respective <a href="#Passing_arguments_to_..._parameters">parameter passing rules</a> apply. +As a special case, <code>append</code> also accepts a first argument +assignable to type <code>[]byte</code> with a second argument of +string type followed by <code>...</code>. This form appends the +bytes of the string. </p> <pre class="grammar"> @@ -4668,7 +4841,7 @@ append(s S, x ...T) S // T is the element type of S If the capacity of <code>s</code> is not large enough to fit the additional values, <code>append</code> allocates a new, sufficiently large slice that fits both the existing slice elements and the additional values. Thus, the returned -slice may refer to a different underlying array. +slice may refer to a different underlying array. </p> <pre> @@ -4679,6 +4852,9 @@ s3 := append(s2, s0...) // append a slice s3 == []int{0, 0, 2, 3 var t []interface{} t = append(t, 42, 3.1415, "foo") t == []interface{}{42, 3.1415, "foo"} + +var b []byte +b = append(b, "bar"...) // append string contents b == []byte{'b', 'a', 'r' } </pre> <p> @@ -4712,7 +4888,28 @@ n2 := copy(s, s[2:]) // n2 == 4, s == []int{2, 3, 4, 5, 4, 5} n3 := copy(b, "Hello, World!") // n3 == 5, b == []byte("Hello") </pre> -<h3 id="Complex_numbers">Assembling and disassembling complex numbers</h3> + +<h3 id="Deletion_of_map_elements">Deletion of map elements</h3> + +<p> +The built-in function <code>delete</code> removes the element with key +<code>k</code> from a <a href="#Map_types">map</a> <code>m</code>. The +type of <code>k</code> must be <a href="#Assignability">assignable</a> +to the key type of <code>m</code>. +</p> + +<pre class="grammar"> +delete(m, k) // remove element m[k] from map m +</pre> + +<p> +If the element <code>m[k]</code> does not exist, <code>delete</code> is +a no-op. Calling <code>delete</code> with a nil map causes a +<a href="#Run_time_panics">run-time panic</a>. +</p> + + +<h3 id="Complex_numbers">Manipulating complex numbers</h3> <p> Three functions assemble and disassemble complex numbers. @@ -4758,7 +4955,7 @@ var rl = real(c64) // float32 <p> Two built-in functions, <code>panic</code> and <code>recover</code>, assist in reporting and handling <a href="#Run_time_panics">run-time panics</a> -and program-defined error conditions. +and program-defined error conditions. </p> <pre class="grammar"> @@ -4808,7 +5005,7 @@ run-time panics raised by <code>g</code>. <pre> func protect(g func()) { defer func() { - log.Println("done") // Println executes normally even in there is a panic + log.Println("done") // Println executes normally even if there is a panic if x := recover(); x != nil { log.Printf("run time panic: %v", x) } @@ -4888,11 +5085,12 @@ An implementation may require that all source files for a package inhabit the sa <h3 id="Import_declarations">Import declarations</h3> <p> -An import declaration states that the source file containing the -declaration uses identifiers -<a href="#Exported_identifiers">exported</a> by the <i>imported</i> -package and enables access to them. The import names an -identifier (PackageName) to be used for access and an ImportPath +An import declaration states that the source file containing the declaration +depends on functionality of the <i>imported</i> package +(<a href="#Program_initialization_and_execution">§Program initialization and execution</a>) +and it enables access to <a href="#Exported_identifiers">exported</a> identifiers +of that package. +The import names an identifier (PackageName) to be used for access and an ImportPath that specifies the package to be imported. </p> @@ -4904,13 +5102,14 @@ ImportPath = string_lit . <p> The PackageName is used in <a href="#Qualified_identifiers">qualified identifiers</a> -to access the exported identifiers of the package within the importing source file. +to access exported identifiers of the package within the importing source file. It is declared in the <a href="#Blocks">file block</a>. If the PackageName is omitted, it defaults to the identifier specified in the <a href="#Package_clause">package clause</a> of the imported package. If an explicit period (<code>.</code>) appears instead of a name, all the -package's exported identifiers will be declared in the current file's -file block and can be accessed without a qualifier. +package's exported identifiers declared in that package's +<a href="#Blocks">package block</a> will be declared in the importing source +file's file block and can be accessed without a qualifier. </p> <p> @@ -4920,6 +5119,16 @@ package and may be relative to a repository of installed packages. </p> <p> +Implementation restriction: A compiler may restrict ImportPaths to +non-empty strings using only characters belonging to +<a href="http://www.unicode.org/versions/Unicode6.0.0/">Unicode's</a> +L, M, N, P, and S general categories (the Graphic characters without +spaces) and may also exclude the characters +<code>!"#$%&'()*,:;<=>?[\]^`{|}</code> +and the Unicode replacement character U+FFFD. +</p> + +<p> Assume we have compiled a package containing the package clause <code>package math</code>, which exports function <code>Sin</code>, and installed the compiled package in the file identified by @@ -4972,7 +5181,7 @@ func generate(ch chan<- int) { // Copy the values from channel 'src' to channel 'dst', // removing those divisible by 'prime'. func filter(src <-chan int, dst chan<- int, prime int) { - for i := range src { // Loop over values received from 'src'. + for i := range src { // Loop over values received from 'src'. if i%prime != 0 { dst <- i // Send 'i' to channel 'dst'. } @@ -5084,12 +5293,6 @@ unspecified results if <code>A</code>'s initializer calls a function defined in another package that refers to <code>B</code>. </p> <p> -Initialization code may contain "go" statements, but the functions -they invoke do not begin execution until initialization of the entire -program is complete. Therefore, all initialization code is run in a single -goroutine. -</p> -<p> An <code>init</code> function cannot be referred to from anywhere in a program. In particular, <code>init</code> cannot be called explicitly, nor can a pointer to <code>init</code> be assigned to a function variable. @@ -5108,7 +5311,7 @@ A complete program is created by linking a single, unimported package called the <i>main package</i> with all the packages it imports, transitively. The main package must have package name <code>main</code> and -declare a function <code>main</code> that takes no +declare a function <code>main</code> that takes no arguments and returns no value. </p> @@ -5119,12 +5322,44 @@ func main() { … } <p> Program execution begins by initializing the main package and then invoking the function <code>main</code>. -</p> -<p> When the function <code>main</code> returns, the program exits. It does not wait for other (non-<code>main</code>) goroutines to complete. </p> +<p> +Package initialization—variable initialization and the invocation of +<code>init</code> functions—happens in a single goroutine, +sequentially, one package at a time. +An <code>init</code> function may launch other goroutines, which can run +concurrently with the initialization code. However, initialization +always sequences +the <code>init</code> functions: it will not start the next +<code>init</code> until +the previous one has returned. +</p> + +<h2 id="Errors">Errors</h2> + +<p> +The predeclared type <code>error</code> is defined as +</p> + +<pre> +type error interface { + Error() string +} +</pre> + +<p> +It is the conventional interface for representing an error condition, +with the nil value representing no error. +For instance, a function to read data from a file might be defined: +</p> + +<pre> +func Read(f *File, b []byte) (n int, err error) +</pre> + <h2 id="Run_time_panics">Run-time panics</h2> <p> @@ -5132,18 +5367,18 @@ Execution errors such as attempting to index an array out of bounds trigger a <i>run-time panic</i> equivalent to a call of the built-in function <a href="#Handling_panics"><code>panic</code></a> with a value of the implementation-defined interface type <code>runtime.Error</code>. -That type defines at least the method -<code>String() string</code>. The exact error values that -represent distinct run-time error conditions are unspecified, -at least for now. +That type satisfies the predeclared interface type +<a href="#Errors"><code>error</code></a>. +The exact error values that +represent distinct run-time error conditions are unspecified. </p> <pre> package runtime type Error interface { - String() string - // and perhaps others + error + // and perhaps other methods } </pre> @@ -5168,14 +5403,10 @@ type Pointer *ArbitraryType func Alignof(variable ArbitraryType) uintptr func Offsetof(selector ArbitraryType) uinptr func Sizeof(variable ArbitraryType) uintptr - -func Reflect(val interface{}) (typ runtime.Type, addr uintptr) -func Typeof(val interface{}) (typ interface{}) -func Unreflect(typ runtime.Type, addr uintptr) interface{} </pre> <p> -Any pointer or value of type <code>uintptr</code> can be converted into +Any pointer or value of <a href="#Types">underlying type</a> <code>uintptr</code> can be converted into a <code>Pointer</code> and vice versa. </p> <p> @@ -5211,23 +5442,6 @@ Calls to <code>Alignof</code>, <code>Offsetof</code>, and <code>Sizeof</code> are compile-time constant expressions of type <code>uintptr</code>. </p> <p> -The functions <code>unsafe.Typeof</code>, -<code>unsafe.Reflect</code>, -and <code>unsafe.Unreflect</code> allow access at run time to the dynamic -types and values stored in interfaces. -<code>Typeof</code> returns a representation of -<code>val</code>'s -dynamic type as a <code>runtime.Type</code>. -<code>Reflect</code> allocates a copy of -<code>val</code>'s dynamic -value and returns both the type and the address of the copy. -<code>Unreflect</code> inverts <code>Reflect</code>, -creating an -interface value from a type and address. -The <a href="/pkg/reflect/"><code>reflect</code> package</a> built on these primitives -provides a safe, more convenient way to inspect interface values. -</p> - <h3 id="Size_and_alignment_guarantees">Size and alignment guarantees</h3> @@ -5261,12 +5475,6 @@ The following minimal alignment properties are guaranteed: </li> </ol> -<span class="alert"> -<h2 id="Implementation_differences">Implementation differences - TODO</h2> -<ul> - <li><code>len(a)</code> is only a constant if <code>a</code> is a (qualified) identifier denoting an array or pointer to an array.</li> - <li><code>nil</code> maps are not treated like empty maps.</li> - <li>Trying to send/receive from a <code>nil</code> channel causes a run-time panic.</li> - <li><code>unsafe.Alignof</code>, <code>unsafe.Offsetof</code>, and <code>unsafe.Sizeof</code> return an <code>int</code>.</li> -</ul> -</span> +<p> +A struct or array type has size zero if it contains no fields (or elements, respectively) that have a size greater than zero. Two distinct zero-size variables may have the same address in memory. +</p> diff --git a/doc/go_tutorial.html b/doc/go_tutorial.html deleted file mode 100644 index 8f6e07b06..000000000 --- a/doc/go_tutorial.html +++ /dev/null @@ -1,1454 +0,0 @@ -<!-- A Tutorial for the Go Programming Language --> -<h2>Introduction</h2> -<p> -This document is a tutorial introduction to the basics of the Go programming -language, intended for programmers familiar with C or C++. It is not a comprehensive -guide to the language; at the moment the document closest to that is the -<a href='/doc/go_spec.html'>language specification</a>. -After you've read this tutorial, you should look at -<a href='/doc/effective_go.html'>Effective Go</a>, -which digs deeper into how the language is used and -talks about the style and idioms of programming in Go. -Also, slides from a 3-day course about Go are available. -They provide some background and a lot of examples: -<a href='/doc/GoCourseDay1.pdf'>Day 1</a>, -<a href='/doc/GoCourseDay2.pdf'>Day 2</a>, -<a href='/doc/GoCourseDay3.pdf'>Day 3</a>. -<p> -The presentation here proceeds through a series of modest programs to illustrate -key features of the language. All the programs work (at time of writing) and are -checked into the repository in the directory <a href='/doc/progs'><code>/doc/progs/</code></a>. -<p> -<h2>Hello, World</h2> -<p> -Let's start in the usual way: -<p> -<pre><!--{{code "progs/helloworld.go" `/package/` "$"}} --->package main - -import fmt "fmt" // Package implementing formatted I/O. - -func main() { - fmt.Printf("Hello, world; or Καλημέρα κόσμε; or こんにちは 世界\n") -} -</pre> -<p> -Every Go source file declares, using a <code>package</code> statement, which package it's part of. -It may also import other packages to use their facilities. -This program imports the package <code>fmt</code> to gain access to -our old, now capitalized and package-qualified, friend, <code>fmt.Printf</code>. -<p> -Functions are introduced with the <code>func</code> keyword. -The <code>main</code> package's <code>main</code> function is where the program starts running (after -any initialization). -<p> -String constants can contain Unicode characters, encoded in UTF-8. -(In fact, Go source files are defined to be encoded in UTF-8.) -<p> -The comment convention is the same as in C++: -<p> -<pre> -/* ... */ -// ... -</pre> -<p> -Later we'll have much more to say about printing. -<p> -<h2>Semicolons</h2> -<p> -You might have noticed that our program has no semicolons. In Go -code, the only place you typically see semicolons is separating the -clauses of <code>for</code> loops and the like; they are not necessary after -every statement. -<p> -In fact, what happens is that the formal language uses semicolons, -much as in C or Java, but they are inserted automatically -at the end of every line that looks like the end of a statement. You -don't need to type them yourself. -<p> -For details about how this is done you can see the language -specification, but in practice all you need to know is that you -never need to put a semicolon at the end of a line. (You can put -them in if you want to write multiple statements per line.) As an -extra help, you can also leave out a semicolon immediately before -a closing brace. -<p> -This approach makes for clean-looking, semicolon-free code. The -one surprise is that it's important to put the opening -brace of a construct such as an <code>if</code> statement on the same line as -the <code>if</code>; if you don't, there are situations that may not compile -or may give the wrong result. The language forces the brace style -to some extent. -<p> -<h2>Compiling</h2> -<p> -Go is a compiled language. At the moment there are two compilers. -<code>Gccgo</code> is a Go compiler that uses the GCC back end. There is also a -suite of compilers with different (and odd) names for each architecture: -<code>6g</code> for the 64-bit x86, <code>8g</code> for the 32-bit x86, and more. These -compilers run significantly faster but generate less efficient code -than <code>gccgo</code>. At the time of writing (late 2009), they also have -a more robust run-time system although <code>gccgo</code> is catching up. -<p> -Here's how to compile and run our program. With <code>6g</code>, say, -<p> -<pre> -$ 6g helloworld.go # compile; object goes into helloworld.6 -$ 6l helloworld.6 # link; output goes into 6.out -$ ./6.out -Hello, world; or Καλημέρα κόσμε; or こんにちは 世界 -$ -</pre> -<p> -With <code>gccgo</code> it looks a little more traditional. -<p> -<pre> -$ gccgo helloworld.go -$ a.out -Hello, world; or Καλημέρα κόσμε; or こんにちは 世界 -$ -</pre> -<p> -<h2>Echo</h2> -<p> -Next up, here's a version of the Unix utility <code>echo(1)</code>: -<p> -<pre><!--{{code "progs/echo.go" `/package/` "$"}} --->package main - -import ( - "os" - "flag" // command line option parser -) - -var omitNewline = flag.Bool("n", false, "don't print final newline") - -const ( - Space = " " - Newline = "\n" -) - -func main() { - flag.Parse() // Scans the arg list and sets up flags - var s string = "" - for i := 0; i < flag.NArg(); i++ { - if i > 0 { - s += Space - } - s += flag.Arg(i) - } - if !*omitNewline { - s += Newline - } - os.Stdout.WriteString(s) -} -</pre> -<p> -This program is small but it's doing a number of new things. In the last example, -we saw <code>func</code> introduce a function. The keywords <code>var</code>, <code>const</code>, and <code>type</code> -(not used yet) also introduce declarations, as does <code>import</code>. -Notice that we can group declarations of the same sort into -parenthesized lists, one item per line, as in the <code>import</code> and <code>const</code> clauses here. -But it's not necessary to do so; we could have said -<p> -<pre> -const Space = " " -const Newline = "\n" -</pre> -<p> -This program imports the <code>"os"</code> package to access its <code>Stdout</code> variable, of type -<code>*os.File</code>. The <code>import</code> statement is actually a declaration: in its general form, -as used in our ``hello world'' program, -it names the identifier (<code>fmt</code>) -that will be used to access members of the package imported from the file (<code>"fmt"</code>), -found in the current directory or in a standard location. -In this program, though, we've dropped the explicit name from the imports; by default, -packages are imported using the name defined by the imported package, -which by convention is of course the file name itself. Our ``hello world'' program -could have said just <code>import "fmt"</code>. -<p> -You can specify your -own import names if you want but it's only necessary if you need to resolve -a naming conflict. -<p> -Given <code>os.Stdout</code> we can use its <code>WriteString</code> method to print the string. -<p> -After importing the <code>flag</code> package, we use a <code>var</code> declaration -to create and initialize a global variable, called <code>omitNewline</code>, -to hold the value of echo's <code>-n</code> flag. -The variable has type <code>*bool</code>, pointer to <code>bool</code>. -<p> -In <code>main.main</code>, we parse the arguments (the call to <code>flag.Parse</code>) and then create a local -string variable with which to build the output. -<p> -The declaration statement has the form -<p> -<pre> -var s string = "" -</pre> -<p> -This is the <code>var</code> keyword, followed by the name of the variable, followed by -its type, followed by an equals sign and an initial value for the variable. -<p> -Go tries to be terse, and this declaration could be shortened. Since the -string constant is of type string, we don't have to tell the compiler that. -We could write -<p> -<pre> -var s = "" -</pre> -<p> -or we could go even shorter and write the idiom -<p> -<pre> -s := "" -</pre> -<p> -The <code>:=</code> operator is used a lot in Go to represent an initializing declaration. -There's one in the <code>for</code> clause on the next line: -<p> -<pre><!--{{code "progs/echo.go" `/for/`}} ---> for i := 0; i < flag.NArg(); i++ { -</pre> -<p> -The <code>flag</code> package has parsed the arguments and left the non-flag arguments -in a list that can be iterated over in the obvious way. -<p> -The Go <code>for</code> statement differs from that of C in a number of ways. First, -it's the only looping construct; there is no <code>while</code> or <code>do</code>. Second, -there are no parentheses on the clause, but the braces on the body -are mandatory. The same applies to the <code>if</code> and <code>switch</code> statements. -Later examples will show some other ways <code>for</code> can be written. -<p> -The body of the loop builds up the string <code>s</code> by appending (using <code>+=</code>) -the arguments and separating spaces. After the loop, if the <code>-n</code> flag is not -set, the program appends a newline. Finally, it writes the result. -<p> -Notice that <code>main.main</code> is a niladic function with no return type. -It's defined that way. Falling off the end of <code>main.main</code> means -''success''; if you want to signal an erroneous return, call -<p> -<pre> -os.Exit(1) -</pre> -<p> -The <code>os</code> package contains other essentials for getting -started; for instance, <code>os.Args</code> is a slice used by the -<code>flag</code> package to access the command-line arguments. -<p> -<h2>An Interlude about Types</h2> -<p> -Go has some familiar types such as <code>int</code> and <code>uint</code> (unsigned <code>int</code>), which represent -values of the ''appropriate'' size for the machine. It also defines -explicitly-sized types such as <code>int8</code>, <code>float64</code>, and so on, plus -unsigned integer types such as <code>uint</code>, <code>uint32</code>, etc. -These are distinct types; even if <code>int</code> and <code>int32</code> are both 32 bits in size, -they are not the same type. There is also a <code>byte</code> synonym for -<code>uint8</code>, which is the element type for strings. -<p> -Floating-point types are always sized: <code>float32</code> and <code>float64</code>, -plus <code>complex64</code> (two <code>float32s</code>) and <code>complex128</code> -(two <code>float64s</code>). Complex numbers are outside the -scope of this tutorial. -<p> -Speaking of <code>string</code>, that's a built-in type as well. Strings are -<i>immutable values</i>—they are not just arrays of <code>byte</code> values. -Once you've built a string <i>value</i>, you can't change it, although -of course you can change a string <i>variable</i> simply by -reassigning it. This snippet from <code>strings.go</code> is legal code: -<p> -<pre><!--{{code "progs/strings.go" `/hello/` `/ciao/`}} ---> s := "hello" - if s[1] != 'e' { - os.Exit(1) - } - s = "good bye" - var p *string = &s - *p = "ciao" -</pre> -<p> -However the following statements are illegal because they would modify -a <code>string</code> value: -<p> -<pre> -s[0] = 'x' -(*p)[1] = 'y' -</pre> -<p> -In C++ terms, Go strings are a bit like <code>const strings</code>, while pointers -to strings are analogous to <code>const string</code> references. -<p> -Yes, there are pointers. However, Go simplifies their use a little; -read on. -<p> -Arrays are declared like this: -<p> -<pre> -var arrayOfInt [10]int -</pre> -<p> -Arrays, like strings, are values, but they are mutable. This differs -from C, in which <code>arrayOfInt</code> would be usable as a pointer to <code>int</code>. -In Go, since arrays are values, it's meaningful (and useful) to talk -about pointers to arrays. -<p> -The size of the array is part of its type; however, one can declare -a <i>slice</i> variable to hold a reference to any array, of any size, -with the same element type. -A <i>slice -expression</i> has the form <code>a[low : high]</code>, representing -the internal array indexed from <code>low</code> through <code>high-1</code>; the resulting -slice is indexed from <code>0</code> through <code>high-low-1</code>. -In short, slices look a lot like arrays but with -no explicit size (<code>[]</code> vs. <code>[10]</code>) and they reference a segment of -an underlying, usually anonymous, regular array. Multiple slices -can share data if they represent pieces of the same array; -multiple arrays can never share data. -<p> -Slices are much more common in Go programs than -regular arrays; they're more flexible, have reference semantics, -and are efficient. What they lack is the precise control of storage -layout of a regular array; if you want to have a hundred elements -of an array stored within your structure, you should use a regular -array. To create one, use a compound value <i>constructor</i>—an -expression formed -from a type followed by a brace-bounded expression like this: -<p> -<pre> -[3]int{1,2,3} -</pre> -<p> -In this case the constructor builds an array of 3 <code>ints</code>. -<p> -When passing an array to a function, you almost always want -to declare the formal parameter to be a slice. When you call -the function, slice the array to create -(efficiently) a slice reference and pass that. -By default, the lower and upper bounds of a slice match the -ends of the existing object, so the concise notation <code>[:]</code> -will slice the whole array. -<p> -Using slices one can write this function (from <code>sum.go</code>): -<p> -<pre><!--{{code "progs/sum.go" `/sum/` `/^}/`}} --->func sum(a []int) int { // returns an int - s := 0 - for i := 0; i < len(a); i++ { - s += a[i] - } - return s -} -</pre> -<p> -Note how the return type (<code>int</code>) is defined for <code>sum</code> by stating it -after the parameter list. -<p> -To call the function, we slice the array. This intricate call (we'll show -a simpler way in a moment) constructs -an array and slices it: -<p> -<pre> -s := sum([3]int{1,2,3}[:]) -</pre> -<p> -If you are creating a regular array but want the compiler to count the -elements for you, use <code>...</code> as the array size: -<p> -<pre> -s := sum([...]int{1,2,3}[:]) -</pre> -<p> -That's fussier than necessary, though. -In practice, unless you're meticulous about storage layout within a -data structure, a slice itself—using empty brackets with no size—is all you need: -<p> -<pre> -s := sum([]int{1,2,3}) -</pre> -<p> -There are also maps, which you can initialize like this: -<p> -<pre> -m := map[string]int{"one":1 , "two":2} -</pre> -<p> -The built-in function <code>len</code>, which returns number of elements, -makes its first appearance in <code>sum</code>. It works on strings, arrays, -slices, maps, and channels. -<p> -By the way, another thing that works on strings, arrays, slices, maps -and channels is the <code>range</code> clause on <code>for</code> loops. Instead of writing -<p> -<pre> -for i := 0; i < len(a); i++ { ... } -</pre> -<p> -to loop over the elements of a slice (or map or ...) , we could write -<p> -<pre> -for i, v := range a { ... } -</pre> -<p> -This assigns <code>i</code> to the index and <code>v</code> to the value of the successive -elements of the target of the range. See -<a href='/doc/effective_go.html'>Effective Go</a> -for more examples of its use. -<p> -<p> -<h2>An Interlude about Allocation</h2> -<p> -Most types in Go are values. If you have an <code>int</code> or a <code>struct</code> -or an array, assignment -copies the contents of the object. -To allocate a new variable, use the built-in function <code>new</code>, which -returns a pointer to the allocated storage. -<p> -<pre> -type T struct { a, b int } -var t *T = new(T) -</pre> -<p> -or the more idiomatic -<p> -<pre> -t := new(T) -</pre> -<p> -Some types—maps, slices, and channels (see below)—have reference semantics. -If you're holding a slice or a map and you modify its contents, other variables -referencing the same underlying data will see the modification. For these three -types you want to use the built-in function <code>make</code>: -<p> -<pre> -m := make(map[string]int) -</pre> -<p> -This statement initializes a new map ready to store entries. -If you just declare the map, as in -<p> -<pre> -var m map[string]int -</pre> -<p> -it creates a <code>nil</code> reference that cannot hold anything. To use the map, -you must first initialize the reference using <code>make</code> or by assignment from an -existing map. -<p> -Note that <code>new(T)</code> returns type <code>*T</code> while <code>make(T)</code> returns type -<code>T</code>. If you (mistakenly) allocate a reference object with <code>new</code> rather than <code>make</code>, -you receive a pointer to a nil reference, equivalent to -declaring an uninitialized variable and taking its address. -<p> -<h2>An Interlude about Constants</h2> -<p> -Although integers come in lots of sizes in Go, integer constants do not. -There are no constants like <code>0LL</code> or <code>0x0UL</code>. Instead, integer -constants are evaluated as large-precision values that -can overflow only when they are assigned to an integer variable with -too little precision to represent the value. -<p> -<pre> -const hardEight = (1 << 100) >> 97 // legal -</pre> -<p> -There are nuances that deserve redirection to the legalese of the -language specification but here are some illustrative examples: -<p> -<pre> -var a uint64 = 0 // a has type uint64, value 0 -a := uint64(0) // equivalent; uses a "conversion" -i := 0x1234 // i gets default type: int -var j int = 1e6 // legal - 1000000 is representable in an int -x := 1.5 // a float64, the default type for floating constants -i3div2 := 3/2 // integer division - result is 1 -f3div2 := 3./2. // floating-point division - result is 1.5 -</pre> -<p> -Conversions only work for simple cases such as converting <code>ints</code> of one -sign or size to another and between integers and floating-point numbers, -plus a couple of other instances outside the scope of a tutorial. -There are no automatic numeric conversions of any kind in Go, -other than that of making constants have concrete size and type when -assigned to a variable. -<p> -<h2>An I/O Package</h2> -<p> -Next we'll look at a simple package for doing file I/O with an -open/close/read/write interface. Here's the start of <code>file.go</code>: -<p> -<pre><!--{{code "progs/file.go" `/package/` `/^}/`}} --->package file - -import ( - "os" - "syscall" -) - -type File struct { - fd int // file descriptor number - name string // file name at Open time -} -</pre> -<p> -The first few lines declare the name of the -package—<code>file</code>—and then import two packages. The <code>os</code> -package hides the differences -between various operating systems to give a consistent view of files and -so on; here we're going to use its error handling utilities -and reproduce the rudiments of its file I/O. -<p> -The other item is the low-level, external <code>syscall</code> package, which provides -a primitive interface to the underlying operating system's calls. -<p> -Next is a type definition: the <code>type</code> keyword introduces a type declaration, -in this case a data structure called <code>File</code>. -To make things a little more interesting, our <code>File</code> includes the name of the file -that the file descriptor refers to. -<p> -Because <code>File</code> starts with a capital letter, the type is available outside the package, -that is, by users of the package. In Go the rule about visibility of information is -simple: if a name (of a top-level type, function, method, constant or variable, or of -a structure field or method) is capitalized, users of the package may see it. Otherwise, the -name and hence the thing being named is visible only inside the package in which -it is declared. This is more than a convention; the rule is enforced by the compiler. -In Go, the term for publicly visible names is ''exported''. -<p> -In the case of <code>File</code>, all its fields are lower case and so invisible to users, but we -will soon give it some exported, upper-case methods. -<p> -First, though, here is a factory to create a <code>File</code>: -<p> -<pre><!--{{code "progs/file.go" `/newFile/` `/^}/`}} --->func newFile(fd int, name string) *File { - if fd < 0 { - return nil - } - return &File{fd, name} -} -</pre> -<p> -This returns a pointer to a new <code>File</code> structure with the file descriptor and name -filled in. This code uses Go's notion of a ''composite literal'', analogous to -the ones used to build maps and arrays, to construct a new heap-allocated -object. We could write -<p> -<pre> -n := new(File) -n.fd = fd -n.name = name -return n -</pre> -<p> -but for simple structures like <code>File</code> it's easier to return the address of a -composite literal, as is done here in the <code>return</code> statement from <code>newFile</code>. -<p> -We can use the factory to construct some familiar, exported variables of type <code>*File</code>: -<p> -<pre><!--{{code "progs/file.go" `/var/` `/^\)/`}} --->var ( - Stdin = newFile(syscall.Stdin, "/dev/stdin") - Stdout = newFile(syscall.Stdout, "/dev/stdout") - Stderr = newFile(syscall.Stderr, "/dev/stderr") -) -</pre> -<p> -The <code>newFile</code> function was not exported because it's internal. The proper, -exported factory to use is <code>OpenFile</code> (we'll explain that name in a moment): -<p> -<pre><!--{{code "progs/file.go" `/func.OpenFile/` `/^}/`}} --->func OpenFile(name string, mode int, perm uint32) (file *File, err os.Error) { - r, e := syscall.Open(name, mode, perm) - if e != 0 { - err = os.Errno(e) - } - return newFile(r, name), err -} -</pre> -<p> -There are a number of new things in these few lines. First, <code>OpenFile</code> returns -multiple values, a <code>File</code> and an error (more about errors in a moment). -We declare the -multi-value return as a parenthesized list of declarations; syntactically -they look just like a second parameter list. The function -<code>syscall.Open</code> -also has a multi-value return, which we can grab with the multi-variable -declaration on the first line; it declares <code>r</code> and <code>e</code> to hold the two values, -both of type <code>int</code> (although you'd have to look at the <code>syscall</code> package -to see that). Finally, <code>OpenFile</code> returns two values: a pointer to the new <code>File</code> -and the error. If <code>syscall.Open</code> fails, the file descriptor <code>r</code> will -be negative and <code>newFile</code> will return <code>nil</code>. -<p> -About those errors: The <code>os</code> library includes a general notion of an error. -It's a good idea to use its facility in your own interfaces, as we do here, for -consistent error handling throughout Go code. In <code>Open</code> we use a -conversion to translate Unix's integer <code>errno</code> value into the integer type -<code>os.Errno</code>, which implements <code>os.Error</code>. -<p> -Why <code>OpenFile</code> and not <code>Open</code>? To mimic Go's <code>os</code> package, which -our exercise is emulating. The <code>os</code> package takes the opportunity -to make the two commonest cases - open for read and create for -write - the simplest, just <code>Open</code> and <code>Create</code>. <code>OpenFile</code> is the -general case, analogous to the Unix system call <code>Open</code>. Here is -the implementation of our <code>Open</code> and <code>Create</code>; they're trivial -wrappers that eliminate common errors by capturing -the tricky standard arguments to open and, especially, to create a file: -<p> -<pre><!--{{code "progs/file.go" `/^const/` `/^}/`}} --->const ( - O_RDONLY = syscall.O_RDONLY - O_RDWR = syscall.O_RDWR - O_CREATE = syscall.O_CREAT - O_TRUNC = syscall.O_TRUNC -) - -func Open(name string) (file *File, err os.Error) { - return OpenFile(name, O_RDONLY, 0) -} -</pre> -<p> -<pre><!--{{code "progs/file.go" `/func.Create/` `/^}/`}} --->func Create(name string) (file *File, err os.Error) { - return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666) -} -</pre> -<p> -Back to our main story. -Now that we can build <code>Files</code>, we can write methods for them. To declare -a method of a type, we define a function to have an explicit receiver -of that type, placed -in parentheses before the function name. Here are some methods for <code>*File</code>, -each of which declares a receiver variable <code>file</code>. -<p> -<pre><!--{{code "progs/file.go" `/Close/` "$"}} --->func (file *File) Close() os.Error { - if file == nil { - return os.EINVAL - } - e := syscall.Close(file.fd) - file.fd = -1 // so it can't be closed again - if e != 0 { - return os.Errno(e) - } - return nil -} - -func (file *File) Read(b []byte) (ret int, err os.Error) { - if file == nil { - return -1, os.EINVAL - } - r, e := syscall.Read(file.fd, b) - if e != 0 { - err = os.Errno(e) - } - return int(r), err -} - -func (file *File) Write(b []byte) (ret int, err os.Error) { - if file == nil { - return -1, os.EINVAL - } - r, e := syscall.Write(file.fd, b) - if e != 0 { - err = os.Errno(e) - } - return int(r), err -} - -func (file *File) String() string { - return file.name -} -</pre> -<p> -There is no implicit <code>this</code> and the receiver variable must be used to access -members of the structure. Methods are not declared within -the <code>struct</code> declaration itself. The <code>struct</code> declaration defines only data members. -In fact, methods can be created for almost any type you name, such as an integer or -array, not just for <code>structs</code>. We'll see an example with arrays later. -<p> -The <code>String</code> method is so called because of a printing convention we'll -describe later. -<p> -The methods use the public variable <code>os.EINVAL</code> to return the (<code>os.Error</code> -version of the) Unix error code <code>EINVAL</code>. The <code>os</code> library defines a standard -set of such error values. -<p> -We can now use our new package: -<p> -<pre><!--{{code "progs/helloworld3.go" `/package/` "$"}} --->package main - -import ( - "./file" - "fmt" - "os" -) - -func main() { - hello := []byte("hello, world\n") - file.Stdout.Write(hello) - f, err := file.Open("/does/not/exist") - if f == nil { - fmt.Printf("can't open file; err=%s\n", err.String()) - os.Exit(1) - } -} -</pre> -<p> -The ''<code>./</code>'' in the import of ''<code>./file</code>'' tells the compiler -to use our own package rather than -something from the directory of installed packages. -(Also, ''<code>file.go</code>'' must be compiled before we can import the -package.) -<p> -Now we can compile and run the program. On Unix, this would be the result: -<p> -<pre> -$ 6g file.go # compile file package -$ 6g helloworld3.go # compile main package -$ 6l -o helloworld3 helloworld3.6 # link - no need to mention "file" -$ helloworld3 -hello, world -can't open file; err=No such file or directory -$ -</pre> -<p> -<h2>Rotting cats</h2> -<p> -Building on the <code>file</code> package, here's a simple version of the Unix utility <code>cat(1)</code>, -<code>progs/cat.go</code>: -<p> -<pre><!--{{code "progs/cat.go" `/package/` "$"}} --->package main - -import ( - "./file" - "flag" - "fmt" - "os" -) - -func cat(f *file.File) { - const NBUF = 512 - var buf [NBUF]byte - for { - switch nr, er := f.Read(buf[:]); true { - case nr < 0: - fmt.Fprintf(os.Stderr, "cat: error reading from %s: %s\n", f.String(), er.String()) - os.Exit(1) - case nr == 0: // EOF - return - case nr > 0: - if nw, ew := file.Stdout.Write(buf[0:nr]); nw != nr { - fmt.Fprintf(os.Stderr, "cat: error writing from %s: %s\n", f.String(), ew.String()) - os.Exit(1) - } - } - } -} - -func main() { - flag.Parse() // Scans the arg list and sets up flags - if flag.NArg() == 0 { - cat(file.Stdin) - } - for i := 0; i < flag.NArg(); i++ { - f, err := file.Open(flag.Arg(i)) - if f == nil { - fmt.Fprintf(os.Stderr, "cat: can't open %s: error %s\n", flag.Arg(i), err) - os.Exit(1) - } - cat(f) - f.Close() - } -} -</pre> -<p> -By now this should be easy to follow, but the <code>switch</code> statement introduces some -new features. Like a <code>for</code> loop, an <code>if</code> or <code>switch</code> can include an -initialization statement. The <code>switch</code> statement in <code>cat</code> uses one to create variables -<code>nr</code> and <code>er</code> to hold the return values from the call to <code>f.Read</code>. (The <code>if</code> a few lines later -has the same idea.) The <code>switch</code> statement is general: it evaluates the cases -from top to bottom looking for the first case that matches the value; the -case expressions don't need to be constants or even integers, as long as -they all have the same type. -<p> -Since the <code>switch</code> value is just <code>true</code>, we could leave it off—as is also -the situation -in a <code>for</code> statement, a missing value means <code>true</code>. In fact, such a <code>switch</code> -is a form of <code>if-else</code> chain. While we're here, it should be mentioned that in -<code>switch</code> statements each <code>case</code> has an implicit <code>break</code>. -<p> -The argument to <code>file.Stdout.Write</code> is created by slicing the array <code>buf</code>. -Slices provide the standard Go way to handle I/O buffers. -<p> -Now let's make a variant of <code>cat</code> that optionally does <code>rot13</code> on its input. -It's easy to do by just processing the bytes, but instead we will exploit -Go's notion of an <i>interface</i>. -<p> -The <code>cat</code> subroutine uses only two methods of <code>f</code>: <code>Read</code> and <code>String</code>, -so let's start by defining an interface that has exactly those two methods. -Here is code from <code>progs/cat_rot13.go</code>: -<p> -<pre><!--{{code "progs/cat_rot13.go" `/type.reader/` `/^}/`}} --->type reader interface { - Read(b []byte) (ret int, err os.Error) - String() string -} -</pre> -<p> -Any type that has the two methods of <code>reader</code>—regardless of whatever -other methods the type may also have—is said to <i>implement</i> the -interface. Since <code>file.File</code> implements these methods, it implements the -<code>reader</code> interface. We could tweak the <code>cat</code> subroutine to accept a <code>reader</code> -instead of a <code>*file.File</code> and it would work just fine, but let's embellish a little -first by writing a second type that implements <code>reader</code>, one that wraps an -existing <code>reader</code> and does <code>rot13</code> on the data. To do this, we just define -the type and implement the methods and with no other bookkeeping, -we have a second implementation of the <code>reader</code> interface. -<p> -<pre><!--{{code "progs/cat_rot13.go" `/type.rotate13/` `/end.of.rotate13/`}} --->type rotate13 struct { - source reader -} - -func newRotate13(source reader) *rotate13 { - return &rotate13{source} -} - -func (r13 *rotate13) Read(b []byte) (ret int, err os.Error) { - r, e := r13.source.Read(b) - for i := 0; i < r; i++ { - b[i] = rot13(b[i]) - } - return r, e -} - -func (r13 *rotate13) String() string { - return r13.source.String() -} -// end of rotate13 implementation -</pre> -<p> -(The <code>rot13</code> function called in <code>Read</code> is trivial and not worth reproducing here.) -<p> -To use the new feature, we define a flag: -<p> -<pre><!--{{code "progs/cat_rot13.go" `/rot13Flag/`}} --->var rot13Flag = flag.Bool("rot13", false, "rot13 the input") -</pre> -<p> -and use it from within a mostly unchanged <code>cat</code> function: -<p> -<pre><!--{{code "progs/cat_rot13.go" `/func.cat/` `/^}/`}} --->func cat(r reader) { - const NBUF = 512 - var buf [NBUF]byte - - if *rot13Flag { - r = newRotate13(r) - } - for { - switch nr, er := r.Read(buf[:]); { - case nr < 0: - fmt.Fprintf(os.Stderr, "cat: error reading from %s: %s\n", r.String(), er.String()) - os.Exit(1) - case nr == 0: // EOF - return - case nr > 0: - nw, ew := file.Stdout.Write(buf[0:nr]) - if nw != nr { - fmt.Fprintf(os.Stderr, "cat: error writing from %s: %s\n", r.String(), ew.String()) - os.Exit(1) - } - } - } -} -</pre> -<p> -(We could also do the wrapping in <code>main</code> and leave <code>cat</code> mostly alone, except -for changing the type of the argument; consider that an exercise.) -The <code>if</code> at the top of <code>cat</code> sets it all up: If the <code>rot13</code> flag is true, wrap the <code>reader</code> -we received into a <code>rotate13</code> and proceed. Note that the interface variables -are values, not pointers: the argument is of type <code>reader</code>, not <code>*reader</code>, -even though under the covers it holds a pointer to a <code>struct</code>. -<p> -Here it is in action: -<p> -<pre> -$ echo abcdefghijklmnopqrstuvwxyz | ./cat -abcdefghijklmnopqrstuvwxyz -$ echo abcdefghijklmnopqrstuvwxyz | ./cat --rot13 -nopqrstuvwxyzabcdefghijklm -$ -</pre> -<p> -Fans of dependency injection may take cheer from how easily interfaces -allow us to substitute the implementation of a file descriptor. -<p> -Interfaces are a distinctive feature of Go. An interface is implemented by a -type if the type implements all the methods declared in the interface. -This means -that a type may implement an arbitrary number of different interfaces. -There is no type hierarchy; things can be much more <i>ad hoc</i>, -as we saw with <code>rot13</code>. The type <code>file.File</code> implements <code>reader</code>; it could also -implement a <code>writer</code>, or any other interface built from its methods that -fits the current situation. Consider the <i>empty interface</i> -<p> -<pre> -type Empty interface {} -</pre> -<p> -<i>Every</i> type implements the empty interface, which makes it -useful for things like containers. -<p> -<h2>Sorting</h2> -<p> -Interfaces provide a simple form of polymorphism. They completely -separate the definition of what an object does from how it does it, allowing -distinct implementations to be represented at different times by the -same interface variable. -<p> -As an example, consider this simple sort algorithm taken from <code>progs/sort.go</code>: -<p> -<pre><!--{{code "progs/sort.go" `/func.Sort/` `/^}/`}} --->func Sort(data Interface) { - for i := 1; i < data.Len(); i++ { - for j := i; j > 0 && data.Less(j, j-1); j-- { - data.Swap(j, j-1) - } - } -} -</pre> -<p> -The code needs only three methods, which we wrap into sort's <code>Interface</code>: -<p> -<pre><!--{{code "progs/sort.go" `/interface/` `/^}/`}} --->type Interface interface { - Len() int - Less(i, j int) bool - Swap(i, j int) -} -</pre> -<p> -We can apply <code>Sort</code> to any type that implements <code>Len</code>, <code>Less</code>, and <code>Swap</code>. -The <code>sort</code> package includes the necessary methods to allow sorting of -arrays of integers, strings, etc.; here's the code for arrays of <code>int</code> -<p> -<pre><!--{{code "progs/sort.go" `/type.*IntSlice/` `/Swap/`}} --->type IntSlice []int - -func (p IntSlice) Len() int { return len(p) } -func (p IntSlice) Less(i, j int) bool { return p[i] < p[j] } -func (p IntSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } -</pre> -<p> -Here we see methods defined for non-<code>struct</code> types. You can define methods -for any type you define and name in your package. -<p> -And now a routine to test it out, from <code>progs/sortmain.go</code>. This -uses a function in the <code>sort</code> package, omitted here for brevity, -to test that the result is sorted. -<p> -<pre><!--{{code "progs/sortmain.go" `/func.ints/` `/^}/`}} --->func ints() { - data := []int{74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586} - a := sort.IntSlice(data) - sort.Sort(a) - if !sort.IsSorted(a) { - panic("fail") - } -} -</pre> -<p> -If we have a new type we want to be able to sort, all we need to do is -to implement the three methods for that type, like this: -<p> -<pre><!--{{code "progs/sortmain.go" `/type.day/` `/Swap/`}} --->type day struct { - num int - shortName string - longName string -} - -type dayArray struct { - data []*day -} - -func (p *dayArray) Len() int { return len(p.data) } -func (p *dayArray) Less(i, j int) bool { return p.data[i].num < p.data[j].num } -func (p *dayArray) Swap(i, j int) { p.data[i], p.data[j] = p.data[j], p.data[i] } -</pre> -<p> -<p> -<h2>Printing</h2> -<p> -The examples of formatted printing so far have been modest. In this section -we'll talk about how formatted I/O can be done well in Go. -<p> -We've seen simple uses of the package <code>fmt</code>, which -implements <code>Printf</code>, <code>Fprintf</code>, and so on. -Within the <code>fmt</code> package, <code>Printf</code> is declared with this signature: -<p> -<pre> -Printf(format string, v ...interface{}) (n int, errno os.Error) -</pre> -<p> -The token <code>...</code> introduces a variable-length argument list that in C would -be handled using the <code>stdarg.h</code> macros. -In Go, variadic functions are passed a slice of the arguments of the -specified type. In <code>Printf</code>'s case, the declaration says <code>...interface{}</code> -so the actual type is a slice of empty interface values, <code>[]interface{}</code>. -<code>Printf</code> can examine the arguments by iterating over the slice -and, for each element, using a type switch or the reflection library -to interpret the value. -It's off topic here but such run-time type analysis -helps explain some of the nice properties of Go's <code>Printf</code>, -due to the ability of <code>Printf</code> to discover the type of its arguments -dynamically. -<p> -For example, in C each format must correspond to the type of its -argument. It's easier in many cases in Go. Instead of <code>%llud</code> you -can just say <code>%d</code>; <code>Printf</code> knows the size and signedness of the -integer and can do the right thing for you. The snippet -<p> -<pre><!--{{code "progs/print.go" 10 11}} ---> var u64 uint64 = 1<<64 - 1 - fmt.Printf("%d %d\n", u64, int64(u64)) -</pre> -<p> -prints -<p> -<pre> -18446744073709551615 -1 -</pre> -<p> -In fact, if you're lazy the format <code>%v</code> will print, in a simple -appropriate style, any value, even an array or structure. The output of -<p> -<pre><!--{{code "progs/print.go" 14 20}} ---> type T struct { - a int - b string - } - t := T{77, "Sunset Strip"} - a := []int{1, 2, 3, 4} - fmt.Printf("%v %v %v\n", u64, t, a) -</pre> -<p> -is -<p> -<pre> -18446744073709551615 {77 Sunset Strip} [1 2 3 4] -</pre> -<p> -You can drop the formatting altogether if you use <code>Print</code> or <code>Println</code> -instead of <code>Printf</code>. Those routines do fully automatic formatting. -The <code>Print</code> function just prints its elements out using the equivalent -of <code>%v</code> while <code>Println</code> inserts spaces between arguments -and adds a newline. The output of each of these two lines is identical -to that of the <code>Printf</code> call above. -<p> -<pre><!--{{code "progs/print.go" 21 22}} ---> fmt.Print(u64, " ", t, " ", a, "\n") - fmt.Println(u64, t, a) -</pre> -<p> -If you have your own type you'd like <code>Printf</code> or <code>Print</code> to format, -just give it a <code>String</code> method that returns a string. The print -routines will examine the value to inquire whether it implements -the method and if so, use it rather than some other formatting. -Here's a simple example. -<p> -<pre><!--{{code "progs/print_string.go" 9 "$"}} --->type testType struct { - a int - b string -} - -func (t *testType) String() string { - return fmt.Sprint(t.a) + " " + t.b -} - -func main() { - t := &testType{77, "Sunset Strip"} - fmt.Println(t) -} -</pre> -<p> -Since <code>*testType</code> has a <code>String</code> method, the -default formatter for that type will use it and produce the output -<p> -<pre> -77 Sunset Strip -</pre> -<p> -Observe that the <code>String</code> method calls <code>Sprint</code> (the obvious Go -variant that returns a string) to do its formatting; special formatters -can use the <code>fmt</code> library recursively. -<p> -Another feature of <code>Printf</code> is that the format <code>%T</code> will print a string -representation of the type of a value, which can be handy when debugging -polymorphic code. -<p> -It's possible to write full custom print formats with flags and precisions -and such, but that's getting a little off the main thread so we'll leave it -as an exploration exercise. -<p> -You might ask, though, how <code>Printf</code> can tell whether a type implements -the <code>String</code> method. Actually what it does is ask if the value can -be converted to an interface variable that implements the method. -Schematically, given a value <code>v</code>, it does this: -<p> -<p> -<pre> -type Stringer interface { - String() string -} -</pre> -<p> -<pre> -s, ok := v.(Stringer) // Test whether v implements "String()" -if ok { - result = s.String() -} else { - result = defaultOutput(v) -} -</pre> -<p> -The code uses a ``type assertion'' (<code>v.(Stringer)</code>) to test if the value stored in -<code>v</code> satisfies the <code>Stringer</code> interface; if it does, <code>s</code> -will become an interface variable implementing the method and <code>ok</code> will -be <code>true</code>. We then use the interface variable to call the method. -(The ''comma, ok'' pattern is a Go idiom used to test the success of -operations such as type conversion, map update, communications, and so on, -although this is the only appearance in this tutorial.) -If the value does not satisfy the interface, <code>ok</code> will be false. -<p> -In this snippet the name <code>Stringer</code> follows the convention that we add ''[e]r'' -to interfaces describing simple method sets like this. -<p> -One last wrinkle. To complete the suite, besides <code>Printf</code> etc. and <code>Sprintf</code> -etc., there are also <code>Fprintf</code> etc. Unlike in C, <code>Fprintf</code>'s first argument is -not a file. Instead, it is a variable of type <code>io.Writer</code>, which is an -interface type defined in the <code>io</code> library: -<p> -<pre> -type Writer interface { - Write(p []byte) (n int, err os.Error) -} -</pre> -<p> -(This interface is another conventional name, this time for <code>Write</code>; there are also -<code>io.Reader</code>, <code>io.ReadWriter</code>, and so on.) -Thus you can call <code>Fprintf</code> on any type that implements a standard <code>Write</code> -method, not just files but also network channels, buffers, whatever -you want. -<p> -<h2>Prime numbers</h2> -<p> -Now we come to processes and communication—concurrent programming. -It's a big subject so to be brief we assume some familiarity with the topic. -<p> -A classic program in the style is a prime sieve. -(The sieve of Eratosthenes is computationally more efficient than -the algorithm presented here, but we are more interested in concurrency than -algorithmics at the moment.) -It works by taking a stream of all the natural numbers and introducing -a sequence of filters, one for each prime, to winnow the multiples of -that prime. At each step we have a sequence of filters of the primes -so far, and the next number to pop out is the next prime, which triggers -the creation of the next filter in the chain. -<p> -Here's a flow diagram; each box represents a filter element whose -creation is triggered by the first number that flowed from the -elements before it. -<p> -<br> -<p> - <img src='sieve.gif'> -<p> -<br> -<p> -To create a stream of integers, we use a Go <i>channel</i>, which, -borrowing from CSP's descendants, represents a communications -channel that can connect two concurrent computations. -In Go, channel variables are references to a run-time object that -coordinates the communication; as with maps and slices, use -<code>make</code> to create a new channel. -<p> -Here is the first function in <code>progs/sieve.go</code>: -<p> -<pre><!--{{code "progs/sieve.go" `/Send/` `/^}/`}} --->// Send the sequence 2, 3, 4, ... to channel 'ch'. -func generate(ch chan int) { - for i := 2; ; i++ { - ch <- i // Send 'i' to channel 'ch'. - } -} -</pre> -<p> -The <code>generate</code> function sends the sequence 2, 3, 4, 5, ... to its -argument channel, <code>ch</code>, using the binary communications operator <code><-</code>. -Channel operations block, so if there's no recipient for the value on <code>ch</code>, -the send operation will wait until one becomes available. -<p> -The <code>filter</code> function has three arguments: an input channel, an output -channel, and a prime number. It copies values from the input to the -output, discarding anything divisible by the prime. The unary communications -operator <code><-</code> (receive) retrieves the next value on the channel. -<p> -<pre><!--{{code "progs/sieve.go" `/Copy.the/` `/^}/`}} --->// Copy the values from channel 'in' to channel 'out', -// removing those divisible by 'prime'. -func filter(in, out chan int, prime int) { - for { - i := <-in // Receive value of new variable 'i' from 'in'. - if i%prime != 0 { - out <- i // Send 'i' to channel 'out'. - } - } -} -</pre> -<p> -The generator and filters execute concurrently. Go has -its own model of process/threads/light-weight processes/coroutines, -so to avoid notational confusion we call concurrently executing -computations in Go <i>goroutines</i>. To start a goroutine, -invoke the function, prefixing the call with the keyword <code>go</code>; -this starts the function running in parallel with the current -computation but in the same address space: -<p> -<pre> -go sum(hugeArray) // calculate sum in the background -</pre> -<p> -If you want to know when the calculation is done, pass a channel -on which it can report back: -<p> -<pre> -ch := make(chan int) -go sum(hugeArray, ch) -// ... do something else for a while -result := <-ch // wait for, and retrieve, result -</pre> -<p> -Back to our prime sieve. Here's how the sieve pipeline is stitched -together: -<p> -<pre><!--{{code "progs/sieve.go" `/func.main/` `/^}/`}} --->func main() { - ch := make(chan int) // Create a new channel. - go generate(ch) // Start generate() as a goroutine. - for i := 0; i < 100; i++ { // Print the first hundred primes. - prime := <-ch - fmt.Println(prime) - ch1 := make(chan int) - go filter(ch, ch1, prime) - ch = ch1 - } -} -</pre> -<p> -The first line of <code>main</code> creates the initial channel to pass to <code>generate</code>, which it -then starts up. As each prime pops out of the channel, a new <code>filter</code> -is added to the pipeline and <i>its</i> output becomes the new value -of <code>ch</code>. -<p> -The sieve program can be tweaked to use a pattern common -in this style of programming. Here is a variant version -of <code>generate</code>, from <code>progs/sieve1.go</code>: -<p> -<pre><!--{{code "progs/sieve1.go" `/func.generate/` `/^}/`}} --->func generate() chan int { - ch := make(chan int) - go func() { - for i := 2; ; i++ { - ch <- i - } - }() - return ch -} -</pre> -<p> -This version does all the setup internally. It creates the output -channel, launches a goroutine running a function literal, and -returns the channel to the caller. It is a factory for concurrent -execution, starting the goroutine and returning its connection. -<p> -The function literal notation used in the <code>go</code> statement allows us to construct an -anonymous function and invoke it on the spot. Notice that the local -variable <code>ch</code> is available to the function literal and lives on even -after <code>generate</code> returns. -<p> -The same change can be made to <code>filter</code>: -<p> -<pre><!--{{code "progs/sieve1.go" `/func.filter/` `/^}/`}} --->func filter(in chan int, prime int) chan int { - out := make(chan int) - go func() { - for { - if i := <-in; i%prime != 0 { - out <- i - } - } - }() - return out -} -</pre> -<p> -The <code>sieve</code> function's main loop becomes simpler and clearer as a -result, and while we're at it let's turn it into a factory too: -<p> -<pre><!--{{code "progs/sieve1.go" `/func.sieve/` `/^}/`}} --->func sieve() chan int { - out := make(chan int) - go func() { - ch := generate() - for { - prime := <-ch - out <- prime - ch = filter(ch, prime) - } - }() - return out -} -</pre> -<p> -Now <code>main</code>'s interface to the prime sieve is a channel of primes: -<p> -<pre><!--{{code "progs/sieve1.go" `/func.main/` `/^}/`}} --->func main() { - primes := sieve() - for i := 0; i < 100; i++ { // Print the first hundred primes. - fmt.Println(<-primes) - } -} -</pre> -<p> -<h2>Multiplexing</h2> -<p> -With channels, it's possible to serve multiple independent client goroutines without -writing an explicit multiplexer. The trick is to send the server a channel in the message, -which it will then use to reply to the original sender. -A realistic client-server program is a lot of code, so here is a very simple substitute -to illustrate the idea. It starts by defining a <code>request</code> type, which embeds a channel -that will be used for the reply. -<p> -<pre><!--{{code "progs/server.go" `/type.request/` `/^}/`}} --->type request struct { - a, b int - replyc chan int -} -</pre> -<p> -The server will be trivial: it will do simple binary operations on integers. Here's the -code that invokes the operation and responds to the request: -<p> -<pre><!--{{code "progs/server.go" `/type.binOp/` `/^}/`}} --->type binOp func(a, b int) int - -func run(op binOp, req *request) { - reply := op(req.a, req.b) - req.replyc <- reply -} -</pre> -<p> -The type declaration makes <code>binOp</code> represent a function taking two integers and -returning a third. -<p> -The <code>server</code> routine loops forever, receiving requests and, to avoid blocking due to -a long-running operation, starting a goroutine to do the actual work. -<p> -<pre><!--{{code "progs/server.go" `/func.server/` `/^}/`}} --->func server(op binOp, service chan *request) { - for { - req := <-service - go run(op, req) // don't wait for it - } -} -</pre> -<p> -We construct a server in a familiar way, starting it and returning a channel -connected to it: -<p> -<pre><!--{{code "progs/server.go" `/func.startServer/` `/^}/`}} --->func startServer(op binOp) chan *request { - req := make(chan *request) - go server(op, req) - return req -} -</pre> -<p> -Here's a simple test. It starts a server with an addition operator and sends out -<code>N</code> requests without waiting for the replies. Only after all the requests are sent -does it check the results. -<p> -<pre><!--{{code "progs/server.go" `/func.main/` `/^}/`}} --->func main() { - adder := startServer(func(a, b int) int { return a + b }) - const N = 100 - var reqs [N]request - for i := 0; i < N; i++ { - req := &reqs[i] - req.a = i - req.b = i + N - req.replyc = make(chan int) - adder <- req - } - for i := N - 1; i >= 0; i-- { // doesn't matter what order - if <-reqs[i].replyc != N+2*i { - fmt.Println("fail at", i) - } - } - fmt.Println("done") -} -</pre> -<p> -One annoyance with this program is that it doesn't shut down the server cleanly; when <code>main</code> returns -there are a number of lingering goroutines blocked on communication. To solve this, -we can provide a second, <code>quit</code> channel to the server: -<p> -<pre><!--{{code "progs/server1.go" `/func.startServer/` `/^}/`}} --->func startServer(op binOp) (service chan *request, quit chan bool) { - service = make(chan *request) - quit = make(chan bool) - go server(op, service, quit) - return service, quit -} -</pre> -<p> -It passes the quit channel to the <code>server</code> function, which uses it like this: -<p> -<pre><!--{{code "progs/server1.go" `/func.server/` `/^}/`}} --->func server(op binOp, service chan *request, quit chan bool) { - for { - select { - case req := <-service: - go run(op, req) // don't wait for it - case <-quit: - return - } - } -} -</pre> -<p> -Inside <code>server</code>, the <code>select</code> statement chooses which of the multiple communications -listed by its cases can proceed. If all are blocked, it waits until one can proceed; if -multiple can proceed, it chooses one at random. In this instance, the <code>select</code> allows -the server to honor requests until it receives a quit message, at which point it -returns, terminating its execution. -<p> -<p> -All that's left is to strobe the <code>quit</code> channel -at the end of main: -<p> -<pre><!--{{code "progs/server1.go" `/adder,.quit/`}} ---> adder, quit := startServer(func(a, b int) int { return a + b }) -</pre> -... -<pre><!--{{code "progs/server1.go" `/quit....true/`}} ---> quit <- true -</pre> -<p> -There's a lot more to Go programming and concurrent programming in general but this -quick tour should give you some of the basics. diff --git a/doc/go_tutorial.tmpl b/doc/go_tutorial.tmpl deleted file mode 100644 index 15f87ca4b..000000000 --- a/doc/go_tutorial.tmpl +++ /dev/null @@ -1,990 +0,0 @@ -<!-- A Tutorial for the Go Programming Language --> -<h2>Introduction</h2> -<p> -This document is a tutorial introduction to the basics of the Go programming -language, intended for programmers familiar with C or C++. It is not a comprehensive -guide to the language; at the moment the document closest to that is the -<a href='/doc/go_spec.html'>language specification</a>. -After you've read this tutorial, you should look at -<a href='/doc/effective_go.html'>Effective Go</a>, -which digs deeper into how the language is used and -talks about the style and idioms of programming in Go. -Also, slides from a 3-day course about Go are available. -They provide some background and a lot of examples: -<a href='/doc/GoCourseDay1.pdf'>Day 1</a>, -<a href='/doc/GoCourseDay2.pdf'>Day 2</a>, -<a href='/doc/GoCourseDay3.pdf'>Day 3</a>. -<p> -The presentation here proceeds through a series of modest programs to illustrate -key features of the language. All the programs work (at time of writing) and are -checked into the repository in the directory <a href='/doc/progs'><code>/doc/progs/</code></a>. -<p> -<h2>Hello, World</h2> -<p> -Let's start in the usual way: -<p> -{{code "progs/helloworld.go" `/package/` "$"}} -<p> -Every Go source file declares, using a <code>package</code> statement, which package it's part of. -It may also import other packages to use their facilities. -This program imports the package <code>fmt</code> to gain access to -our old, now capitalized and package-qualified, friend, <code>fmt.Printf</code>. -<p> -Functions are introduced with the <code>func</code> keyword. -The <code>main</code> package's <code>main</code> function is where the program starts running (after -any initialization). -<p> -String constants can contain Unicode characters, encoded in UTF-8. -(In fact, Go source files are defined to be encoded in UTF-8.) -<p> -The comment convention is the same as in C++: -<p> -<pre> -/* ... */ -// ... -</pre> -<p> -Later we'll have much more to say about printing. -<p> -<h2>Semicolons</h2> -<p> -You might have noticed that our program has no semicolons. In Go -code, the only place you typically see semicolons is separating the -clauses of <code>for</code> loops and the like; they are not necessary after -every statement. -<p> -In fact, what happens is that the formal language uses semicolons, -much as in C or Java, but they are inserted automatically -at the end of every line that looks like the end of a statement. You -don't need to type them yourself. -<p> -For details about how this is done you can see the language -specification, but in practice all you need to know is that you -never need to put a semicolon at the end of a line. (You can put -them in if you want to write multiple statements per line.) As an -extra help, you can also leave out a semicolon immediately before -a closing brace. -<p> -This approach makes for clean-looking, semicolon-free code. The -one surprise is that it's important to put the opening -brace of a construct such as an <code>if</code> statement on the same line as -the <code>if</code>; if you don't, there are situations that may not compile -or may give the wrong result. The language forces the brace style -to some extent. -<p> -<h2>Compiling</h2> -<p> -Go is a compiled language. At the moment there are two compilers. -<code>Gccgo</code> is a Go compiler that uses the GCC back end. There is also a -suite of compilers with different (and odd) names for each architecture: -<code>6g</code> for the 64-bit x86, <code>8g</code> for the 32-bit x86, and more. These -compilers run significantly faster but generate less efficient code -than <code>gccgo</code>. At the time of writing (late 2009), they also have -a more robust run-time system although <code>gccgo</code> is catching up. -<p> -Here's how to compile and run our program. With <code>6g</code>, say, -<p> -<pre> -$ 6g helloworld.go # compile; object goes into helloworld.6 -$ 6l helloworld.6 # link; output goes into 6.out -$ ./6.out -Hello, world; or Καλημέρα κόσμε; or こんにちは 世界 -$ -</pre> -<p> -With <code>gccgo</code> it looks a little more traditional. -<p> -<pre> -$ gccgo helloworld.go -$ a.out -Hello, world; or Καλημέρα κόσμε; or こんにちは 世界 -$ -</pre> -<p> -<h2>Echo</h2> -<p> -Next up, here's a version of the Unix utility <code>echo(1)</code>: -<p> -{{code "progs/echo.go" `/package/` "$"}} -<p> -This program is small but it's doing a number of new things. In the last example, -we saw <code>func</code> introduce a function. The keywords <code>var</code>, <code>const</code>, and <code>type</code> -(not used yet) also introduce declarations, as does <code>import</code>. -Notice that we can group declarations of the same sort into -parenthesized lists, one item per line, as in the <code>import</code> and <code>const</code> clauses here. -But it's not necessary to do so; we could have said -<p> -<pre> -const Space = " " -const Newline = "\n" -</pre> -<p> -This program imports the <code>"os"</code> package to access its <code>Stdout</code> variable, of type -<code>*os.File</code>. The <code>import</code> statement is actually a declaration: in its general form, -as used in our ``hello world'' program, -it names the identifier (<code>fmt</code>) -that will be used to access members of the package imported from the file (<code>"fmt"</code>), -found in the current directory or in a standard location. -In this program, though, we've dropped the explicit name from the imports; by default, -packages are imported using the name defined by the imported package, -which by convention is of course the file name itself. Our ``hello world'' program -could have said just <code>import "fmt"</code>. -<p> -You can specify your -own import names if you want but it's only necessary if you need to resolve -a naming conflict. -<p> -Given <code>os.Stdout</code> we can use its <code>WriteString</code> method to print the string. -<p> -After importing the <code>flag</code> package, we use a <code>var</code> declaration -to create and initialize a global variable, called <code>omitNewline</code>, -to hold the value of echo's <code>-n</code> flag. -The variable has type <code>*bool</code>, pointer to <code>bool</code>. -<p> -In <code>main.main</code>, we parse the arguments (the call to <code>flag.Parse</code>) and then create a local -string variable with which to build the output. -<p> -The declaration statement has the form -<p> -<pre> -var s string = "" -</pre> -<p> -This is the <code>var</code> keyword, followed by the name of the variable, followed by -its type, followed by an equals sign and an initial value for the variable. -<p> -Go tries to be terse, and this declaration could be shortened. Since the -string constant is of type string, we don't have to tell the compiler that. -We could write -<p> -<pre> -var s = "" -</pre> -<p> -or we could go even shorter and write the idiom -<p> -<pre> -s := "" -</pre> -<p> -The <code>:=</code> operator is used a lot in Go to represent an initializing declaration. -There's one in the <code>for</code> clause on the next line: -<p> -{{code "progs/echo.go" `/for/`}} -<p> -The <code>flag</code> package has parsed the arguments and left the non-flag arguments -in a list that can be iterated over in the obvious way. -<p> -The Go <code>for</code> statement differs from that of C in a number of ways. First, -it's the only looping construct; there is no <code>while</code> or <code>do</code>. Second, -there are no parentheses on the clause, but the braces on the body -are mandatory. The same applies to the <code>if</code> and <code>switch</code> statements. -Later examples will show some other ways <code>for</code> can be written. -<p> -The body of the loop builds up the string <code>s</code> by appending (using <code>+=</code>) -the arguments and separating spaces. After the loop, if the <code>-n</code> flag is not -set, the program appends a newline. Finally, it writes the result. -<p> -Notice that <code>main.main</code> is a niladic function with no return type. -It's defined that way. Falling off the end of <code>main.main</code> means -''success''; if you want to signal an erroneous return, call -<p> -<pre> -os.Exit(1) -</pre> -<p> -The <code>os</code> package contains other essentials for getting -started; for instance, <code>os.Args</code> is a slice used by the -<code>flag</code> package to access the command-line arguments. -<p> -<h2>An Interlude about Types</h2> -<p> -Go has some familiar types such as <code>int</code> and <code>uint</code> (unsigned <code>int</code>), which represent -values of the ''appropriate'' size for the machine. It also defines -explicitly-sized types such as <code>int8</code>, <code>float64</code>, and so on, plus -unsigned integer types such as <code>uint</code>, <code>uint32</code>, etc. -These are distinct types; even if <code>int</code> and <code>int32</code> are both 32 bits in size, -they are not the same type. There is also a <code>byte</code> synonym for -<code>uint8</code>, which is the element type for strings. -<p> -Floating-point types are always sized: <code>float32</code> and <code>float64</code>, -plus <code>complex64</code> (two <code>float32s</code>) and <code>complex128</code> -(two <code>float64s</code>). Complex numbers are outside the -scope of this tutorial. -<p> -Speaking of <code>string</code>, that's a built-in type as well. Strings are -<i>immutable values</i>—they are not just arrays of <code>byte</code> values. -Once you've built a string <i>value</i>, you can't change it, although -of course you can change a string <i>variable</i> simply by -reassigning it. This snippet from <code>strings.go</code> is legal code: -<p> -{{code "progs/strings.go" `/hello/` `/ciao/`}} -<p> -However the following statements are illegal because they would modify -a <code>string</code> value: -<p> -<pre> -s[0] = 'x' -(*p)[1] = 'y' -</pre> -<p> -In C++ terms, Go strings are a bit like <code>const strings</code>, while pointers -to strings are analogous to <code>const string</code> references. -<p> -Yes, there are pointers. However, Go simplifies their use a little; -read on. -<p> -Arrays are declared like this: -<p> -<pre> -var arrayOfInt [10]int -</pre> -<p> -Arrays, like strings, are values, but they are mutable. This differs -from C, in which <code>arrayOfInt</code> would be usable as a pointer to <code>int</code>. -In Go, since arrays are values, it's meaningful (and useful) to talk -about pointers to arrays. -<p> -The size of the array is part of its type; however, one can declare -a <i>slice</i> variable to hold a reference to any array, of any size, -with the same element type. -A <i>slice -expression</i> has the form <code>a[low : high]</code>, representing -the internal array indexed from <code>low</code> through <code>high-1</code>; the resulting -slice is indexed from <code>0</code> through <code>high-low-1</code>. -In short, slices look a lot like arrays but with -no explicit size (<code>[]</code> vs. <code>[10]</code>) and they reference a segment of -an underlying, usually anonymous, regular array. Multiple slices -can share data if they represent pieces of the same array; -multiple arrays can never share data. -<p> -Slices are much more common in Go programs than -regular arrays; they're more flexible, have reference semantics, -and are efficient. What they lack is the precise control of storage -layout of a regular array; if you want to have a hundred elements -of an array stored within your structure, you should use a regular -array. To create one, use a compound value <i>constructor</i>—an -expression formed -from a type followed by a brace-bounded expression like this: -<p> -<pre> -[3]int{1,2,3} -</pre> -<p> -In this case the constructor builds an array of 3 <code>ints</code>. -<p> -When passing an array to a function, you almost always want -to declare the formal parameter to be a slice. When you call -the function, slice the array to create -(efficiently) a slice reference and pass that. -By default, the lower and upper bounds of a slice match the -ends of the existing object, so the concise notation <code>[:]</code> -will slice the whole array. -<p> -Using slices one can write this function (from <code>sum.go</code>): -<p> -{{code "progs/sum.go" `/sum/` `/^}/`}} -<p> -Note how the return type (<code>int</code>) is defined for <code>sum</code> by stating it -after the parameter list. -<p> -To call the function, we slice the array. This intricate call (we'll show -a simpler way in a moment) constructs -an array and slices it: -<p> -<pre> -s := sum([3]int{1,2,3}[:]) -</pre> -<p> -If you are creating a regular array but want the compiler to count the -elements for you, use <code>...</code> as the array size: -<p> -<pre> -s := sum([...]int{1,2,3}[:]) -</pre> -<p> -That's fussier than necessary, though. -In practice, unless you're meticulous about storage layout within a -data structure, a slice itself—using empty brackets with no size—is all you need: -<p> -<pre> -s := sum([]int{1,2,3}) -</pre> -<p> -There are also maps, which you can initialize like this: -<p> -<pre> -m := map[string]int{"one":1 , "two":2} -</pre> -<p> -The built-in function <code>len</code>, which returns number of elements, -makes its first appearance in <code>sum</code>. It works on strings, arrays, -slices, maps, and channels. -<p> -By the way, another thing that works on strings, arrays, slices, maps -and channels is the <code>range</code> clause on <code>for</code> loops. Instead of writing -<p> -<pre> -for i := 0; i < len(a); i++ { ... } -</pre> -<p> -to loop over the elements of a slice (or map or ...) , we could write -<p> -<pre> -for i, v := range a { ... } -</pre> -<p> -This assigns <code>i</code> to the index and <code>v</code> to the value of the successive -elements of the target of the range. See -<a href='/doc/effective_go.html'>Effective Go</a> -for more examples of its use. -<p> -<p> -<h2>An Interlude about Allocation</h2> -<p> -Most types in Go are values. If you have an <code>int</code> or a <code>struct</code> -or an array, assignment -copies the contents of the object. -To allocate a new variable, use the built-in function <code>new</code>, which -returns a pointer to the allocated storage. -<p> -<pre> -type T struct { a, b int } -var t *T = new(T) -</pre> -<p> -or the more idiomatic -<p> -<pre> -t := new(T) -</pre> -<p> -Some types—maps, slices, and channels (see below)—have reference semantics. -If you're holding a slice or a map and you modify its contents, other variables -referencing the same underlying data will see the modification. For these three -types you want to use the built-in function <code>make</code>: -<p> -<pre> -m := make(map[string]int) -</pre> -<p> -This statement initializes a new map ready to store entries. -If you just declare the map, as in -<p> -<pre> -var m map[string]int -</pre> -<p> -it creates a <code>nil</code> reference that cannot hold anything. To use the map, -you must first initialize the reference using <code>make</code> or by assignment from an -existing map. -<p> -Note that <code>new(T)</code> returns type <code>*T</code> while <code>make(T)</code> returns type -<code>T</code>. If you (mistakenly) allocate a reference object with <code>new</code> rather than <code>make</code>, -you receive a pointer to a nil reference, equivalent to -declaring an uninitialized variable and taking its address. -<p> -<h2>An Interlude about Constants</h2> -<p> -Although integers come in lots of sizes in Go, integer constants do not. -There are no constants like <code>0LL</code> or <code>0x0UL</code>. Instead, integer -constants are evaluated as large-precision values that -can overflow only when they are assigned to an integer variable with -too little precision to represent the value. -<p> -<pre> -const hardEight = (1 << 100) >> 97 // legal -</pre> -<p> -There are nuances that deserve redirection to the legalese of the -language specification but here are some illustrative examples: -<p> -<pre> -var a uint64 = 0 // a has type uint64, value 0 -a := uint64(0) // equivalent; uses a "conversion" -i := 0x1234 // i gets default type: int -var j int = 1e6 // legal - 1000000 is representable in an int -x := 1.5 // a float64, the default type for floating constants -i3div2 := 3/2 // integer division - result is 1 -f3div2 := 3./2. // floating-point division - result is 1.5 -</pre> -<p> -Conversions only work for simple cases such as converting <code>ints</code> of one -sign or size to another and between integers and floating-point numbers, -plus a couple of other instances outside the scope of a tutorial. -There are no automatic numeric conversions of any kind in Go, -other than that of making constants have concrete size and type when -assigned to a variable. -<p> -<h2>An I/O Package</h2> -<p> -Next we'll look at a simple package for doing file I/O with an -open/close/read/write interface. Here's the start of <code>file.go</code>: -<p> -{{code "progs/file.go" `/package/` `/^}/`}} -<p> -The first few lines declare the name of the -package—<code>file</code>—and then import two packages. The <code>os</code> -package hides the differences -between various operating systems to give a consistent view of files and -so on; here we're going to use its error handling utilities -and reproduce the rudiments of its file I/O. -<p> -The other item is the low-level, external <code>syscall</code> package, which provides -a primitive interface to the underlying operating system's calls. -<p> -Next is a type definition: the <code>type</code> keyword introduces a type declaration, -in this case a data structure called <code>File</code>. -To make things a little more interesting, our <code>File</code> includes the name of the file -that the file descriptor refers to. -<p> -Because <code>File</code> starts with a capital letter, the type is available outside the package, -that is, by users of the package. In Go the rule about visibility of information is -simple: if a name (of a top-level type, function, method, constant or variable, or of -a structure field or method) is capitalized, users of the package may see it. Otherwise, the -name and hence the thing being named is visible only inside the package in which -it is declared. This is more than a convention; the rule is enforced by the compiler. -In Go, the term for publicly visible names is ''exported''. -<p> -In the case of <code>File</code>, all its fields are lower case and so invisible to users, but we -will soon give it some exported, upper-case methods. -<p> -First, though, here is a factory to create a <code>File</code>: -<p> -{{code "progs/file.go" `/newFile/` `/^}/`}} -<p> -This returns a pointer to a new <code>File</code> structure with the file descriptor and name -filled in. This code uses Go's notion of a ''composite literal'', analogous to -the ones used to build maps and arrays, to construct a new heap-allocated -object. We could write -<p> -<pre> -n := new(File) -n.fd = fd -n.name = name -return n -</pre> -<p> -but for simple structures like <code>File</code> it's easier to return the address of a -composite literal, as is done here in the <code>return</code> statement from <code>newFile</code>. -<p> -We can use the factory to construct some familiar, exported variables of type <code>*File</code>: -<p> -{{code "progs/file.go" `/var/` `/^\)/`}} -<p> -The <code>newFile</code> function was not exported because it's internal. The proper, -exported factory to use is <code>OpenFile</code> (we'll explain that name in a moment): -<p> -{{code "progs/file.go" `/func.OpenFile/` `/^}/`}} -<p> -There are a number of new things in these few lines. First, <code>OpenFile</code> returns -multiple values, a <code>File</code> and an error (more about errors in a moment). -We declare the -multi-value return as a parenthesized list of declarations; syntactically -they look just like a second parameter list. The function -<code>syscall.Open</code> -also has a multi-value return, which we can grab with the multi-variable -declaration on the first line; it declares <code>r</code> and <code>e</code> to hold the two values, -both of type <code>int</code> (although you'd have to look at the <code>syscall</code> package -to see that). Finally, <code>OpenFile</code> returns two values: a pointer to the new <code>File</code> -and the error. If <code>syscall.Open</code> fails, the file descriptor <code>r</code> will -be negative and <code>newFile</code> will return <code>nil</code>. -<p> -About those errors: The <code>os</code> library includes a general notion of an error. -It's a good idea to use its facility in your own interfaces, as we do here, for -consistent error handling throughout Go code. In <code>Open</code> we use a -conversion to translate Unix's integer <code>errno</code> value into the integer type -<code>os.Errno</code>, which implements <code>os.Error</code>. -<p> -Why <code>OpenFile</code> and not <code>Open</code>? To mimic Go's <code>os</code> package, which -our exercise is emulating. The <code>os</code> package takes the opportunity -to make the two commonest cases - open for read and create for -write - the simplest, just <code>Open</code> and <code>Create</code>. <code>OpenFile</code> is the -general case, analogous to the Unix system call <code>Open</code>. Here is -the implementation of our <code>Open</code> and <code>Create</code>; they're trivial -wrappers that eliminate common errors by capturing -the tricky standard arguments to open and, especially, to create a file: -<p> -{{code "progs/file.go" `/^const/` `/^}/`}} -<p> -{{code "progs/file.go" `/func.Create/` `/^}/`}} -<p> -Back to our main story. -Now that we can build <code>Files</code>, we can write methods for them. To declare -a method of a type, we define a function to have an explicit receiver -of that type, placed -in parentheses before the function name. Here are some methods for <code>*File</code>, -each of which declares a receiver variable <code>file</code>. -<p> -{{code "progs/file.go" `/Close/` "$"}} -<p> -There is no implicit <code>this</code> and the receiver variable must be used to access -members of the structure. Methods are not declared within -the <code>struct</code> declaration itself. The <code>struct</code> declaration defines only data members. -In fact, methods can be created for almost any type you name, such as an integer or -array, not just for <code>structs</code>. We'll see an example with arrays later. -<p> -The <code>String</code> method is so called because of a printing convention we'll -describe later. -<p> -The methods use the public variable <code>os.EINVAL</code> to return the (<code>os.Error</code> -version of the) Unix error code <code>EINVAL</code>. The <code>os</code> library defines a standard -set of such error values. -<p> -We can now use our new package: -<p> -{{code "progs/helloworld3.go" `/package/` "$"}} -<p> -The ''<code>./</code>'' in the import of ''<code>./file</code>'' tells the compiler -to use our own package rather than -something from the directory of installed packages. -(Also, ''<code>file.go</code>'' must be compiled before we can import the -package.) -<p> -Now we can compile and run the program. On Unix, this would be the result: -<p> -<pre> -$ 6g file.go # compile file package -$ 6g helloworld3.go # compile main package -$ 6l -o helloworld3 helloworld3.6 # link - no need to mention "file" -$ helloworld3 -hello, world -can't open file; err=No such file or directory -$ -</pre> -<p> -<h2>Rotting cats</h2> -<p> -Building on the <code>file</code> package, here's a simple version of the Unix utility <code>cat(1)</code>, -<code>progs/cat.go</code>: -<p> -{{code "progs/cat.go" `/package/` "$"}} -<p> -By now this should be easy to follow, but the <code>switch</code> statement introduces some -new features. Like a <code>for</code> loop, an <code>if</code> or <code>switch</code> can include an -initialization statement. The <code>switch</code> statement in <code>cat</code> uses one to create variables -<code>nr</code> and <code>er</code> to hold the return values from the call to <code>f.Read</code>. (The <code>if</code> a few lines later -has the same idea.) The <code>switch</code> statement is general: it evaluates the cases -from top to bottom looking for the first case that matches the value; the -case expressions don't need to be constants or even integers, as long as -they all have the same type. -<p> -Since the <code>switch</code> value is just <code>true</code>, we could leave it off—as is also -the situation -in a <code>for</code> statement, a missing value means <code>true</code>. In fact, such a <code>switch</code> -is a form of <code>if-else</code> chain. While we're here, it should be mentioned that in -<code>switch</code> statements each <code>case</code> has an implicit <code>break</code>. -<p> -The argument to <code>file.Stdout.Write</code> is created by slicing the array <code>buf</code>. -Slices provide the standard Go way to handle I/O buffers. -<p> -Now let's make a variant of <code>cat</code> that optionally does <code>rot13</code> on its input. -It's easy to do by just processing the bytes, but instead we will exploit -Go's notion of an <i>interface</i>. -<p> -The <code>cat</code> subroutine uses only two methods of <code>f</code>: <code>Read</code> and <code>String</code>, -so let's start by defining an interface that has exactly those two methods. -Here is code from <code>progs/cat_rot13.go</code>: -<p> -{{code "progs/cat_rot13.go" `/type.reader/` `/^}/`}} -<p> -Any type that has the two methods of <code>reader</code>—regardless of whatever -other methods the type may also have—is said to <i>implement</i> the -interface. Since <code>file.File</code> implements these methods, it implements the -<code>reader</code> interface. We could tweak the <code>cat</code> subroutine to accept a <code>reader</code> -instead of a <code>*file.File</code> and it would work just fine, but let's embellish a little -first by writing a second type that implements <code>reader</code>, one that wraps an -existing <code>reader</code> and does <code>rot13</code> on the data. To do this, we just define -the type and implement the methods and with no other bookkeeping, -we have a second implementation of the <code>reader</code> interface. -<p> -{{code "progs/cat_rot13.go" `/type.rotate13/` `/end.of.rotate13/`}} -<p> -(The <code>rot13</code> function called in <code>Read</code> is trivial and not worth reproducing here.) -<p> -To use the new feature, we define a flag: -<p> -{{code "progs/cat_rot13.go" `/rot13Flag/`}} -<p> -and use it from within a mostly unchanged <code>cat</code> function: -<p> -{{code "progs/cat_rot13.go" `/func.cat/` `/^}/`}} -<p> -(We could also do the wrapping in <code>main</code> and leave <code>cat</code> mostly alone, except -for changing the type of the argument; consider that an exercise.) -The <code>if</code> at the top of <code>cat</code> sets it all up: If the <code>rot13</code> flag is true, wrap the <code>reader</code> -we received into a <code>rotate13</code> and proceed. Note that the interface variables -are values, not pointers: the argument is of type <code>reader</code>, not <code>*reader</code>, -even though under the covers it holds a pointer to a <code>struct</code>. -<p> -Here it is in action: -<p> -<pre> -$ echo abcdefghijklmnopqrstuvwxyz | ./cat -abcdefghijklmnopqrstuvwxyz -$ echo abcdefghijklmnopqrstuvwxyz | ./cat --rot13 -nopqrstuvwxyzabcdefghijklm -$ -</pre> -<p> -Fans of dependency injection may take cheer from how easily interfaces -allow us to substitute the implementation of a file descriptor. -<p> -Interfaces are a distinctive feature of Go. An interface is implemented by a -type if the type implements all the methods declared in the interface. -This means -that a type may implement an arbitrary number of different interfaces. -There is no type hierarchy; things can be much more <i>ad hoc</i>, -as we saw with <code>rot13</code>. The type <code>file.File</code> implements <code>reader</code>; it could also -implement a <code>writer</code>, or any other interface built from its methods that -fits the current situation. Consider the <i>empty interface</i> -<p> -<pre> -type Empty interface {} -</pre> -<p> -<i>Every</i> type implements the empty interface, which makes it -useful for things like containers. -<p> -<h2>Sorting</h2> -<p> -Interfaces provide a simple form of polymorphism. They completely -separate the definition of what an object does from how it does it, allowing -distinct implementations to be represented at different times by the -same interface variable. -<p> -As an example, consider this simple sort algorithm taken from <code>progs/sort.go</code>: -<p> -{{code "progs/sort.go" `/func.Sort/` `/^}/`}} -<p> -The code needs only three methods, which we wrap into sort's <code>Interface</code>: -<p> -{{code "progs/sort.go" `/interface/` `/^}/`}} -<p> -We can apply <code>Sort</code> to any type that implements <code>Len</code>, <code>Less</code>, and <code>Swap</code>. -The <code>sort</code> package includes the necessary methods to allow sorting of -arrays of integers, strings, etc.; here's the code for arrays of <code>int</code> -<p> -{{code "progs/sort.go" `/type.*IntSlice/` `/Swap/`}} -<p> -Here we see methods defined for non-<code>struct</code> types. You can define methods -for any type you define and name in your package. -<p> -And now a routine to test it out, from <code>progs/sortmain.go</code>. This -uses a function in the <code>sort</code> package, omitted here for brevity, -to test that the result is sorted. -<p> -{{code "progs/sortmain.go" `/func.ints/` `/^}/`}} -<p> -If we have a new type we want to be able to sort, all we need to do is -to implement the three methods for that type, like this: -<p> -{{code "progs/sortmain.go" `/type.day/` `/Swap/`}} -<p> -<p> -<h2>Printing</h2> -<p> -The examples of formatted printing so far have been modest. In this section -we'll talk about how formatted I/O can be done well in Go. -<p> -We've seen simple uses of the package <code>fmt</code>, which -implements <code>Printf</code>, <code>Fprintf</code>, and so on. -Within the <code>fmt</code> package, <code>Printf</code> is declared with this signature: -<p> -<pre> -Printf(format string, v ...interface{}) (n int, errno os.Error) -</pre> -<p> -The token <code>...</code> introduces a variable-length argument list that in C would -be handled using the <code>stdarg.h</code> macros. -In Go, variadic functions are passed a slice of the arguments of the -specified type. In <code>Printf</code>'s case, the declaration says <code>...interface{}</code> -so the actual type is a slice of empty interface values, <code>[]interface{}</code>. -<code>Printf</code> can examine the arguments by iterating over the slice -and, for each element, using a type switch or the reflection library -to interpret the value. -It's off topic here but such run-time type analysis -helps explain some of the nice properties of Go's <code>Printf</code>, -due to the ability of <code>Printf</code> to discover the type of its arguments -dynamically. -<p> -For example, in C each format must correspond to the type of its -argument. It's easier in many cases in Go. Instead of <code>%llud</code> you -can just say <code>%d</code>; <code>Printf</code> knows the size and signedness of the -integer and can do the right thing for you. The snippet -<p> -{{code "progs/print.go" 10 11}} -<p> -prints -<p> -<pre> -18446744073709551615 -1 -</pre> -<p> -In fact, if you're lazy the format <code>%v</code> will print, in a simple -appropriate style, any value, even an array or structure. The output of -<p> -{{code "progs/print.go" 14 20}} -<p> -is -<p> -<pre> -18446744073709551615 {77 Sunset Strip} [1 2 3 4] -</pre> -<p> -You can drop the formatting altogether if you use <code>Print</code> or <code>Println</code> -instead of <code>Printf</code>. Those routines do fully automatic formatting. -The <code>Print</code> function just prints its elements out using the equivalent -of <code>%v</code> while <code>Println</code> inserts spaces between arguments -and adds a newline. The output of each of these two lines is identical -to that of the <code>Printf</code> call above. -<p> -{{code "progs/print.go" 21 22}} -<p> -If you have your own type you'd like <code>Printf</code> or <code>Print</code> to format, -just give it a <code>String</code> method that returns a string. The print -routines will examine the value to inquire whether it implements -the method and if so, use it rather than some other formatting. -Here's a simple example. -<p> -{{code "progs/print_string.go" 9 "$"}} -<p> -Since <code>*testType</code> has a <code>String</code> method, the -default formatter for that type will use it and produce the output -<p> -<pre> -77 Sunset Strip -</pre> -<p> -Observe that the <code>String</code> method calls <code>Sprint</code> (the obvious Go -variant that returns a string) to do its formatting; special formatters -can use the <code>fmt</code> library recursively. -<p> -Another feature of <code>Printf</code> is that the format <code>%T</code> will print a string -representation of the type of a value, which can be handy when debugging -polymorphic code. -<p> -It's possible to write full custom print formats with flags and precisions -and such, but that's getting a little off the main thread so we'll leave it -as an exploration exercise. -<p> -You might ask, though, how <code>Printf</code> can tell whether a type implements -the <code>String</code> method. Actually what it does is ask if the value can -be converted to an interface variable that implements the method. -Schematically, given a value <code>v</code>, it does this: -<p> -<p> -<pre> -type Stringer interface { - String() string -} -</pre> -<p> -<pre> -s, ok := v.(Stringer) // Test whether v implements "String()" -if ok { - result = s.String() -} else { - result = defaultOutput(v) -} -</pre> -<p> -The code uses a ``type assertion'' (<code>v.(Stringer)</code>) to test if the value stored in -<code>v</code> satisfies the <code>Stringer</code> interface; if it does, <code>s</code> -will become an interface variable implementing the method and <code>ok</code> will -be <code>true</code>. We then use the interface variable to call the method. -(The ''comma, ok'' pattern is a Go idiom used to test the success of -operations such as type conversion, map update, communications, and so on, -although this is the only appearance in this tutorial.) -If the value does not satisfy the interface, <code>ok</code> will be false. -<p> -In this snippet the name <code>Stringer</code> follows the convention that we add ''[e]r'' -to interfaces describing simple method sets like this. -<p> -One last wrinkle. To complete the suite, besides <code>Printf</code> etc. and <code>Sprintf</code> -etc., there are also <code>Fprintf</code> etc. Unlike in C, <code>Fprintf</code>'s first argument is -not a file. Instead, it is a variable of type <code>io.Writer</code>, which is an -interface type defined in the <code>io</code> library: -<p> -<pre> -type Writer interface { - Write(p []byte) (n int, err os.Error) -} -</pre> -<p> -(This interface is another conventional name, this time for <code>Write</code>; there are also -<code>io.Reader</code>, <code>io.ReadWriter</code>, and so on.) -Thus you can call <code>Fprintf</code> on any type that implements a standard <code>Write</code> -method, not just files but also network channels, buffers, whatever -you want. -<p> -<h2>Prime numbers</h2> -<p> -Now we come to processes and communication—concurrent programming. -It's a big subject so to be brief we assume some familiarity with the topic. -<p> -A classic program in the style is a prime sieve. -(The sieve of Eratosthenes is computationally more efficient than -the algorithm presented here, but we are more interested in concurrency than -algorithmics at the moment.) -It works by taking a stream of all the natural numbers and introducing -a sequence of filters, one for each prime, to winnow the multiples of -that prime. At each step we have a sequence of filters of the primes -so far, and the next number to pop out is the next prime, which triggers -the creation of the next filter in the chain. -<p> -Here's a flow diagram; each box represents a filter element whose -creation is triggered by the first number that flowed from the -elements before it. -<p> -<br> -<p> - <img src='sieve.gif'> -<p> -<br> -<p> -To create a stream of integers, we use a Go <i>channel</i>, which, -borrowing from CSP's descendants, represents a communications -channel that can connect two concurrent computations. -In Go, channel variables are references to a run-time object that -coordinates the communication; as with maps and slices, use -<code>make</code> to create a new channel. -<p> -Here is the first function in <code>progs/sieve.go</code>: -<p> -{{code "progs/sieve.go" `/Send/` `/^}/`}} -<p> -The <code>generate</code> function sends the sequence 2, 3, 4, 5, ... to its -argument channel, <code>ch</code>, using the binary communications operator <code><-</code>. -Channel operations block, so if there's no recipient for the value on <code>ch</code>, -the send operation will wait until one becomes available. -<p> -The <code>filter</code> function has three arguments: an input channel, an output -channel, and a prime number. It copies values from the input to the -output, discarding anything divisible by the prime. The unary communications -operator <code><-</code> (receive) retrieves the next value on the channel. -<p> -{{code "progs/sieve.go" `/Copy.the/` `/^}/`}} -<p> -The generator and filters execute concurrently. Go has -its own model of process/threads/light-weight processes/coroutines, -so to avoid notational confusion we call concurrently executing -computations in Go <i>goroutines</i>. To start a goroutine, -invoke the function, prefixing the call with the keyword <code>go</code>; -this starts the function running in parallel with the current -computation but in the same address space: -<p> -<pre> -go sum(hugeArray) // calculate sum in the background -</pre> -<p> -If you want to know when the calculation is done, pass a channel -on which it can report back: -<p> -<pre> -ch := make(chan int) -go sum(hugeArray, ch) -// ... do something else for a while -result := <-ch // wait for, and retrieve, result -</pre> -<p> -Back to our prime sieve. Here's how the sieve pipeline is stitched -together: -<p> -{{code "progs/sieve.go" `/func.main/` `/^}/`}} -<p> -The first line of <code>main</code> creates the initial channel to pass to <code>generate</code>, which it -then starts up. As each prime pops out of the channel, a new <code>filter</code> -is added to the pipeline and <i>its</i> output becomes the new value -of <code>ch</code>. -<p> -The sieve program can be tweaked to use a pattern common -in this style of programming. Here is a variant version -of <code>generate</code>, from <code>progs/sieve1.go</code>: -<p> -{{code "progs/sieve1.go" `/func.generate/` `/^}/`}} -<p> -This version does all the setup internally. It creates the output -channel, launches a goroutine running a function literal, and -returns the channel to the caller. It is a factory for concurrent -execution, starting the goroutine and returning its connection. -<p> -The function literal notation used in the <code>go</code> statement allows us to construct an -anonymous function and invoke it on the spot. Notice that the local -variable <code>ch</code> is available to the function literal and lives on even -after <code>generate</code> returns. -<p> -The same change can be made to <code>filter</code>: -<p> -{{code "progs/sieve1.go" `/func.filter/` `/^}/`}} -<p> -The <code>sieve</code> function's main loop becomes simpler and clearer as a -result, and while we're at it let's turn it into a factory too: -<p> -{{code "progs/sieve1.go" `/func.sieve/` `/^}/`}} -<p> -Now <code>main</code>'s interface to the prime sieve is a channel of primes: -<p> -{{code "progs/sieve1.go" `/func.main/` `/^}/`}} -<p> -<h2>Multiplexing</h2> -<p> -With channels, it's possible to serve multiple independent client goroutines without -writing an explicit multiplexer. The trick is to send the server a channel in the message, -which it will then use to reply to the original sender. -A realistic client-server program is a lot of code, so here is a very simple substitute -to illustrate the idea. It starts by defining a <code>request</code> type, which embeds a channel -that will be used for the reply. -<p> -{{code "progs/server.go" `/type.request/` `/^}/`}} -<p> -The server will be trivial: it will do simple binary operations on integers. Here's the -code that invokes the operation and responds to the request: -<p> -{{code "progs/server.go" `/type.binOp/` `/^}/`}} -<p> -The type declaration makes <code>binOp</code> represent a function taking two integers and -returning a third. -<p> -The <code>server</code> routine loops forever, receiving requests and, to avoid blocking due to -a long-running operation, starting a goroutine to do the actual work. -<p> -{{code "progs/server.go" `/func.server/` `/^}/`}} -<p> -We construct a server in a familiar way, starting it and returning a channel -connected to it: -<p> -{{code "progs/server.go" `/func.startServer/` `/^}/`}} -<p> -Here's a simple test. It starts a server with an addition operator and sends out -<code>N</code> requests without waiting for the replies. Only after all the requests are sent -does it check the results. -<p> -{{code "progs/server.go" `/func.main/` `/^}/`}} -<p> -One annoyance with this program is that it doesn't shut down the server cleanly; when <code>main</code> returns -there are a number of lingering goroutines blocked on communication. To solve this, -we can provide a second, <code>quit</code> channel to the server: -<p> -{{code "progs/server1.go" `/func.startServer/` `/^}/`}} -<p> -It passes the quit channel to the <code>server</code> function, which uses it like this: -<p> -{{code "progs/server1.go" `/func.server/` `/^}/`}} -<p> -Inside <code>server</code>, the <code>select</code> statement chooses which of the multiple communications -listed by its cases can proceed. If all are blocked, it waits until one can proceed; if -multiple can proceed, it chooses one at random. In this instance, the <code>select</code> allows -the server to honor requests until it receives a quit message, at which point it -returns, terminating its execution. -<p> -<p> -All that's left is to strobe the <code>quit</code> channel -at the end of main: -<p> -{{code "progs/server1.go" `/adder,.quit/`}} -... -{{code "progs/server1.go" `/quit....true/`}} -<p> -There's a lot more to Go programming and concurrent programming in general but this -quick tour should give you some of the basics. diff --git a/doc/godocs.js b/doc/godocs.js index 946c4c39f..8fd32fef0 100644 --- a/doc/godocs.js +++ b/doc/godocs.js @@ -18,13 +18,6 @@ function bindEvent(el, e, fn) { el.attachEvent('on'+e, fn); } } -bindEvent(window, 'load', godocs_onload); - -function godocs_onload() { - godocs_bindSearchEvents(); - godocs_generateTOC(); - godocs_addTopLinks(); -} function godocs_bindSearchEvents() { var search = document.getElementById('search'); @@ -39,7 +32,7 @@ function godocs_bindSearchEvents() { } } function restoreInactive() { - if (search.value != "") { + if (search.value !== "") { return; } if (search.type != "search") { @@ -52,56 +45,72 @@ function godocs_bindSearchEvents() { bindEvent(search, 'blur', restoreInactive); } +/* Returns the "This sweet header" from <h2>This <i>sweet</i> header</h2>. + * Takes a node, returns a string. + */ +function godocs_nodeToText(node) { + var TEXT_NODE = 3; // Defined in Mozilla but not MSIE :( + + var text = ''; + for (var j = 0; j != node.childNodes.length; j++) { + var child = node.childNodes[j]; + if (child.nodeType == TEXT_NODE) { + if (child.nodeValue != '[Top]') { //ok, that's a hack, but it works. + text = text + child.nodeValue; + } + } else { + text = text + godocs_nodeToText(child); + } + } + return text; +} + /* Generates a table of contents: looks for h2 and h3 elements and generates * links. "Decorates" the element with id=="nav" with this table of contents. */ function godocs_generateTOC() { + if (document.getElementById('manual-nav')) { return; } var navbar = document.getElementById('nav'); if (!navbar) { return; } var toc_items = []; var i; + var seenNav = false; for (i = 0; i < navbar.parentNode.childNodes.length; i++) { var node = navbar.parentNode.childNodes[i]; - if ((node.tagName == 'h2') || (node.tagName == 'H2')) { - if (!node.id) { - node.id = 'tmp_' + i; + if (!seenNav) { + if (node.id == 'nav') { + seenNav = true; } - var text = godocs_nodeToText(node); - if (!text) { continue; } - - var textNode = document.createTextNode(text); - - var link = document.createElement('a'); - link.href = '#' + node.id; - link.appendChild(textNode); - - // Then create the item itself - var item = document.createElement('dt'); - - item.appendChild(link); - toc_items.push(item); + continue; } - if ((node.tagName == 'h3') || (node.tagName == 'H3')) { - if (!node.id) { - node.id = 'tmp_' + i; - } - var text = godocs_nodeToText(node); - if (!text) { continue; } - - var textNode = document.createTextNode(text); + if ((node.tagName != 'h2') && (node.tagName != 'H2') && + (node.tagName != 'h3') && (node.tagName != 'H3')) { + continue; + } + if (!node.id) { + node.id = 'tmp_' + i; + } + var text = godocs_nodeToText(node); + if (!text) { continue; } - var link = document.createElement('a'); - link.href = '#' + node.id; - link.appendChild(textNode); + var textNode = document.createTextNode(text); - // Then create the item itself - var item = document.createElement('dd'); + var link = document.createElement('a'); + link.href = '#' + node.id; + link.appendChild(textNode); - item.appendChild(link); - toc_items.push(item); + // Then create the item itself + var item; + if ((node.tagName == 'h2') || (node.tagName == 'H2')) { + item = document.createElement('dt'); + } else { // h3 + item = document.createElement('dd'); } + + item.appendChild(link); + toc_items.push(item); } if (toc_items.length <= 1) { return; } @@ -142,49 +151,63 @@ function godocs_generateTOC() { tocCell.appendChild(dl2); } -/* Returns the "This sweet header" from <h2>This <i>sweet</i> header</h2>. - * Takes a node, returns a string. - */ -function godocs_nodeToText(node) { - var TEXT_NODE = 3; // Defined in Mozilla but not MSIE :( +function getElementsByClassName(base, clazz) { + if (base.getElementsByClassName) { + return base.getElementsByClassName(clazz); + } + var elements = base.getElementsByTagName('*'), foundElements = []; + for (var n in elements) { + if (clazz == elements[n].className) { + foundElements.push(elements[n]); + } + } + return foundElements; +} - var text = ''; - for (var j = 0; j != node.childNodes.length; j++) { - var child = node.childNodes[j]; - if (child.nodeType == TEXT_NODE) { - if (child.nodeValue != '[Top]') { //ok, that's a hack, but it works. - text = text + child.nodeValue; - } +function godocs_bindToggle(el) { + var button = getElementsByClassName(el, "toggleButton"); + var callback = function() { + if (el.className == "toggle") { + el.className = "toggleVisible"; } else { - text = text + godocs_nodeToText(child); + el.className = "toggle"; } + }; + for (var i = 0; i < button.length; i++) { + bindEvent(button[i], "click", callback); } - return text; } - -/* For each H2 heading, add a link up to the #top of the document. - * (As part of this: ensure existence of 'top' named anchor link - * (theoretically at doc's top).) - */ -function godocs_addTopLinks() { - /* Make sure there's a "top" to link to. */ - var top = document.getElementById('top'); - if (!top) { - document.body.id = 'top'; +function godocs_bindToggles(className) { + var els = getElementsByClassName(document, className); + for (var i = 0; i < els.length; i++) { + godocs_bindToggle(els[i]); } - - if (!document.getElementsByTagName) return; // no browser support - - var headers = document.getElementsByTagName('h2'); - - for (var i = 0; i < headers.length; i++) { - var span = document.createElement('span'); - span.className = 'navtop'; - var link = document.createElement('a'); - span.appendChild(link); - link.href = '#top'; - var textNode = document.createTextNode('[Top]'); - link.appendChild(textNode); - headers[i].appendChild(span); +} +function godocs_bindToggleLink(l, prefix) { + bindEvent(l, "click", function() { + var i = l.href.indexOf("#"+prefix); + if (i < 0) { + return; + } + var id = prefix + l.href.slice(i+1+prefix.length); + var eg = document.getElementById(id); + eg.className = "toggleVisible"; + }); +} +function godocs_bindToggleLinks(className, prefix) { + var links = getElementsByClassName(document, className); + for (i = 0; i < links.length; i++) { + godocs_bindToggleLink(links[i], prefix); } } + +function godocs_onload() { + godocs_bindSearchEvents(); + godocs_generateTOC(); + godocs_bindToggles("toggle"); + godocs_bindToggles("toggleVisible"); + godocs_bindToggleLinks("exampleLink", "example_"); + godocs_bindToggleLinks("overviewLink", ""); +} + +bindEvent(window, 'load', godocs_onload); diff --git a/doc/gopher/bumper.png b/doc/gopher/bumper.png Binary files differindex 6b41c1fd0..b357cdf47 100644 --- a/doc/gopher/bumper.png +++ b/doc/gopher/bumper.png diff --git a/doc/gopher/bumper192x108.png b/doc/gopher/bumper192x108.png Binary files differindex 470a74df5..925474e76 100644 --- a/doc/gopher/bumper192x108.png +++ b/doc/gopher/bumper192x108.png diff --git a/doc/gopher/bumper320x180.png b/doc/gopher/bumper320x180.png Binary files differindex 5b31b5d31..611c417c4 100644 --- a/doc/gopher/bumper320x180.png +++ b/doc/gopher/bumper320x180.png diff --git a/doc/gopher/bumper480x270.png b/doc/gopher/bumper480x270.png Binary files differindex 621f51b65..cf187151f 100644 --- a/doc/gopher/bumper480x270.png +++ b/doc/gopher/bumper480x270.png diff --git a/doc/gopher/bumper640x360.png b/doc/gopher/bumper640x360.png Binary files differindex 9c898d0c7..a5073e0d1 100644 --- a/doc/gopher/bumper640x360.png +++ b/doc/gopher/bumper640x360.png diff --git a/doc/gopher/doc.png b/doc/gopher/doc.png Binary files differnew file mode 100644 index 000000000..e15a3234d --- /dev/null +++ b/doc/gopher/doc.png diff --git a/doc/gopher/frontpage.png b/doc/gopher/frontpage.png Binary files differnew file mode 100644 index 000000000..1eb81f0be --- /dev/null +++ b/doc/gopher/frontpage.png diff --git a/doc/gopher/gopherbw.png b/doc/gopher/gopherbw.png Binary files differindex 48a08cc61..3bfe85dc1 100644 --- a/doc/gopher/gopherbw.png +++ b/doc/gopher/gopherbw.png diff --git a/doc/gopher/gophercolor.png b/doc/gopher/gophercolor.png Binary files differindex b48ffba37..b5f8d01ff 100644 --- a/doc/gopher/gophercolor.png +++ b/doc/gopher/gophercolor.png diff --git a/doc/gopher/gophercolor16x16.png b/doc/gopher/gophercolor16x16.png Binary files differindex 48854ff3b..ec7028cc1 100644 --- a/doc/gopher/gophercolor16x16.png +++ b/doc/gopher/gophercolor16x16.png diff --git a/doc/gopher/help.png b/doc/gopher/help.png Binary files differnew file mode 100644 index 000000000..6ee523898 --- /dev/null +++ b/doc/gopher/help.png diff --git a/doc/gopher/pkg.png b/doc/gopher/pkg.png Binary files differnew file mode 100644 index 000000000..ac96551b5 --- /dev/null +++ b/doc/gopher/pkg.png diff --git a/doc/gopher/project.png b/doc/gopher/project.png Binary files differnew file mode 100644 index 000000000..24603f306 --- /dev/null +++ b/doc/gopher/project.png diff --git a/doc/gopher/ref.png b/doc/gopher/ref.png Binary files differnew file mode 100644 index 000000000..0508f6ec6 --- /dev/null +++ b/doc/gopher/ref.png diff --git a/doc/gopher/run.png b/doc/gopher/run.png Binary files differnew file mode 100644 index 000000000..eb690e3f2 --- /dev/null +++ b/doc/gopher/run.png diff --git a/doc/gopher/talks.png b/doc/gopher/talks.png Binary files differnew file mode 100644 index 000000000..589db470a --- /dev/null +++ b/doc/gopher/talks.png diff --git a/doc/help.html b/doc/help.html new file mode 100644 index 000000000..fadf80a03 --- /dev/null +++ b/doc/help.html @@ -0,0 +1,38 @@ +<!--{ + "Title": "Getting Help", + "Path": "/help/" +}--> + +<img class="gopher" src="/doc/gopher/help.png"/> + +<p> +Need help with Go? Try these resources. +</p> + +<div id="manual-nav"></div> + +<h3 id="go_faq"><a href="/doc/go_faq.html">Frequently Asked Questions (FAQ)</a></h3> +<p>Answers to common questions about Go.</p> + +<h3 id="wiki"><a href="http://code.google.com/p/go-wiki/wiki">Go Language Community Wiki</a></h3> +<p>A wiki maintained by the Go community.</p> + +<h3 id="mailinglist"><a href="http://groups.google.com/group/golang-nuts">Go Nuts Mailing List</a></h3> +<p> +Search the <a href="http://groups.google.com/group/golang-nuts">golang-nuts</a> +archives and consult the <a href="/doc/go_faq.html">FAQ</a> and +<a href="http://code.google.com/p/go-wiki/wiki">wiki</a> before posting. +</p> + +<h3 id="irc"><a href="irc:irc.freenode.net/go-nuts">Go IRC Channel</a></h3> +<p>Get live support at <b>#go-nuts</b> on <b>irc.freenode.net</b>, the official +Go IRC channel.</p> + +<h3 id="twitter"><a href="http://twitter.com/go_nuts">@go_nuts at Twitter</a></h3> +<p>The Go project's official Twitter account.</p> +<p>Tweeting your about problem with the <code>#golang</code> hashtag usually +generates some helpful responses.</p> + +<h3 id="plus"><a href="https://plus.google.com/101406623878176903605/posts">The Go Programming Language at Google+</a></h3> +<p>The Go project's Google+ page.</p> + diff --git a/doc/install-source.html b/doc/install-source.html new file mode 100644 index 000000000..4673850f4 --- /dev/null +++ b/doc/install-source.html @@ -0,0 +1,441 @@ +<!--{ + "Title": "Installing Go from source", + "Path": "/doc/install/source" +}--> + +<h2 id="introduction">Introduction</h2> + +<p> +Go is an open source project, distributed under a +<a href="/LICENSE">BSD-style license</a>. +This document explains how to check out the sources, +build them on your own machine, and run them. +</p> + +<p> +Most users don't need to do this, and will instead install +from precompiled binary packages as described in +<a href="/doc/install">Getting Started</a>, +a much simpler process. +If you want to help develop what goes into those precompiled +packages, though, read on. +</p> + +<div class="detail"> + +<p> +There are two official Go compiler tool chains. +This document focuses on the <code>gc</code> Go +compiler and tools (<code>6g</code>, <code>8g</code> etc.). +For information on how to work on <code>gccgo</code>, a more traditional +compiler using the GCC back end, see +<a href="/doc/install/gccgo">Setting up and using gccgo</a>. +</p> + +<p> +The Go compilers support three instruction sets. +There are important differences in the quality of the compilers for the different +architectures. +</p> + +<dl> +<dt> + <code>amd64</code> (a.k.a. <code>x86-64</code>); <code>6g,6l,6c,6a</code> +</dt> +<dd> + A mature implementation. The compiler has an effective + optimizer (registerizer) and generates good code (although + <code>gccgo</code> can do noticeably better sometimes). +</dd> +<dt> + <code>386</code> (a.k.a. <code>x86</code> or <code>x86-32</code>); <code>8g,8l,8c,8a</code> +</dt> +<dd> + Comparable to the <code>amd64</code> port. +</dd> +<dt> + <code>arm</code> (a.k.a. <code>ARM</code>); <code>5g,5l,5c,5a</code> +</dt> +<dd> + Supports only Linux binaries. Less widely used than the other ports and therefore + not as thoroughly tested. +</dd> +</dl> + +<p> +Except for things like low-level operating system interface code, the run-time +support is the same in all ports and includes a mark-and-sweep garbage +collector, efficient array and string slicing, and support for efficient +goroutines, such as stacks that grow and shrink on demand. +</p> + +<p> +The compilers can target the FreeBSD, Linux, NetBSD, OpenBSD, OS X (Darwin), +and Windows operating systems. +The full set of supported combinations is listed in the discussion of +<a href="#environment">environment variables</a> below. +</p> + +</div> + +<h2 id="ctools">Install C tools, if needed</h2> + +<p> +The Go tool chain is written in C. +To build it, you need a C compiler installed. +</p> + +<p> +On OS X, a C compiler can be installed as part of +<a href="http://developer.apple.com/Xcode/">Xcode</a>. +</p> + +<p> +On Ubuntu/Debian, use <code>sudo apt-get install gcc libc6-dev</code>. +If you want to build 32-bit binaries on a 64-bit system you'll also need the +<code>libc6-dev-i386</code> package. +</p> + +<p> +On Windows, install <code>gcc</code> with +<a href="http://www.mingw.org/">MinGW</a>. +(Make sure you add its <code>bin</code> subdirectory to your <code>PATH</code>.) +</p> + +<h2 id="mercurial">Install Mercurial, if needed</h2> + +<p> +To perform the next step you must have Mercurial installed. (Check that you +have an <code>hg</code> command.) This suffices to install Mercurial on most +Unix systems: +</p> + +<pre> +sudo easy_install mercurial==2.0 +</pre> + +<p> +On Ubuntu/Debian, the Mercurial in your distribution's +package repository is most likely old and broken. +You might try this first: +</p> + +<pre>apt-get install python-setuptools python-dev build-essential</pre> + +<p> +If that fails, or if you use Windows, install manually from the +<a href="http://mercurial.selenic.com/wiki/Download">Mercurial Download</a> +page. +</p> + +<p> +Mercurial versions 1.7.x and up require the configuration of +<a href="http://mercurial.selenic.com/wiki/CACertificates">Certification Authorities</a> +(CAs). Error messages of the form: +</p> + +<pre> +warning: code.google.com certificate with fingerprint b1:af: ... bc not verified (check hostfingerprints or web.cacerts config setting) +</pre> + +<p> +when using Mercurial indicate that the CAs are missing. +Check your Mercurial version (<code>hg --version</code>) and +<a href="http://mercurial.selenic.com/wiki/CACertificates#Configuration_of_HTTPS_certificate_authorities">configure the CAs</a> +if necessary. +</p> + + +<h2 id="fetch">Fetch the repository</h2> + +<p>Go will install to a directory named <code>go</code>. +Change to the directory that will be its parent +and make sure the <code>go</code> directory does not exist. +Then check out the repository:</p> + +<pre> +$ hg clone -u release https://code.google.com/p/go +</pre> + +<h2 id="install">Install Go</h2> + +<p> +To build the Go distribution, run +</p> + +<pre> +$ cd go/src +$ ./all.bash +</pre> + +<p> +(To build under Windows use <code>all.bat</code>.) +</p> + +<p> +If all goes well, it will finish by printing output like: +</p> + +<pre> +ALL TESTS PASSED + +--- +Installed Go for linux/amd64 in /home/you/go. +Installed commands in /home/you/go/bin. +*** You need to add /home/you/go/bin to your $PATH. *** +The compiler is 6g. +</pre> + +<p> +where the details on the last few lines reflect the operating system, +architecture, and root directory used during the install. +</p> + +<div class="detail"> +<p> +For more information about ways to control the build, see the discussion of +<a href="#environment">environment variables</a> below. +</p> +</div> + + +<h2 id="testing">Testing your installation</h2> + +<p> +Check that Go is installed correctly by building a simple program. +</p> + +<p> +Create a file named <code>hello.go</code> and put the following program in it: +</p> + +<pre> +package main + +import "fmt" + +func main() { + fmt.Printf("hello, world\n") +} +</pre> + +<p> +Then run it with the <code>go</code> tool: +</p> + +<pre> +$ go run hello.go +hello, world +</pre> + +<p> +If you see the "hello, world" message then Go is installed correctly. +</p> + + +<h2 id="community">Community resources</h2> + +<p> +The usual community resources such as +<code>#go-nuts</code> on the <a href="http://freenode.net/">Freenode</a> IRC server +and the +<a href="http://groups.google.com/group/golang-nuts">Go Nuts</a> +mailing list have active developers that can help you with problems +with your installation or your development work. +For those who wish to keep up to date, +there is another mailing list, <a href="http://groups.google.com/group/golang-checkins">golang-checkins</a>, +that receives a message summarizing each checkin to the Go repository. +</p> + +<p> +Bugs can be reported using the <a href="http://code.google.com/p/go/issues/list">Go issue tracker</a>. +</p> + + +<h2 id="releases">Keeping up with releases</h2> + +<p> +The Go project maintains two stable tags in its Mercurial repository: +<code>release</code> and <code>weekly</code>. +</p> + +<p> +The <code>release</code> tag refers to the current stable release of Go. +Most Go users should use this version. New releases are announced on the +<a href="http://groups.google.com/group/golang-announce">golang-announce</a> +mailing list. +</p> + +<p> +To update an existing tree to the latest release, you can run: +</p> + +<pre> +$ cd go/src +$ hg pull +$ hg update release +$ ./all.bash +</pre> + +<p> +The <code>weekly</code> tag is updated about once a week, and should be used +only by those who are actively working on the Go core. +To use the <code>weekly</code> tag run <code>hg update weekly</code> instead. +</p> + + +<h2 id="environment">Optional environment variables</h2> + +<p> +The Go compilation environment can be customized by environment variables. +<i>None is required by the build</i>, but you may wish to set some +to override the defaults. +</p> + +<blockquote> + +<p><code>$GOROOT</code></p> +<p> +The root of the Go tree, often <code>$HOME/go</code>. +Its value is built into the tree when it is compiled, and +defaults to the parent of the directory where <code>all.bash</code> was run. +There is no need to set this unless you want to switch between multiple +local copies of the repository. +</p> + +<p><code>$GOROOT_FINAL</code></p> +<p> +The value assumed by installed binaries and scripts when +<code>$GOROOT</code> is not set explicitly. +It defaults to the value of <code>$GOROOT</code>. +If you want to build the Go tree in one location +but move it elsewhere after the build, set +<code>$GOROOT_FINAL</code> to the eventual location. +</p> + +<p><code>$GOOS</code> and <code>$GOARCH</code></p> +<p> +The name of the target operating system and compilation architecture. +These default to the values of <code>$GOHOSTOS</code> and +<code>$GOHOSTARCH</code> respectively (described below). + +<p> +Choices for <code>$GOOS</code> are +<code>darwin</code> (Mac OS X 10.6 and above), <code>freebsd</code>, +<code>linux</code>, <code>netbsd</code>, <code>openbsd</code>, +<code>plan9</code>, and <code>windows</code>. +Choices for <code>$GOARCH</code> are +<code>amd64</code> (64-bit x86, the most mature port), +<code>386</code> (32-bit x86), and <code>arm</code> (32-bit ARM). +The valid combinations of <code>$GOOS</code> and <code>$GOARCH</code> are: +<table cellpadding="0"> +<tr> +<th width="50"><th align="left" width="100"><code>$GOOS</code></th> <th align="left" width="100"><code>$GOARCH</code></th> <th align="left"></th> +</tr> +<tr> +<td></td><td><code>darwin</code></td> <td><code>386</code></td> +</tr> +<tr> +<td></td><td><code>darwin</code></td> <td><code>amd64</code></td> +</tr> +<tr> +<td></td><td><code>freebsd</code></td> <td><code>386</code></td> +</tr> +<tr> +<td></td><td><code>freebsd</code></td> <td><code>amd64</code></td> +</tr> +<tr> +<td></td><td><code>linux</code></td> <td><code>386</code></td> +</tr> +<tr> +<td></td><td><code>linux</code></td> <td><code>amd64</code></td> +</tr> +<tr> +<td></td><td><code>linux</code></td> <td><code>arm</code></td> +</tr> +<tr> +<td></td><td><code>netbsd</code></td> <td><code>386</code></td> +</tr> +<tr> +<td></td><td><code>netbsd</code></td> <td><code>amd64</code></td> +</tr> +<tr> +<td></td><td><code>openbsd</code></td> <td><code>386</code></td> +</tr> +<tr> +<td></td><td><code>openbsd</code></td> <td><code>amd64</code></td> +</tr> +<tr> +<td></td><td><code>plan9</code></td> <td><code>386</code></td> +</tr> +<tr> +<td></td><td><code>windows</code></td> <td><code>386</code></td> +</tr> +<tr> +<td></td><td><code>windows</code></td> <td><code>amd64</code></td> +</tr> +</table> + +<p><code>$GOHOSTOS</code> and <code>$GOHOSTARCH</code></p> +<p> +The name of the host operating system and compilation architecture. +These default to the local system's operating system and +architecture. +</p> + +<p> +Valid choices are the same as for <code>$GOOS</code> and +<code>$GOARCH</code>, listed above. +The specified values must be compatible with the local system. +For example, you should not set <code>$GOHOSTARCH</code> to +<code>arm</code> on an x86 system. +</p> + +<p><code>$GOBIN</code> +<p> +The location where Go binaries will be installed. +The default is <code>$GOROOT/bin</code>. +After installing, you will want to arrange to add this +directory to your <code>$PATH</code>, so you can use the tools. +If <code>$GOBIN</code> is set, the <a href="/cmd/go">go command</a> +installs all commands there. +</p> + +<p><code>$GOARM</code> (arm, default=6)</p> +<p> +The ARM architecture version the run-time libraries should target. +Setting <code>$GOARM</code> to 5 causes the linker to emit calls +to a software floating point implementation instead of using +hardware floating point support. +</p> + +</blockquote> + +<p> +Note that <code>$GOARCH</code> and <code>$GOOS</code> identify the +<em>target</em> environment, not the environment you are running on. +In effect, you are always cross-compiling. +By architecture, we mean the kind of binaries +that the target environment can run: +an x86-64 system running a 32-bit-only operating system +must set <code>GOARCH</code> to <code>386</code>, +not <code>amd64</code>. +</p> + +<p> +If you choose to override the defaults, +set these variables in your shell profile (<code>$HOME/.bashrc</code>, +<code>$HOME/.profile</code>, or equivalent). The settings might look +something like this: +</p> + +<pre> +export GOROOT=$HOME/go +export GOARCH=amd64 +export GOOS=linux +</pre> + +<p> +although, to reiterate, none of these variables needs to be set to build, +install, and develop the Go tree. +</p> diff --git a/doc/install.html b/doc/install.html index c47f9218b..ad3eaf338 100644 --- a/doc/install.html +++ b/doc/install.html @@ -1,314 +1,237 @@ -<!-- Getting Started --> +<!--{ + "Title": "Getting Started", + "Path": "/doc/install" +}--> <h2 id="introduction">Introduction</h2> -<p>Go is an open source project, distributed under a -<a href="/LICENSE">BSD-style license</a>. -This document explains how to check out the sources, -build them on your own machine, and run them. +<p> +Go is an open source project with a BSD-style license. +There are two official Go compiler toolchains: the <code>gc</code> Go compiler +and the <code>gccgo</code> compiler that is part of the GNU C Compiler (GCC). </p> -<div class="detail"> - <p> -There are two distinct ways to experiment with Go. -This document focuses on the <code>gc</code> Go -compiler and tools (<code>6g</code>, <code>8g</code> etc.). -For information on how to use <code>gccgo</code>, a more traditional -compiler using the GCC back end, see -<a href="gccgo_install.html">Setting up and using gccgo</a>. +The <code>gc</code> compiler is the more mature and well-tested of the two. +This page is about installing a binary distribution of the <code>gc</code> +compiler. </p> <p> -The Go compilers support three instruction sets. -There are important differences in the quality of the compilers for the different -architectures. +For information about installing the <code>gc</code> compiler from source, see +<a href="/doc/install/source">Installing Go from source</a>. +For information about installing <code>gccgo</code>, see +<a href="/doc/install/gccgo">Setting up and using gccgo</a>. </p> -<dl> -<dt> - <code>amd64</code> (a.k.a. <code>x86-64</code>); <code>6g,6l,6c,6a</code> -</dt> -<dd> - The most mature implementation. The compiler has an effective optimizer - (registerizer) and generates good code (although <code>gccgo</code> - can do noticeably better sometimes). -</dd> -<dt> - <code>386</code> (a.k.a. <code>x86</code> or <code>x86-32</code>); <code>8g,8l,8c,8a</code> -</dt> -<dd> - Comparable to the <code>amd64</code> port. -</dd> -<dt> - <code>arm</code> (a.k.a. <code>ARM</code>); <code>5g,5l,5c,5a</code> -</dt> -<dd> - Incomplete. - It only supports Linux binaries, the optimizer is incomplete, - and floating point uses the VFP unit. - However, all tests pass. - Work on the optimizer is continuing. - Tested against a Nexus One. -</dd> -</dl> +<h2 id="download">Download the Go tools</h2> <p> -Except for things like low-level operating system interface code, the run-time -support is the same in all ports and includes a mark-and-sweep garbage collector -(a fancier one is in the works), efficient array and string slicing, -support for segmented stacks, and a strong goroutine implementation. +Visit the +<a href="http://code.google.com/p/go/downloads">Go project's downloads page</a> +and select the binary distribution that matches +your operating system and processor architecture. </p> <p> -The compilers can target the FreeBSD, Linux, -and OS X (a.k.a. Darwin) operating systems. -(A port to Microsoft Windows is in progress but incomplete. See the -<a href="http://code.google.com/p/go/wiki/WindowsPort">Windows Port</a> -page for details.) -The full set of supported combinations is listed in the discussion of -<a href="#environment">environment variables</a> below. +Official binary distributions are available +for the FreeBSD, Linux, Mac OS X (Snow Leopard/Lion), and Windows operating systems +and the 32-bit (<code>386</code>) and 64-bit (<code>amd64</code>) +x86 processor architectures. </p> -</div> - -<h2 id="ctools">Install C tools, if needed</h2> - -<p>The Go tool chain is written in C. -To build it, you need these programs installed: -<ul> -<li>GCC, -<li>the standard C libraries, -<li>the parser generator Bison, -<li>GNU <tt>make</tt> (version 3.81 or later), -and -<li><tt>awk</tt>. -</ul> +<p> +If a binary distribution is not available for your +OS/arch combination you may want to try +<a href="/doc/install/source">installing from source</a> or +<a href="/doc/install/gccgo">installing gccgo instead of gc</a>. </p> -<p>On OS X, they can be -installed as part of -<a href="http://developer.apple.com/TOOLS/Xcode/">Xcode</a>. -</p> +<h2 id="install">Install the Go tools</h2> -<p>On Ubuntu/Debian, use <code>sudo apt-get install bison gawk gcc libc6-dev -make</code>. If you want to build 32-bit binaries on a 64-bit system you'll -also need the <code>libc6-dev-i386</code> package. +<p> +The Go binary distributions assume they will be installed in +<code>/usr/local/go</code> (or <code>c:\Go</code> under Windows), +but it is possible to install them in a different +location. If you do this, you will need to set the <code>GOROOT</code> +environment variable to that directory when using the Go tools. </p> -<h2 id="mercurial">Install Mercurial, if needed</h2> - <p> -To perform the next step you must have Mercurial installed. (Check that you have an <code>hg</code> command.) This suffices to install Mercurial on most systems: +For example, if you installed Go to your home directory you should add the +following commands to <code>$HOME/.profile</code>: </p> + <pre> -sudo easy_install mercurial +export GOROOT=$HOME/go +export PATH=$PATH:$GOROOT/bin </pre> -(On Ubuntu/Debian, you might try <code>apt-get install python-setuptools -python-dev build-essential</code> first. The Mercurial in your distribution's -package repository will most likely be old and broken.) -</p> + <p> -If that fails, try installing manually from the <a href="http://mercurial.selenic.com/wiki/Download">Mercurial Download</a> page.</p> +Windows users should read the section about <a href="#windows_env">setting +environment variables under Windows</a>. </p> +<h3 id="freebsd_linux">FreeBSD and Linux</h3> + <p> -Mercurial versions 1.7.x and up require the configuration of -<a href="http://mercurial.selenic.com/wiki/CACertificates">Certification Authorities</a> -(CAs). Error messages of the form: +On FreeBSD and Linux, if you are upgrading from an older version of Go you must +first remove the existing version from <code>/usr/local/go</code>: </p> + <pre> -warning: go.googlecode.com certificate with fingerprint b1:af: ... bc not verified (check hostfingerprints or web.cacerts config setting) +rm -r /usr/local/go </pre> -<p> -when using Mercurial indicate that the CAs are missing. -Check your Mercurial version (<code>hg --version</code>) and -<a href="http://mercurial.selenic.com/wiki/CACertificates#Configuration_of_HTTPS_certificate_authorities">configure the CAs</a> -if necessary. -</p> - -<h2 id="fetch">Fetch the repository</h2> <p> -<p>Go will install to a directory named <code>go</code>. -Change to the directory that will be its parent -and make sure the <code>go</code> directory does not exist. -Then check out the repository:</p> +Extract <a href="http://code.google.com/p/go/downloads/list?q=OpSys-FreeBSD+OR+OpSys-Linux">the archive</a> +into <code>/usr/local</code>, creating a Go tree in <code>/usr/local/go</code>: +</p> <pre> -$ hg clone -u release https://go.googlecode.com/hg/ go +tar -C /usr/local -xzf go.release.go1.tar.gz </pre> -<h2 id="install">Install Go</h2> +<p> +(Typically these commands must be run as root or through <code>sudo</code>.) +</p> <p> -To build the Go distribution, run +Add <code>/usr/local/go/bin</code> to the <code>PATH</code> environment +variable. You can do this by adding this line to your <code>/etc/profile</code> +(for a system-wide installation) or <code>$HOME/.profile</code>: </p> <pre> -$ cd go/src -$ ./all.bash +export PATH=$PATH:/usr/local/go/bin </pre> +<h3 id="osx">Mac OS X</h3> + <p> -If all goes well, it will finish by printing output like: +Open the <a href="http://code.google.com/p/go/downloads/list?q=OpSys-Darwin">package file</a> +and follow the prompts to install the Go tools. +The package installs the Go distribution to <code>/usr/local/go</code>. </p> -<pre> -ALL TESTS PASSED +<p> +The package should put the <code>/usr/local/go/bin</code> directory in your +<code>PATH</code> environment variable. You may need to restart any open +Terminal sessions for the change to take effect. +</p> ---- -Installed Go for linux/amd64 in /home/you/go. -Installed commands in /home/you/go/bin. -*** You need to add /home/you/go/bin to your $PATH. *** -The compiler is 6g. -</pre> +<h3 id="windows">Windows</h3> <p> -where the details on the last few lines reflect the operating system, -architecture, and root directory used during the install. +The Go project provides two installation options for Windows users +(besides <a href="/doc/install/source">installing from source</a>): +a zip archive that requires you to set some environment variables and an +experimental MSI installer that configures your installation automatically. </p> -<div class="detail"> +<h4 id="windows_zip">Zip archive</h3> -<p>For more information about ways to control the build, -see the discussion of <a href="#environment">environment variables</a> below.</p> -</div> +<p> +Extract the <a href="http://code.google.com/p/go/downloads/list?q=OpSys-Windows+Type%3DArchive">zip file</a> +to the directory of your choice (we suggest <code>c:\Go</code>). +</p> -<h2 id="writing">Writing programs</h2> +<p> +If you chose a directory other than <code>c:\Go</code>, you must set +the <code>GOROOT</code> environment variable to your chosen path. +</p> <p> -Given a file <code>file.go</code>, compile it using +Add the <code>bin</code> subdirectory of your Go root (for example, <code>c:\Go\bin</code>) to to your <code>PATH</code> environment variable. </p> -<pre> -$ 6g file.go -</pre> +<h4 id="windows_msi">MSI installer (experimental)</h3> <p> -<code>6g</code> is the Go compiler for <code>amd64</code>; it will write the output -in <code>file.6</code>. The ‘<code>6</code>’ identifies -files for the <code>amd64</code> architecture. -The identifier letters for <code>386</code> and <code>arm</code> -are ‘<code>8</code>’ and ‘<code>5</code>’. -That is, if you were compiling for <code>386</code>, you would use -<code>8g</code> and the output would be named <code>file.8</code>. +Open the <a href="http://code.google.com/p/go/downloads/list?q=OpSys-Windows+Type%3DInstaller">MSI file</a> +and follow the prompts to install the Go tools. +By default, the installer puts the Go distribution in <code>c:\Go</code>. </p> <p> -To link the file, use +The installer should put the <code>c:\Go\bin</code> directory in your +<code>PATH</code> environment variable. You may need to restart any open +command prompts for the change to take effect. </p> -<pre> -$ 6l file.6 -</pre> +<h4 id="windows_env">Setting environment variables under Windows</h4> <p> -and to run it +Under Windows, you may set environment variables through the "Environment +Variables" button on the "Advanced" tab of the "System" control panel. Some +versions of Windows provide this control panel through the "Advanced System +Settings" option inside the "System" control panel. </p> -<pre> -$ ./6.out -</pre> +<h2 id="testing">Test your installation</h2> -<p>A complete example: +<p> +Check that Go is installed correctly by building a simple program, as follows. +</p> + +<p> +Create a file named <code>hello.go</code> and put the following program in it: </p> <pre> -$ cat >hello.go <<EOF package main import "fmt" func main() { - fmt.Printf("hello, world\n") + fmt.Printf("hello, world\n") } -EOF -$ 6g hello.go -$ 6l hello.6 -$ ./6.out -hello, world -$ </pre> <p> -There is no need to list <code>hello.6</code>'s package dependencies -(in this case, package <code>fmt</code>) on the <code>6l</code> -command line. -The linker learns about them by reading <code>hello.6</code>. +Then run it with the <code>go</code> tool: </p> -<div class="detail"> +<pre> +$ go run hello.go +hello, world +</pre> + <p> -To build more complicated programs, you will probably -want to use a -<code>Makefile</code>. -There are examples in places like -<code>go/src/cmd/godoc/Makefile</code> -and <code>go/src/pkg/*/Makefile</code>. -The -<a href="contribute.html">document</a> -about contributing to the Go project -gives more detail about -the process of building and testing Go programs. +If you see the "hello, world" message then your Go installation is working. </p> -</div> <h2 id="next">What's next</h2> <p> -Start by taking <a href="http://code.google.com/p/go-tour/">A Tour of Go</a> -or reading the <a href="go_tutorial.html">Go Tutorial</a>. +Start by taking <a href="http://code.google.com/p/go-tour/">A Tour of Go</a>. </p> <p> -Build a web application by following the <a href="codelab/wiki/">Wiki -Codelab</a>. +For more detail about the process of building and testing Go programs +read <a href="/doc/code.html">How to Write Go Code</a>. </p> <p> -Read <a href="effective_go.html">Effective Go</a> to learn about writing -idiomatic Go code. +Build a web application by following the <a href="/doc/articles/wiki/">Wiki +Tutorial</a>. </p> <p> -For the full story, consult Go's extensive -<a href="docs.html">documentation</a>. +Read <a href="/doc/effective_go.html">Effective Go</a> to learn about writing +idiomatic Go code. </p> -<h2 id="releases">Keeping up with releases</h2> - <p> -The Go project maintains two stable tags in its Mercurial repository: -<code>release</code> and <code>weekly</code>. -The <code>weekly</code> tag is updated about once a week, and should be used by -those who want to track the project's development. -The <code>release</code> tag is given, less often, to those weekly releases -that have proven themselves to be robust. +For the full story, consult Go's extensive <a href="/doc/">documentation</a>. </p> <p> -Most Go users will want to keep their Go installation at the latest -<code>release</code> tag. -New releases are announced on the +Subscribe to the <a href="http://groups.google.com/group/golang-announce">golang-announce</a> -mailing list. +mailing list to be notified when a new stable version of Go is released. </p> -<p> -To update an existing tree to the latest release, you can run: -</p> - -<pre> -$ cd go/src -$ hg pull -$ hg update release -$ ./all.bash -</pre> - -<p> -To use the <code>weekly</code> tag run <code>hg update weekly</code> instead. -</p> <h2 id="community">Community resources</h2> @@ -323,153 +246,6 @@ The official mailing list for discussion of the Go language is </p> <p> -Bugs can be reported using the <a href="http://code.google.com/p/go/issues/list">Go issue tracker</a>. -</p> - -<p> -For those who wish to keep up with development, -there is another mailing list, <a href="http://groups.google.com/group/golang-checkins">golang-checkins</a>, -that receives a message summarizing each checkin to the Go repository. -</p> - -<h2 id="environment">Environment variables</h2> - -<p> -The Go compilation environment can be customized by environment variables. -None are required by the build, but you may wish to set them -to override the defaults. -</p> - -<dl> -<dt> - <code>$GOROOT</code> -</dt> -<dd> - The root of the Go tree, often <code>$HOME/go</code>. - This defaults to the parent of the directory where <code>all.bash</code> is run. - If you choose not to set <code>$GOROOT</code>, you must - run <code>gomake</code> instead of <code>make</code> or <code>gmake</code> - when developing Go programs using the conventional makefiles. -</dd> - -<dt> - <code>$GOROOT_FINAL</code> -</dt> -<dd> - The value assumed by installed binaries and scripts when - <code>$GOROOT</code> is not set. - It defaults to the value used for <code>$GOROOT</code>. - If you want to build the Go tree in one location - but move it elsewhere after the build, set - <code>$GOROOT_FINAL</code> to the eventual location. -</dd> - -<dt> -<code>$GOOS</code> and <code>$GOARCH</code> -</dt> -<dd> - The name of the target operating system and compilation architecture. - These default to the values of <code>$GOHOSTOS</code> and - <code>$GOHOSTARCH</code> respectively (described below). - - <p> - Choices for <code>$GOOS</code> are <code>linux</code>, - <code>freebsd</code>, - <code>darwin</code> (Mac OS X 10.5 or 10.6), - and <code>windows</code> (Windows, an incomplete port). - Choices for <code>$GOARCH</code> are <code>amd64</code> (64-bit x86, the most mature port), - <code>386</code> (32-bit x86), and - <code>arm</code> (32-bit ARM, an incomplete port). - The valid combinations of <code>$GOOS</code> and <code>$GOARCH</code> are: - <table cellpadding="0"> - <tr> - <th width="50"><th align="left" width="100"><code>$GOOS</code></th> <th align="left" width="100"><code>$GOARCH</code></th> <th align="left"></th> - </tr> - <tr> - <td></td><td><code>darwin</code></td> <td><code>386</code></td> - </tr> - <tr> - <td></td><td><code>darwin</code></td> <td><code>amd64</code></td> - </tr> - <tr> - <td></td><td><code>freebsd</code></td> <td><code>386</code></td> - </tr> - <tr> - <td></td><td><code>freebsd</code></td> <td><code>amd64</code></td> - </tr> - <tr> - <td></td><td><code>linux</code></td> <td><code>386</code></td> - </tr> - <tr> - <td></td><td><code>linux</code></td> <td><code>amd64</code></td> - </tr> - <tr> - <td></td><td><code>linux</code></td> <td><code>arm</code></td> <td><i>incomplete</i></td> - </tr> - <tr> - <td></td><td><code>windows</code></td> <td><code>386</code></td> <td><i>incomplete</i></td> - </tr> - </table> -</dd> - -<dt> -<code>$GOHOSTOS</code> and <code>$GOHOSTARCH</code> -</dt> -<dd> - The name of the host operating system and compilation architecture. - These default to the local system's operating system and - architecture. - - <p> - Valid choices are the same as for <code>$GOOS</code> and - <code>$GOARCH</code>, listed above. - The specified values must be compatible with the local system. - For example, you should not set <code>$GOHOSTARCH</code> to - <code>arm</code> on an x86 system. -</dd> - -<dt> -<code>$GOBIN</code> -</dt> -<dd> - The location where binaries will be installed. - The default is <code>$GOROOT/bin</code>. - After installing, you will want to arrange to add this - directory to your <code>$PATH</code>, so you can use the tools. -</dd> - -<dt> -<code>$GOARM</code> (arm, default=6) -</dt> -<dd> - The ARM architecture version the run-time libraries should target. - ARMv6 cores have more efficient synchronization primitives. Setting - <code>$GOARM</code> to 5 will compile the run-time libraries using - just SWP instructions that work on older architectures as well. - Running v6 code on an older core will cause an illegal instruction trap. -</dd> -</dl> - -<p> -Note that <code>$GOARCH</code> and <code>$GOOS</code> identify the -<em>target</em> environment, not the environment you are running on. -In effect, you are always cross-compiling. -By architecture, we mean the kind of binaries -that the target environment can run: -an x86-64 system running a 32-bit-only operating system -must set <code>GOARCH</code> to <code>386</code>, -not <code>amd64</code>. -</p> - -<p> -If you choose to override the defaults, -set these variables in your shell profile (<code>$HOME/.bashrc</code>, -<code>$HOME/.profile</code>, or equivalent). The settings might look -something like this: +Bugs should be reported using the +<a href="http://code.google.com/p/go/issues/list">Go issue tracker</a>. </p> - -<pre> -export GOROOT=$HOME/go -export GOARCH=386 -export GOOS=linux -</pre> diff --git a/doc/logo-153x55.png b/doc/logo-153x55.png Binary files differindex 4a2446ce7..8ec22aa6d 100644 --- a/doc/logo-153x55.png +++ b/doc/logo-153x55.png diff --git a/doc/logo.png b/doc/logo.png Binary files differdeleted file mode 100644 index 076ce398e..000000000 --- a/doc/logo.png +++ /dev/null diff --git a/doc/makehtml b/doc/makehtml deleted file mode 100755 index 2418c68fa..000000000 --- a/doc/makehtml +++ /dev/null @@ -1,17 +0,0 @@ -#!/bin/sh -# Copyright 2009 The Go Authors. All rights reserved. -# Use of this source code is governed by a BSD-style -# license that can be found in the LICENSE file. - -set -e - -TMPL=${1:-go_tutorial.tmpl} # input file -HTML=$(basename $TMPL .tmpl).html # output file (basename) - -if ! test -w $HTML -then - echo 1>&2 makehtml: cannot open $HTML for write - exit 1 -fi - -make && ./tmpltohtml $TMPL > $HTML diff --git a/doc/play/fib.go b/doc/play/fib.go new file mode 100644 index 000000000..42da9ce82 --- /dev/null +++ b/doc/play/fib.go @@ -0,0 +1,17 @@ +package main + +// fib returns a function that returns +// successive Fibonacci numbers. +func fib() func() int { + a, b := 0, 1 + return func() int { + a, b = b, a+b + return a + } +} + +func main() { + f := fib() + // Function calls are evaluated left-to-right. + println(f(), f(), f(), f(), f()) +} diff --git a/doc/play/hello.go b/doc/play/hello.go new file mode 100644 index 000000000..078ddff8f --- /dev/null +++ b/doc/play/hello.go @@ -0,0 +1,7 @@ +package main + +import "fmt" + +func main() { + fmt.Println("Hello, 世界") +} diff --git a/doc/play/peano.go b/doc/play/peano.go new file mode 100644 index 000000000..c1ee5ad45 --- /dev/null +++ b/doc/play/peano.go @@ -0,0 +1,88 @@ +// Peano integers are represented by a linked +// list whose nodes contain no data +// (the nodes are the data). +// http://en.wikipedia.org/wiki/Peano_axioms + +// This program demonstrates the power of Go's +// segmented stacks when doing massively +// recursive computations. + +package main + +import "fmt" + +// Number is a pointer to a Number +type Number *Number + +// The arithmetic value of a Number is the +// count of the nodes comprising the list. +// (See the count function below.) + +// ------------------------------------- +// Peano primitives + +func zero() *Number { + return nil +} + +func isZero(x *Number) bool { + return x == nil +} + +func add1(x *Number) *Number { + e := new(Number) + *e = x + return e +} + +func sub1(x *Number) *Number { + return *x +} + +func add(x, y *Number) *Number { + if isZero(y) { + return x + } + return add(add1(x), sub1(y)) +} + +func mul(x, y *Number) *Number { + if isZero(x) || isZero(y) { + return zero() + } + return add(mul(x, sub1(y)), x) +} + +func fact(n *Number) *Number { + if isZero(n) { + return add1(zero()) + } + return mul(fact(sub1(n)), n) +} + +// ------------------------------------- +// Helpers to generate/count Peano integers + +func gen(n int) *Number { + if n > 0 { + return add1(gen(n - 1)) + } + return zero() +} + +func count(x *Number) int { + if isZero(x) { + return 0 + } + return count(sub1(x)) + 1 +} + +// ------------------------------------- +// Print i! for i in [0,9] + +func main() { + for i := 0; i <= 9; i++ { + f := count(fact(gen(i))) + fmt.Println(i, "! =", f) + } +} diff --git a/doc/play/pi.go b/doc/play/pi.go new file mode 100644 index 000000000..f2f5dca74 --- /dev/null +++ b/doc/play/pi.go @@ -0,0 +1,34 @@ +// Concurrent computation of pi. +// See http://goo.gl/ZuTZM. +// +// This demonstrates Go's ability to handle +// large numbers of concurrent processes. +// It is an unreasonable way to calculate pi. +package main + +import ( + "fmt" + "math" +) + +func main() { + fmt.Println(pi(5000)) +} + +// pi launches n goroutines to compute an +// approximation of pi. +func pi(n int) float64 { + ch := make(chan float64) + for k := 0; k <= n; k++ { + go term(ch, float64(k)) + } + f := 0.0 + for k := 0; k <= n; k++ { + f += <-ch + } + return f +} + +func term(ch chan float64, k float64) { + ch <- 4 * math.Pow(-1, k) / (2*k + 1) +} diff --git a/doc/play/playground.js b/doc/play/playground.js new file mode 100644 index 000000000..947f8a4ec --- /dev/null +++ b/doc/play/playground.js @@ -0,0 +1,234 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// opts is an object with these keys +// codeEl - code editor element +// outputEl - program output element +// runEl - run button element +// shareEl - share button element (optional) +// shareURLEl - share URL text input element (optional) +// shareRedirect - base URL to redirect to on share (optional) +// preCompile - callback to mutate request data before compiling +// postCompile - callback to read response data after compiling +// simple - use plain textarea instead of CodeMirror. +// toysEl - select element with a list of toys. +function playground(opts) { + var simple = opts['simple']; + var code = $(opts['codeEl']); + var editor; + + // autoindent helpers for simple mode. + function insertTabs(n) { + // find the selection start and end + var start = code[0].selectionStart; + var end = code[0].selectionEnd; + // split the textarea content into two, and insert n tabs + var v = code[0].value; + var u = v.substr(0, start); + for (var i=0; i<n; i++) { + u += "\t"; + } + u += v.substr(end); + // set revised content + code[0].value = u; + // reset caret position after inserted tabs + code[0].selectionStart = start+n; + code[0].selectionEnd = start+n; + } + function autoindent(el) { + var curpos = el.selectionStart; + var tabs = 0; + while (curpos > 0) { + curpos--; + if (el.value[curpos] == "\t") { + tabs++; + } else if (tabs > 0 || el.value[curpos] == "\n") { + break; + } + } + setTimeout(function() { + insertTabs(tabs, 1); + }, 1); + } + + function keyHandler(e) { + if (simple && e.keyCode == 9) { // tab + insertTabs(1); + e.preventDefault(); + return false; + } + if (e.keyCode == 13) { // enter + if (e.shiftKey) { // +shift + run(); + e.preventDefault(); + return false; + } else if (simple) { + autoindent(e.target); + } + } + return true; + } + if (simple) { + code.unbind('keydown').bind('keydown', keyHandler); + } else { + editor = CodeMirror.fromTextArea( + code[0], + { + lineNumbers: true, + indentUnit: 8, + indentWithTabs: true, + onKeyEvent: function(editor, e) { keyHandler(e); } + } + ); + } + var output = $(opts['outputEl']); + + function clearErrors() { + if (!editor) { + return; + } + var lines = editor.lineCount(); + for (var i = 0; i < lines; i++) { + editor.setLineClass(i, null); + } + } + function highlightErrors(text) { + if (!editor) { + return; + } + var errorRe = /[a-z]+\.go:([0-9]+): /g; + var result; + while ((result = errorRe.exec(text)) != null) { + var line = result[1]*1-1; + editor.setLineClass(line, "errLine") + } + } + function body() { + if (editor) { + return editor.getValue(); + } + return $(opts['codeEl']).val(); + } + function setBody(text) { + if (editor) { + editor.setValue(text); + return; + } + $(opts['codeEl']).val(text); + } + function origin(href) { + return (""+href).split("/").slice(0, 3).join("/"); + } + + var seq = 0; + function run() { + clearErrors(); + output.removeClass("error").html( + '<div class="loading">Waiting for remote server...</div>' + ); + seq++; + var cur = seq; + var data = {"body": body()}; + if (opts['preCompile']) { + opts['preCompile'](data); + } + $.ajax("/compile", { + data: data, + type: "POST", + dataType: "json", + success: function(data) { + if (seq != cur) { + return; + } + pre = $("<pre/>"); + output.empty().append(pre); + if (opts['postCompile']) { + opts['postCompile'](data); + } + if (!data) { + return; + } + if (data.compile_errors != "") { + pre.text(data.compile_errors); + output.addClass("error"); + highlightErrors(data.compile_errors); + return; + } + var out = ""+data.output; + if (out.indexOf("IMAGE:") == 0) { + var img = $("<img/>"); + var url = "data:image/png;base64,"; + url += out.substr(6) + img.attr("src", url); + output.empty().append(img); + return; + } + pre.text(out); + }, + error: function(xhr) { + var text = "Error communicating with remote server."; + console.log(xhr.status); + if (xhr.status == 501) { + text = xhr.responseText; + } + output.addClass("error").text(text); + } + }); + } + $(opts['runEl']).click(run); + + if (opts['shareEl'] != null && (opts['shareURLEl'] != null || opts['shareRedirect'] != null)) { + var shareURL; + if (opts['shareURLEl']) { + shareURL = $(opts['shareURLEl']).hide(); + } + var sharing = false; + $(opts['shareEl']).click(function() { + if (sharing) return; + sharing = true; + $.ajax("/share", { + processData: false, + data: body(), + type: "POST", + complete: function(xhr) { + sharing = false; + if (xhr.status == 501) { + alert(xhr.responseText); + return; + } + if (xhr.status != 200) { + alert("Server error; try again."); + return; + } + if (opts['shareRedirect']) { + window.location = opts['shareRedirect'] + xhr.responseText; + } + if (shareURL) { + var url = origin(window.location) + "/p/" + xhr.responseText; + shareURL.show().val(url).focus().select(); + } + } + }); + }); + } + + if (opts['toysEl'] != null) { + $(opts['toysEl']).bind('change', function() { + var toy = $(this).val(); + $.ajax("/doc/play/"+toy, { + processData: false, + type: "GET", + complete: function(xhr) { + if (xhr.status != 200) { + alert("Server error; try again.") + return; + } + setBody(xhr.responseText); + } + }); + }); + } + + return editor; +} diff --git a/doc/play/sieve.go b/doc/play/sieve.go new file mode 100644 index 000000000..585507ac4 --- /dev/null +++ b/doc/play/sieve.go @@ -0,0 +1,34 @@ +// A concurrent prime sieve + +package main + +// Send the sequence 2, 3, 4, ... to channel 'ch'. +func Generate(ch chan<- int) { + for i := 2; ; i++ { + ch <- i // Send 'i' to channel 'ch'. + } +} + +// Copy the values from channel 'in' to channel 'out', +// removing those divisible by 'prime'. +func Filter(in <-chan int, out chan<- int, prime int) { + for { + i := <-in // Receive value from 'in'. + if i%prime != 0 { + out <- i // Send 'i' to 'out'. + } + } +} + +// The prime sieve: Daisy-chain Filter processes. +func main() { + ch := make(chan int) // Create a new channel. + go Generate(ch) // Launch Generate goroutine. + for i := 0; i < 10; i++ { + prime := <-ch + print(prime, "\n") + ch1 := make(chan int) + go Filter(ch, ch1, prime) + ch = ch1 + } +} diff --git a/doc/play/solitaire.go b/doc/play/solitaire.go new file mode 100644 index 000000000..759d54281 --- /dev/null +++ b/doc/play/solitaire.go @@ -0,0 +1,117 @@ +// This program solves the (English) peg +// solitaire board game. +// http://en.wikipedia.org/wiki/Peg_solitaire + +package main + +import "fmt" + +const N = 11 + 1 // length of a row (+1 for \n) + +// The board must be surrounded by 2 illegal +// fields in each direction so that move() +// doesn't need to check the board boundaries. +// Periods represent illegal fields, +// ● are pegs, and ○ are holes. + +var board = []rune( + `........... +........... +....●●●.... +....●●●.... +..●●●●●●●.. +..●●●○●●●.. +..●●●●●●●.. +....●●●.... +....●●●.... +........... +........... +`) + +// center is the position of the center hole if +// there is a single one; otherwise it is -1. +var center int + +func init() { + n := 0 + for pos, field := range board { + if field == '○' { + center = pos + n++ + } + } + if n != 1 { + center = -1 // no single hole + } +} + +var moves int // number of times move is called + +// move tests if there is a peg at position pos that +// can jump over another peg in direction dir. If the +// move is valid, it is executed and move returns true. +// Otherwise, move returns false. +func move(pos, dir int) bool { + moves++ + if board[pos] == '●' && board[pos+dir] == '●' && board[pos+2*dir] == '○' { + board[pos] = '○' + board[pos+dir] = '○' + board[pos+2*dir] = '●' + return true + } + return false +} + +// unmove reverts a previously executed valid move. +func unmove(pos, dir int) { + board[pos] = '●' + board[pos+dir] = '●' + board[pos+2*dir] = '○' +} + +// solve tries to find a sequence of moves such that +// there is only one peg left at the end; if center is +// >= 0, that last peg must be in the center position. +// If a solution is found, solve prints the board after +// each move in a backward fashion (i.e., the last +// board position is printed first, all the way back to +// the starting board position). +func solve() bool { + var last, n int + for pos, field := range board { + // try each board position + if field == '●' { + // found a peg + for _, dir := range [...]int{-1, -N, +1, +N} { + // try each direction + if move(pos, dir) { + // a valid move was found and executed, + // see if this new board has a solution + if solve() { + unmove(pos, dir) + println(string(board)) + return true + } + unmove(pos, dir) + } + } + last = pos + n++ + } + } + // tried each possible move + if n == 1 && (center < 0 || last == center) { + // there's only one peg left + println(string(board)) + return true + } + // no solution found for this board + return false +} + +func main() { + if !solve() { + fmt.Println("no solution found") + } + fmt.Println(moves, "moves tried") +} diff --git a/doc/play/tree.go b/doc/play/tree.go new file mode 100644 index 000000000..5bcbf05a8 --- /dev/null +++ b/doc/play/tree.go @@ -0,0 +1,100 @@ +// Go's concurrency primitives make it easy to +// express concurrent concepts, such as +// this binary tree comparison. +// +// Trees may be of different shapes, +// but have the same contents. For example: +// +// 4 6 +// 2 6 4 7 +// 1 3 5 7 2 5 +// 1 3 +// +// This program compares a pair of trees by +// walking each in its own goroutine, +// sending their contents through a channel +// to a third goroutine that compares them. + +package main + +import ( + "fmt" + "math/rand" +) + +// A Tree is a binary tree with integer values. +type Tree struct { + Left *Tree + Value int + Right *Tree +} + +// Walk traverses a tree depth-first, +// sending each Value on a channel. +func Walk(t *Tree, ch chan int) { + if t == nil { + return + } + Walk(t.Left, ch) + ch <- t.Value + Walk(t.Right, ch) +} + +// Walker launches Walk in a new goroutine, +// and returns a read-only channel of values. +func Walker(t *Tree) <-chan int { + ch := make(chan int) + go func() { + Walk(t, ch) + close(ch) + }() + return ch +} + +// Compare reads values from two Walkers +// that run simultaneously, and returns true +// if t1 and t2 have the same contents. +func Compare(t1, t2 *Tree) bool { + c1, c2 := Walker(t1), Walker(t2) + for { + v1, ok1 := <-c1 + v2, ok2 := <-c2 + if !ok1 || !ok2 { + return ok1 == ok2 + } + if v1 != v2 { + break + } + } + return false +} + +// New returns a new, random binary tree +// holding the values 1k, 2k, ..., nk. +func New(n, k int) *Tree { + var t *Tree + for _, v := range rand.Perm(n) { + t = insert(t, (1+v)*k) + } + return t +} + +func insert(t *Tree, v int) *Tree { + if t == nil { + return &Tree{nil, v, nil} + } + if v < t.Value { + t.Left = insert(t.Left, v) + return t + } + t.Right = insert(t.Right, v) + return t +} + +func main() { + t1 := New(100, 1) + fmt.Println(Compare(t1, New(100, 1)), "Same Contents") + fmt.Println(Compare(t1, New(99, 1)), "Differing Sizes") + fmt.Println(Compare(t1, New(100, 2)), "Differing Values") + fmt.Println(Compare(t1, New(101, 2)), "Dissimilar") +} diff --git a/doc/play_overlay.png b/doc/play_overlay.png Binary files differdeleted file mode 100644 index 20ef7f399..000000000 --- a/doc/play_overlay.png +++ /dev/null diff --git a/doc/playground.html b/doc/playground.html deleted file mode 100644 index 01d3adc9c..000000000 --- a/doc/playground.html +++ /dev/null @@ -1,27 +0,0 @@ -<!-- About the Go Playground --> - -<div class="left-column"> -<p> -The Go Playground is a web service that runs on -<a href="http://golang.org/">golang.org</a>'s servers. -The service receives a Go program, compiles, links, and runs the program inside -a sandbox, then returns the output. -</p> - -<p> -There are limitations to the programs that can be run in the Playground. -They must be single-threaded (but they may use many goroutines). -There are also limits on execution time, and CPU and memory usage. -The Playground can access only a subset of the standard library -(notably absent are network and file system access). -Therefore, the only communication a Playground program has to the outside world -is via standard output. -</div> - -<div class="right-column"> -<script src="http://www.google.com/jsapi" type="text/javascript"></script> -<div id="playground" class="small"></div> -<script src="/doc/play/playground.js"></script> -</div> - -<div class="end-columns"></div> diff --git a/doc/progs/cat.go b/doc/progs/cat.go deleted file mode 100644 index 9f0b8d4a3..000000000 --- a/doc/progs/cat.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import ( - "./file" - "flag" - "fmt" - "os" -) - -func cat(f *file.File) { - const NBUF = 512 - var buf [NBUF]byte - for { - switch nr, er := f.Read(buf[:]); true { - case nr < 0: - fmt.Fprintf(os.Stderr, "cat: error reading from %s: %s\n", f.String(), er.String()) - os.Exit(1) - case nr == 0: // EOF - return - case nr > 0: - if nw, ew := file.Stdout.Write(buf[0:nr]); nw != nr { - fmt.Fprintf(os.Stderr, "cat: error writing from %s: %s\n", f.String(), ew.String()) - os.Exit(1) - } - } - } -} - -func main() { - flag.Parse() // Scans the arg list and sets up flags - if flag.NArg() == 0 { - cat(file.Stdin) - } - for i := 0; i < flag.NArg(); i++ { - f, err := file.Open(flag.Arg(i)) - if f == nil { - fmt.Fprintf(os.Stderr, "cat: can't open %s: error %s\n", flag.Arg(i), err) - os.Exit(1) - } - cat(f) - f.Close() - } -} diff --git a/doc/progs/cat_rot13.go b/doc/progs/cat_rot13.go deleted file mode 100644 index 0eefe7cfc..000000000 --- a/doc/progs/cat_rot13.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import ( - "./file" - "flag" - "fmt" - "os" -) - -var rot13Flag = flag.Bool("rot13", false, "rot13 the input") - -func rot13(b byte) byte { - if 'a' <= b && b <= 'z' { - b = 'a' + ((b-'a')+13)%26 - } - if 'A' <= b && b <= 'Z' { - b = 'A' + ((b-'A')+13)%26 - } - return b -} - -type reader interface { - Read(b []byte) (ret int, err os.Error) - String() string -} - -type rotate13 struct { - source reader -} - -func newRotate13(source reader) *rotate13 { - return &rotate13{source} -} - -func (r13 *rotate13) Read(b []byte) (ret int, err os.Error) { - r, e := r13.source.Read(b) - for i := 0; i < r; i++ { - b[i] = rot13(b[i]) - } - return r, e -} - -func (r13 *rotate13) String() string { - return r13.source.String() -} -// end of rotate13 implementation - -func cat(r reader) { - const NBUF = 512 - var buf [NBUF]byte - - if *rot13Flag { - r = newRotate13(r) - } - for { - switch nr, er := r.Read(buf[:]); { - case nr < 0: - fmt.Fprintf(os.Stderr, "cat: error reading from %s: %s\n", r.String(), er.String()) - os.Exit(1) - case nr == 0: // EOF - return - case nr > 0: - nw, ew := file.Stdout.Write(buf[0:nr]) - if nw != nr { - fmt.Fprintf(os.Stderr, "cat: error writing from %s: %s\n", r.String(), ew.String()) - os.Exit(1) - } - } - } -} - -func main() { - flag.Parse() // Scans the arg list and sets up flags - if flag.NArg() == 0 { - cat(file.Stdin) - } - for i := 0; i < flag.NArg(); i++ { - f, err := file.Open(flag.Arg(i)) - if f == nil { - fmt.Fprintf(os.Stderr, "cat: can't open %s: error %s\n", flag.Arg(i), err) - os.Exit(1) - } - cat(f) - f.Close() - } -} diff --git a/doc/progs/cgo1.go b/doc/progs/cgo1.go new file mode 100644 index 000000000..b79ee368a --- /dev/null +++ b/doc/progs/cgo1.go @@ -0,0 +1,21 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +package rand + +/* +#include <stdlib.h> +*/ +import "C" + +// STOP OMIT +func Random() int { + return int(C.random()) +} + +// STOP OMIT +func Seed(i int) { + C.srandom(C.uint(i)) +} + +// END OMIT diff --git a/doc/progs/cgo2.go b/doc/progs/cgo2.go new file mode 100644 index 000000000..f38473b13 --- /dev/null +++ b/doc/progs/cgo2.go @@ -0,0 +1,21 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +package rand2 + +/* +#include <stdlib.h> +*/ +import "C" + +func Random() int { + var r C.long = C.random() + return int(r) +} + +// STOP OMIT +func Seed(i int) { + C.srandom(C.uint(i)) +} + +// END OMIT diff --git a/doc/progs/cgo3.go b/doc/progs/cgo3.go new file mode 100644 index 000000000..435fd0402 --- /dev/null +++ b/doc/progs/cgo3.go @@ -0,0 +1,17 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +package print + +// #include <stdio.h> +// #include <stdlib.h> +import "C" +import "unsafe" + +func Print(s string) { + cs := C.CString(s) + C.fputs(cs, (*C.FILE)(C.stdout)) + C.free(unsafe.Pointer(cs)) +} + +// END OMIT diff --git a/doc/progs/cgo4.go b/doc/progs/cgo4.go new file mode 100644 index 000000000..3808d6217 --- /dev/null +++ b/doc/progs/cgo4.go @@ -0,0 +1,17 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +package print + +// #include <stdio.h> +// #include <stdlib.h> +import "C" +import "unsafe" + +func Print(s string) { + cs := C.CString(s) + defer C.free(unsafe.Pointer(cs)) + C.fputs(cs, (*C.FILE)(C.stdout)) +} + +// END OMIT diff --git a/doc/progs/defer.go b/doc/progs/defer.go new file mode 100644 index 000000000..2e11020ab --- /dev/null +++ b/doc/progs/defer.go @@ -0,0 +1,64 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains the code snippets included in "Defer, Panic, and Recover." + +package main + +import ( + "fmt" + "io" + "os" +) + +func a() { + i := 0 + defer fmt.Println(i) + i++ + return +} + +// STOP OMIT + +func b() { + for i := 0; i < 4; i++ { + defer fmt.Print(i) + } +} + +// STOP OMIT + +func c() (i int) { + defer func() { i++ }() + return 1 +} + +// STOP OMIT + +// Initial version. +func CopyFile(dstName, srcName string) (written int64, err error) { + src, err := os.Open(srcName) + if err != nil { + return + } + + dst, err := os.Create(dstName) + if err != nil { + return + } + + written, err = io.Copy(dst, src) + dst.Close() + src.Close() + return +} + +// STOP OMIT + +func main() { + a() + b() + fmt.Println() + fmt.Println(c()) +} diff --git a/doc/progs/defer2.go b/doc/progs/defer2.go new file mode 100644 index 000000000..cad66b070 --- /dev/null +++ b/doc/progs/defer2.go @@ -0,0 +1,58 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains the code snippets included in "Defer, Panic, and Recover." + +package main + +import "fmt" +import "io" // OMIT +import "os" // OMIT + +func main() { + f() + fmt.Println("Returned normally from f.") +} + +func f() { + defer func() { + if r := recover(); r != nil { + fmt.Println("Recovered in f", r) + } + }() + fmt.Println("Calling g.") + g(0) + fmt.Println("Returned normally from g.") +} + +func g(i int) { + if i > 3 { + fmt.Println("Panicking!") + panic(fmt.Sprintf("%v", i)) + } + defer fmt.Println("Defer in g", i) + fmt.Println("Printing in g", i) + g(i + 1) +} + +// STOP OMIT + +// Revised version. +func CopyFile(dstName, srcName string) (written int64, err error) { + src, err := os.Open(srcName) + if err != nil { + return + } + defer src.Close() + + dst, err := os.Create(dstName) + if err != nil { + return + } + defer dst.Close() + + return io.Copy(dst, src) +} + +// STOP OMIT diff --git a/doc/progs/echo.go b/doc/progs/echo.go deleted file mode 100644 index 3260edd74..000000000 --- a/doc/progs/echo.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import ( - "os" - "flag" // command line option parser -) - -var omitNewline = flag.Bool("n", false, "don't print final newline") - -const ( - Space = " " - Newline = "\n" -) - -func main() { - flag.Parse() // Scans the arg list and sets up flags - var s string = "" - for i := 0; i < flag.NArg(); i++ { - if i > 0 { - s += Space - } - s += flag.Arg(i) - } - if !*omitNewline { - s += Newline - } - os.Stdout.WriteString(s) -} diff --git a/doc/progs/eff_bytesize.go b/doc/progs/eff_bytesize.go new file mode 100644 index 000000000..b45961114 --- /dev/null +++ b/doc/progs/eff_bytesize.go @@ -0,0 +1,47 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "fmt" + +type ByteSize float64 + +const ( + _ = iota // ignore first value by assigning to blank identifier + KB ByteSize = 1 << (10 * iota) + MB + GB + TB + PB + EB + ZB + YB +) + +func (b ByteSize) String() string { + switch { + case b >= YB: + return fmt.Sprintf("%.2fYB", b/YB) + case b >= ZB: + return fmt.Sprintf("%.2fZB", b/ZB) + case b >= EB: + return fmt.Sprintf("%.2fEB", b/EB) + case b >= PB: + return fmt.Sprintf("%.2fPB", b/PB) + case b >= TB: + return fmt.Sprintf("%.2fTB", b/TB) + case b >= GB: + return fmt.Sprintf("%.2fGB", b/GB) + case b >= MB: + return fmt.Sprintf("%.2fMB", b/MB) + case b >= KB: + return fmt.Sprintf("%.2fKB", b/KB) + } + return fmt.Sprintf("%.2fB", b) +} + +func main() { + fmt.Println(YB, ByteSize(1e13)) +} diff --git a/doc/progs/eff_qr.go b/doc/progs/eff_qr.go new file mode 100644 index 000000000..de96a0208 --- /dev/null +++ b/doc/progs/eff_qr.go @@ -0,0 +1,46 @@ +package main + +import ( + "flag" + "log" + "net/http" + "text/template" +) + +var addr = flag.String("addr", ":1718", "http service address") // Q=17, R=18 + +var templ = template.Must(template.New("qr").Parse(templateStr)) + +func main() { + flag.Parse() + http.Handle("/", http.HandlerFunc(QR)) + err := http.ListenAndServe(*addr, nil) + if err != nil { + log.Fatal("ListenAndServe:", err) + } +} + +func QR(w http.ResponseWriter, req *http.Request) { + templ.Execute(w, req.FormValue("s")) +} + +const templateStr = ` +<html> +<head> +<title>QR Link Generator</title> +</head> +<body> +{{if .}} +<img src="http://chart.apis.google.com/chart?chs=300x300&cht=qr&choe=UTF-8&chl={{urlquery .}}" /> +<br> +{{html .}} +<br> +<br> +{{end}} +<form action="/" name=f method="GET"><input maxLength=1024 size=70 +name=s value="" title="Text to QR Encode"><input type=submit +value="Show QR" name=qr> +</form> +</body> +</html> +` diff --git a/doc/progs/eff_sequence.go b/doc/progs/eff_sequence.go new file mode 100644 index 000000000..11c885abf --- /dev/null +++ b/doc/progs/eff_sequence.go @@ -0,0 +1,42 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "fmt" + "sort" +) + +func main() { + seq := Sequence{6, 2, -1, 44, 16} + sort.Sort(seq) + fmt.Println(seq) +} + +type Sequence []int + +// Methods required by sort.Interface. +func (s Sequence) Len() int { + return len(s) +} +func (s Sequence) Less(i, j int) bool { + return s[i] < s[j] +} +func (s Sequence) Swap(i, j int) { + s[i], s[j] = s[j], s[i] +} + +// Method for printing - sorts the elements before printing. +func (s Sequence) String() string { + sort.Sort(s) + str := "[" + for i, elem := range s { + if i > 0 { + str += " " + } + str += fmt.Sprint(elem) + } + return str + "]" +} diff --git a/doc/progs/error.go b/doc/progs/error.go new file mode 100644 index 000000000..f85a5273a --- /dev/null +++ b/doc/progs/error.go @@ -0,0 +1,123 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains the code snippets included in "Error Handling and Go." + +package main + +import ( + "encoding/json" + "errors" + "fmt" + "log" + "net" + "os" + "time" +) + +type File struct{} + +func Open(name string) (file *File, err error) + +func openFile() { // OMIT + f, err := os.Open("filename.ext") + if err != nil { + log.Fatal(err) + } + // do something with the open *File f + // STOP OMIT + _ = f +} + +// errorString is a trivial implementation of error. +type errorString struct { + s string +} + +func (e *errorString) Error() string { + return e.s +} + +// STOP OMIT + +// New returns an error that formats as the given text. +func New(text string) error { + return &errorString{text} +} + +// STOP OMIT + +func Sqrt(f float64) (float64, error) { + if f < 0 { + return 0, errors.New("math: square root of negative number") + } + // implementation + return 0, nil // OMIT +} + +// STOP OMIT + +func printErr() (int, error) { // OMIT + f, err := Sqrt(-1) + if err != nil { + fmt.Println(err) + } + // STOP OMIT + // fmtError OMIT + if f < 0 { + return 0, fmt.Errorf("math: square root of negative number %g", f) + } + // STOP OMIT + return 0, nil +} + +type NegativeSqrtError float64 + +func (f NegativeSqrtError) Error() string { + return fmt.Sprintf("math: square root of negative number %g", float64(f)) +} + +// STOP OMIT + +type SyntaxError struct { + msg string // description of error + Offset int64 // error occurred after reading Offset bytes +} + +func (e *SyntaxError) Error() string { return e.msg } + +// STOP OMIT + +func decodeError(dec *json.Decoder, val struct{}) error { // OMIT + var f os.FileInfo // OMIT + if err := dec.Decode(&val); err != nil { + if serr, ok := err.(*json.SyntaxError); ok { + line, col := findLine(f, serr.Offset) + return fmt.Errorf("%s:%d:%d: %v", f.Name(), line, col, err) + } + return err + } + // STOP OMIT + return nil +} + +func findLine(os.FileInfo, int64) (int, int) { + // place holder; no need to run + return 0, 0 +} + +func netError(err error) { // OMIT + for { // OMIT + if nerr, ok := err.(net.Error); ok && nerr.Temporary() { + time.Sleep(1e9) + continue + } + if err != nil { + log.Fatal(err) + } + // STOP OMIT + } +} + +func main() {} diff --git a/doc/progs/error2.go b/doc/progs/error2.go new file mode 100644 index 000000000..2b0e0c356 --- /dev/null +++ b/doc/progs/error2.go @@ -0,0 +1,54 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains the code snippets included in "Error Handling and Go." + +package main + +import ( + "net/http" + "text/template" +) + +func init() { + http.HandleFunc("/view", viewRecord) +} + +func viewRecord(w http.ResponseWriter, r *http.Request) { + c := appengine.NewContext(r) + key := datastore.NewKey(c, "Record", r.FormValue("id"), 0, nil) + record := new(Record) + if err := datastore.Get(c, key, record); err != nil { + http.Error(w, err.Error(), 500) + return + } + if err := viewTemplate.Execute(w, record); err != nil { + http.Error(w, err.Error(), 500) + } +} + +// STOP OMIT + +type ap struct{} + +func (ap) NewContext(*http.Request) *ctx { return nil } + +type ctx struct{} + +func (*ctx) Errorf(string, ...interface{}) {} + +var appengine ap + +type ds struct{} + +func (ds) NewKey(*ctx, string, string, int, *int) string { return "" } +func (ds) Get(*ctx, string, *Record) error { return nil } + +var datastore ds + +type Record struct{} + +var viewTemplate *template.Template + +func main() {} diff --git a/doc/progs/error3.go b/doc/progs/error3.go new file mode 100644 index 000000000..e4e57e077 --- /dev/null +++ b/doc/progs/error3.go @@ -0,0 +1,63 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains the code snippets included in "Error Handling and Go." + +package main + +import ( + "net/http" + "text/template" +) + +func init() { + http.Handle("/view", appHandler(viewRecord)) +} + +// STOP OMIT + +func viewRecord(w http.ResponseWriter, r *http.Request) error { + c := appengine.NewContext(r) + key := datastore.NewKey(c, "Record", r.FormValue("id"), 0, nil) + record := new(Record) + if err := datastore.Get(c, key, record); err != nil { + return err + } + return viewTemplate.Execute(w, record) +} + +// STOP OMIT + +type appHandler func(http.ResponseWriter, *http.Request) error + +func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if err := fn(w, r); err != nil { + http.Error(w, err.Error(), 500) + } +} + +// STOP OMIT + +type ap struct{} + +func (ap) NewContext(*http.Request) *ctx { return nil } + +type ctx struct{} + +func (*ctx) Errorf(string, ...interface{}) {} + +var appengine ap + +type ds struct{} + +func (ds) NewKey(*ctx, string, string, int, *int) string { return "" } +func (ds) Get(*ctx, string, *Record) error { return nil } + +var datastore ds + +type Record struct{} + +var viewTemplate *template.Template + +func main() {} diff --git a/doc/progs/error4.go b/doc/progs/error4.go new file mode 100644 index 000000000..8f35cf74b --- /dev/null +++ b/doc/progs/error4.go @@ -0,0 +1,74 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains the code snippets included in "Error Handling and Go." + +package main + +import ( + "net/http" + "text/template" +) + +type appError struct { + Error error + Message string + Code int +} + +// STOP OMIT + +type appHandler func(http.ResponseWriter, *http.Request) *appError + +func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if e := fn(w, r); e != nil { // e is *appError, not os.Error. + c := appengine.NewContext(r) + c.Errorf("%v", e.Error) + http.Error(w, e.Message, e.Code) + } +} + +// STOP OMIT + +func viewRecord(w http.ResponseWriter, r *http.Request) *appError { + c := appengine.NewContext(r) + key := datastore.NewKey(c, "Record", r.FormValue("id"), 0, nil) + record := new(Record) + if err := datastore.Get(c, key, record); err != nil { + return &appError{err, "Record not found", 404} + } + if err := viewTemplate.Execute(w, record); err != nil { + return &appError{err, "Can't display record", 500} + } + return nil +} + +// STOP OMIT + +func init() { + http.Handle("/view", appHandler(viewRecord)) +} + +type ap struct{} + +func (ap) NewContext(*http.Request) *ctx { return nil } + +type ctx struct{} + +func (*ctx) Errorf(string, ...interface{}) {} + +var appengine ap + +type ds struct{} + +func (ds) NewKey(*ctx, string, string, int, *int) string { return "" } +func (ds) Get(*ctx, string, *Record) error { return nil } + +var datastore ds + +type Record struct{} + +var viewTemplate *template.Template + +func main() {} diff --git a/doc/progs/file.go b/doc/progs/file.go deleted file mode 100644 index 2875ce73a..000000000 --- a/doc/progs/file.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package file - -import ( - "os" - "syscall" -) - -type File struct { - fd int // file descriptor number - name string // file name at Open time -} - -func newFile(fd int, name string) *File { - if fd < 0 { - return nil - } - return &File{fd, name} -} - -var ( - Stdin = newFile(syscall.Stdin, "/dev/stdin") - Stdout = newFile(syscall.Stdout, "/dev/stdout") - Stderr = newFile(syscall.Stderr, "/dev/stderr") -) - -func OpenFile(name string, mode int, perm uint32) (file *File, err os.Error) { - r, e := syscall.Open(name, mode, perm) - if e != 0 { - err = os.Errno(e) - } - return newFile(r, name), err -} - -const ( - O_RDONLY = syscall.O_RDONLY - O_RDWR = syscall.O_RDWR - O_CREATE = syscall.O_CREAT - O_TRUNC = syscall.O_TRUNC -) - -func Open(name string) (file *File, err os.Error) { - return OpenFile(name, O_RDONLY, 0) -} - -func Create(name string) (file *File, err os.Error) { - return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666) -} - -func (file *File) Close() os.Error { - if file == nil { - return os.EINVAL - } - e := syscall.Close(file.fd) - file.fd = -1 // so it can't be closed again - if e != 0 { - return os.Errno(e) - } - return nil -} - -func (file *File) Read(b []byte) (ret int, err os.Error) { - if file == nil { - return -1, os.EINVAL - } - r, e := syscall.Read(file.fd, b) - if e != 0 { - err = os.Errno(e) - } - return int(r), err -} - -func (file *File) Write(b []byte) (ret int, err os.Error) { - if file == nil { - return -1, os.EINVAL - } - r, e := syscall.Write(file.fd, b) - if e != 0 { - err = os.Errno(e) - } - return int(r), err -} - -func (file *File) String() string { - return file.name -} diff --git a/doc/progs/file_windows.go b/doc/progs/file_windows.go deleted file mode 100644 index 03003a3f7..000000000 --- a/doc/progs/file_windows.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package file - -import ( - "os" - "syscall" -) - -type File struct { - fd syscall.Handle // file descriptor number - name string // file name at Open time -} - -func newFile(fd syscall.Handle, name string) *File { - if fd < 0 { - return nil - } - return &File{fd, name} -} - -var ( - Stdin = newFile(syscall.Stdin, "/dev/stdin") - Stdout = newFile(syscall.Stdout, "/dev/stdout") - Stderr = newFile(syscall.Stderr, "/dev/stderr") -) - -func OpenFile(name string, mode int, perm uint32) (file *File, err os.Error) { - r, e := syscall.Open(name, mode, perm) - if e != 0 { - err = os.Errno(e) - } - return newFile(r, name), err -} - -const ( - O_RDONLY = syscall.O_RDONLY - O_RDWR = syscall.O_RDWR - O_CREATE = syscall.O_CREAT - O_TRUNC = syscall.O_TRUNC -) - -func Open(name string) (file *File, err os.Error) { - return OpenFile(name, O_RDONLY, 0) -} - -func Create(name string) (file *File, err os.Error) { - return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666) -} - -func (file *File) Close() os.Error { - if file == nil { - return os.EINVAL - } - e := syscall.Close(file.fd) - file.fd = syscall.InvalidHandle // so it can't be closed again - if e != 0 { - return os.Errno(e) - } - return nil -} - -func (file *File) Read(b []byte) (ret int, err os.Error) { - if file == nil { - return -1, os.EINVAL - } - r, e := syscall.Read(file.fd, b) - if e != 0 { - err = os.Errno(e) - } - return int(r), err -} - -func (file *File) Write(b []byte) (ret int, err os.Error) { - if file == nil { - return -1, os.EINVAL - } - r, e := syscall.Write(file.fd, b) - if e != 0 { - err = os.Errno(e) - } - return int(r), err -} - -func (file *File) String() string { - return file.name -} diff --git a/doc/progs/go1.go b/doc/progs/go1.go new file mode 100644 index 000000000..50fd93441 --- /dev/null +++ b/doc/progs/go1.go @@ -0,0 +1,245 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains examples to embed in the Go 1 release notes document. + +package main + +import ( + "errors" + "flag" + "fmt" + "log" + "os" + "path/filepath" + "testing" + "time" + "unicode" +) + +func main() { + flag.Parse() + stringAppend() + mapDelete() + mapIteration() + multipleAssignment() + structEquality() + compositeLiterals() + runeType() + errorExample() + timePackage() + walkExample() + osIsExist() +} + +var timeout = flag.Duration("timeout", 30*time.Second, "how long to wait for completion") + +func init() { + // canonicalize the logging + log.SetFlags(0) +} + +func mapDelete() { + m := map[string]int{"7": 7, "23": 23} + k := "7" + delete(m, k) + if m["7"] != 0 || m["23"] != 23 { + log.Fatal("mapDelete:", m) + } +} + +func stringAppend() { + greeting := []byte{} + greeting = append(greeting, []byte("hello ")...) + greeting = append(greeting, "world"...) + if string(greeting) != "hello world" { + log.Fatal("stringAppend: ", string(greeting)) + } +} + +func mapIteration() { + m := map[string]int{"Sunday": 0, "Monday": 1} + for name, value := range m { + // This loop should not assume Sunday will be visited first. + f(name, value) + } +} + +func f(string, int) { +} + +func assert(t bool) { + if !t { + log.Panic("assertion fail") + } +} + +func multipleAssignment() { + sa := []int{1, 2, 3} + i := 0 + i, sa[i] = 1, 2 // sets i = 1, sa[0] = 2 + + sb := []int{1, 2, 3} + j := 0 + sb[j], j = 2, 1 // sets sb[0] = 2, j = 1 + + sc := []int{1, 2, 3} + sc[0], sc[0] = 1, 2 // sets sc[0] = 1, then sc[0] = 2 (so sc[0] = 2 at end) + + assert(i == 1 && sa[0] == 2) + assert(j == 1 && sb[0] == 2) + assert(sc[0] == 2) +} + +func structEquality() { + type Day struct { + long string + short string + } + Christmas := Day{"Christmas", "XMas"} + Thanksgiving := Day{"Thanksgiving", "Turkey"} + holiday := map[Day]bool{ + Christmas: true, + Thanksgiving: true, + } + fmt.Printf("Christmas is a holiday: %t\n", holiday[Christmas]) +} + +func compositeLiterals() { + type Date struct { + month string + day int + } + // Struct values, fully qualified; always legal. + holiday1 := []Date{ + Date{"Feb", 14}, + Date{"Nov", 11}, + Date{"Dec", 25}, + } + // Struct values, type name elided; always legal. + holiday2 := []Date{ + {"Feb", 14}, + {"Nov", 11}, + {"Dec", 25}, + } + // Pointers, fully qualified, always legal. + holiday3 := []*Date{ + &Date{"Feb", 14}, + &Date{"Nov", 11}, + &Date{"Dec", 25}, + } + // Pointers, type name elided; legal in Go 1. + holiday4 := []*Date{ + {"Feb", 14}, + {"Nov", 11}, + {"Dec", 25}, + } + // STOP OMIT + _, _, _, _ = holiday1, holiday2, holiday3, holiday4 +} + +func runeType() { + // STARTRUNE OMIT + delta := 'δ' // delta has type rune. + var DELTA rune + DELTA = unicode.ToUpper(delta) + epsilon := unicode.ToLower(DELTA + 1) + if epsilon != 'δ'+1 { + log.Fatal("inconsistent casing for Greek") + } + // ENDRUNE OMIT +} + +// START ERROR EXAMPLE OMIT +type SyntaxError struct { + File string + Line int + Message string +} + +func (se *SyntaxError) Error() string { + return fmt.Sprintf("%s:%d: %s", se.File, se.Line, se.Message) +} + +// END ERROR EXAMPLE OMIT + +func errorExample() { + var ErrSyntax = errors.New("syntax error") + _ = ErrSyntax + se := &SyntaxError{"file", 7, "error"} + got := fmt.Sprint(se) + const expect = "file:7: error" + if got != expect { + log.Fatalf("errorsPackage: expected %q got %q", expect, got) + } +} + +// sleepUntil sleeps until the specified time. It returns immediately if it's too late. +func sleepUntil(wakeup time.Time) { + now := time.Now() // A Time. + if !wakeup.After(now) { + return + } + delta := wakeup.Sub(now) // A Duration. + fmt.Printf("Sleeping for %.3fs\n", delta.Seconds()) + time.Sleep(delta) +} + +func timePackage() { + sleepUntil(time.Now().Add(123 * time.Millisecond)) +} + +func walkExample() { + // STARTWALK OMIT + markFn := func(path string, info os.FileInfo, err error) error { + if path == "pictures" { // Will skip walking of directory pictures and its contents. + return filepath.SkipDir + } + if err != nil { + return err + } + log.Println(path) + return nil + } + err := filepath.Walk(".", markFn) + if err != nil { + log.Fatal(err) + } + // ENDWALK OMIT +} + +func initializationFunction(c chan int) { + c <- 1 +} + +var PackageGlobal int + +func init() { + c := make(chan int) + go initializationFunction(c) + PackageGlobal = <-c +} + +func BenchmarkSprintf(b *testing.B) { + // Verify correctness before running benchmark. + b.StopTimer() + got := fmt.Sprintf("%x", 23) + const expect = "17" + if expect != got { + b.Fatalf("expected %q; got %q", expect, got) + } + b.StartTimer() + for i := 0; i < b.N; i++ { + fmt.Sprintf("%x", 23) + } +} + +func osIsExist() { + name := "go1.go" + f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) + if os.IsExist(err) { + log.Printf("%s already exists", name) + } + _ = f +} diff --git a/doc/progs/gobs1.go b/doc/progs/gobs1.go new file mode 100644 index 000000000..7077ca159 --- /dev/null +++ b/doc/progs/gobs1.go @@ -0,0 +1,22 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package gobs1 + +type T struct{ X, Y, Z int } // Only exported fields are encoded and decoded. +var t = T{X: 7, Y: 0, Z: 8} + +// STOP OMIT + +type U struct{ X, Y *int8 } // Note: pointers to int8s +var u U + +// STOP OMIT + +type Node struct { + Value int + Left, Right *Node +} + +// STOP OMIT diff --git a/doc/progs/gobs2.go b/doc/progs/gobs2.go new file mode 100644 index 000000000..85bb41cdc --- /dev/null +++ b/doc/progs/gobs2.go @@ -0,0 +1,43 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "bytes" + "encoding/gob" + "fmt" + "log" +) + +type P struct { + X, Y, Z int + Name string +} + +type Q struct { + X, Y *int32 + Name string +} + +func main() { + // Initialize the encoder and decoder. Normally enc and dec would be + // bound to network connections and the encoder and decoder would + // run in different processes. + var network bytes.Buffer // Stand-in for a network connection + enc := gob.NewEncoder(&network) // Will write to network. + dec := gob.NewDecoder(&network) // Will read from network. + // Encode (send) the value. + err := enc.Encode(P{3, 4, 5, "Pythagoras"}) + if err != nil { + log.Fatal("encode error:", err) + } + // Decode (receive) the value. + var q Q + err = dec.Decode(&q) + if err != nil { + log.Fatal("decode error:", err) + } + fmt.Printf("%q: {%d,%d}\n", q.Name, *q.X, *q.Y) +} diff --git a/doc/progs/helloworld.go b/doc/progs/helloworld.go deleted file mode 100644 index 8185038d9..000000000 --- a/doc/progs/helloworld.go +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import fmt "fmt" // Package implementing formatted I/O. - -func main() { - fmt.Printf("Hello, world; or Καλημέρα κόσμε; or こんにちは 世界\n") -} diff --git a/doc/progs/helloworld3.go b/doc/progs/helloworld3.go deleted file mode 100644 index 2011513b7..000000000 --- a/doc/progs/helloworld3.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import ( - "./file" - "fmt" - "os" -) - -func main() { - hello := []byte("hello, world\n") - file.Stdout.Write(hello) - f, err := file.Open("/does/not/exist") - if f == nil { - fmt.Printf("can't open file; err=%s\n", err.String()) - os.Exit(1) - } -} diff --git a/doc/progs/image_draw.go b/doc/progs/image_draw.go new file mode 100644 index 000000000..2cc5c632f --- /dev/null +++ b/doc/progs/image_draw.go @@ -0,0 +1,142 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains the code snippets included in "The Go image/draw package." + +package main + +import ( + "image" + "image/color" + "image/draw" +) + +func main() { + Color() + Rect() + RectAndScroll() + ConvAndCircle() + Glyph() +} + +func Color() { + c := color.RGBA{255, 0, 255, 255} + r := image.Rect(0, 0, 640, 480) + dst := image.NewRGBA(r) + + // ZERO OMIT + // image.ZP is the zero point -- the origin. + draw.Draw(dst, r, &image.Uniform{c}, image.ZP, draw.Src) + // STOP OMIT + + // BLUE OMIT + m := image.NewRGBA(image.Rect(0, 0, 640, 480)) + blue := color.RGBA{0, 0, 255, 255} + draw.Draw(m, m.Bounds(), &image.Uniform{blue}, image.ZP, draw.Src) + // STOP OMIT + + // RESET OMIT + draw.Draw(m, m.Bounds(), image.Transparent, image.ZP, draw.Src) + // STOP OMIT +} + +func Rect() { + dst := image.NewRGBA(image.Rect(0, 0, 640, 480)) + sr := image.Rect(0, 0, 200, 200) + src := image.Black + dp := image.Point{100, 100} + + // RECT OMIT + r := image.Rectangle{dp, dp.Add(sr.Size())} + draw.Draw(dst, r, src, sr.Min, draw.Src) + // STOP OMIT +} + +func RectAndScroll() { + dst := image.NewRGBA(image.Rect(0, 0, 640, 480)) + sr := image.Rect(0, 0, 200, 200) + src := image.Black + dp := image.Point{100, 100} + + // RECT2 OMIT + r := sr.Sub(sr.Min).Add(dp) + draw.Draw(dst, r, src, sr.Min, draw.Src) + // STOP OMIT + + m := dst + + // SCROLL OMIT + b := m.Bounds() + p := image.Pt(0, 20) + // Note that even though the second argument is b, + // the effective rectangle is smaller due to clipping. + draw.Draw(m, b, m, b.Min.Add(p), draw.Src) + dirtyRect := b.Intersect(image.Rect(b.Min.X, b.Max.Y-20, b.Max.X, b.Max.Y)) + // STOP OMIT + + _ = dirtyRect // noop +} + +func ConvAndCircle() { + src := image.NewRGBA(image.Rect(0, 0, 640, 480)) + dst := image.NewRGBA(image.Rect(0, 0, 640, 480)) + + // CONV OMIT + b := src.Bounds() + m := image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy())) + draw.Draw(m, m.Bounds(), src, b.Min, draw.Src) + // STOP OMIT + + p := image.Point{100, 100} + r := 50 + + // CIRCLE2 OMIT + draw.DrawMask(dst, dst.Bounds(), src, image.ZP, &circle{p, r}, image.ZP, draw.Over) + // STOP OMIT +} + +func theGlyphImageForAFont() image.Image { + return image.NewRGBA(image.Rect(0, 0, 640, 480)) +} + +func theBoundsFor(index int) image.Rectangle { + return image.Rect(0, 0, 32, 32) +} + +func Glyph() { + p := image.Point{100, 100} + dst := image.NewRGBA(image.Rect(0, 0, 640, 480)) + glyphIndex := 42 + + // GLYPH OMIT + src := &image.Uniform{color.RGBA{0, 0, 255, 255}} + mask := theGlyphImageForAFont() + mr := theBoundsFor(glyphIndex) + draw.DrawMask(dst, mr.Sub(mr.Min).Add(p), src, image.ZP, mask, mr.Min, draw.Over) + // STOP OMIT +} + +//CIRCLESTRUCT OMIT +type circle struct { + p image.Point + r int +} + +func (c *circle) ColorModel() color.Model { + return color.AlphaModel +} + +func (c *circle) Bounds() image.Rectangle { + return image.Rect(c.p.X-c.r, c.p.Y-c.r, c.p.X+c.r, c.p.Y+c.r) +} + +func (c *circle) At(x, y int) color.Color { + xx, yy, rr := float64(x-c.p.X)+0.5, float64(y-c.p.Y)+0.5, float64(c.r) + if xx*xx+yy*yy < rr*rr { + return color.Alpha{255} + } + return color.Alpha{0} +} + +//STOP OMIT diff --git a/doc/progs/image_package1.go b/doc/progs/image_package1.go new file mode 100644 index 000000000..c4c401e72 --- /dev/null +++ b/doc/progs/image_package1.go @@ -0,0 +1,15 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "fmt" + "image" +) + +func main() { + p := image.Point{2, 1} + fmt.Println("X is", p.X, "Y is", p.Y) +} diff --git a/doc/progs/image_package2.go b/doc/progs/image_package2.go new file mode 100644 index 000000000..fcb5d9fd0 --- /dev/null +++ b/doc/progs/image_package2.go @@ -0,0 +1,16 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "fmt" + "image" +) + +func main() { + r := image.Rect(2, 1, 5, 5) + // Dx and Dy return a rectangle's width and height. + fmt.Println(r.Dx(), r.Dy(), image.Pt(0, 0).In(r)) // prints 3 4 false +} diff --git a/doc/progs/image_package3.go b/doc/progs/image_package3.go new file mode 100644 index 000000000..13d0f0807 --- /dev/null +++ b/doc/progs/image_package3.go @@ -0,0 +1,15 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "fmt" + "image" +) + +func main() { + r := image.Rect(2, 1, 5, 5).Add(image.Pt(-4, -2)) + fmt.Println(r.Dx(), r.Dy(), image.Pt(0, 0).In(r)) // prints 3 4 true +} diff --git a/doc/progs/image_package4.go b/doc/progs/image_package4.go new file mode 100644 index 000000000..c46fddf07 --- /dev/null +++ b/doc/progs/image_package4.go @@ -0,0 +1,16 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "fmt" + "image" +) + +func main() { + r := image.Rect(0, 0, 4, 3).Intersect(image.Rect(2, 2, 5, 5)) + // Size returns a rectangle's width and height, as a Point. + fmt.Printf("%#v\n", r.Size()) // prints image.Point{X:2, Y:1} +} diff --git a/doc/progs/image_package5.go b/doc/progs/image_package5.go new file mode 100644 index 000000000..0bb5c7608 --- /dev/null +++ b/doc/progs/image_package5.go @@ -0,0 +1,17 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "fmt" + "image" + "image/color" +) + +func main() { + m := image.NewRGBA(image.Rect(0, 0, 640, 480)) + m.Set(5, 5, color.RGBA{255, 0, 0, 255}) + fmt.Println(m.At(5, 5)) +} diff --git a/doc/progs/image_package6.go b/doc/progs/image_package6.go new file mode 100644 index 000000000..62eeecdb9 --- /dev/null +++ b/doc/progs/image_package6.go @@ -0,0 +1,17 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "fmt" + "image" +) + +func main() { + m0 := image.NewRGBA(image.Rect(0, 0, 8, 5)) + m1 := m0.SubImage(image.Rect(1, 2, 5, 5)).(*image.RGBA) + fmt.Println(m0.Bounds().Dx(), m1.Bounds().Dx()) // prints 8, 4 + fmt.Println(m0.Stride == m1.Stride) // prints true +} diff --git a/doc/progs/interface.go b/doc/progs/interface.go new file mode 100644 index 000000000..c2925d590 --- /dev/null +++ b/doc/progs/interface.go @@ -0,0 +1,62 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains the code snippets included in "The Laws of Reflection." + +package main + +import ( + "bufio" + "bytes" + "io" + "os" +) + +type MyInt int + +var i int +var j MyInt + +// STOP OMIT + +// Reader is the interface that wraps the basic Read method. +type Reader interface { + Read(p []byte) (n int, err error) +} + +// Writer is the interface that wraps the basic Write method. +type Writer interface { + Write(p []byte) (n int, err error) +} + +// STOP OMIT + +func readers() { // OMIT + var r io.Reader + r = os.Stdin + r = bufio.NewReader(r) + r = new(bytes.Buffer) + // and so on + // STOP OMIT +} + +func typeAssertions() (interface{}, error) { // OMIT + var r io.Reader + tty, err := os.OpenFile("/dev/tty", os.O_RDWR, 0) + if err != nil { + return nil, err + } + r = tty + // STOP OMIT + var w io.Writer + w = r.(io.Writer) + // STOP OMIT + var empty interface{} + empty = w + // STOP OMIT + return empty, err +} + +func main() { +} diff --git a/doc/progs/interface2.go b/doc/progs/interface2.go new file mode 100644 index 000000000..a541d94e4 --- /dev/null +++ b/doc/progs/interface2.go @@ -0,0 +1,132 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains the code snippets included in "The Laws of Reflection." + +package main + +import ( + "fmt" + "reflect" +) + +func main() { + var x float64 = 3.4 + fmt.Println("type:", reflect.TypeOf(x)) + // STOP OMIT + // TODO(proppy): test output OMIT +} + +// STOP main OMIT + +func f1() { + // START f1 OMIT + var x float64 = 3.4 + v := reflect.ValueOf(x) + fmt.Println("type:", v.Type()) + fmt.Println("kind is float64:", v.Kind() == reflect.Float64) + fmt.Println("value:", v.Float()) + // STOP OMIT +} + +func f2() { + // START f2 OMIT + var x uint8 = 'x' + v := reflect.ValueOf(x) + fmt.Println("type:", v.Type()) // uint8. + fmt.Println("kind is uint8: ", v.Kind() == reflect.Uint8) // true. + x = uint8(v.Uint()) // v.Uint returns a uint64. + // STOP OMIT +} + +func f3() { + // START f3 OMIT + type MyInt int + var x MyInt = 7 + v := reflect.ValueOf(x) + // STOP OMIT + // START f3b OMIT + y := v.Interface().(float64) // y will have type float64. + fmt.Println(y) + // STOP OMIT + // START f3c OMIT + fmt.Println(v.Interface()) + // STOP OMIT + // START f3d OMIT + fmt.Printf("value is %7.1e\n", v.Interface()) + // STOP OMIT +} + +func f4() { + // START f4 OMIT + var x float64 = 3.4 + v := reflect.ValueOf(x) + v.SetFloat(7.1) // Error: will panic. + // STOP OMIT +} + +func f5() { + // START f5 OMIT + var x float64 = 3.4 + v := reflect.ValueOf(x) + fmt.Println("settability of v:", v.CanSet()) + // STOP OMIT +} + +func f6() { + // START f6 OMIT + var x float64 = 3.4 + v := reflect.ValueOf(x) + // STOP OMIT + // START f6b OMIT + v.SetFloat(7.1) + // STOP OMIT +} + +func f7() { + // START f7 OMIT + var x float64 = 3.4 + p := reflect.ValueOf(&x) // Note: take the address of x. + fmt.Println("type of p:", p.Type()) + fmt.Println("settability of p:", p.CanSet()) + // STOP OMIT + // START f7b OMIT + v := p.Elem() + fmt.Println("settability of v:", v.CanSet()) + // STOP OMIT + // START f7c OMIT + v.SetFloat(7.1) + fmt.Println(v.Interface()) + fmt.Println(x) + // STOP OMIT +} + +func f8() { + // START f8 OMIT + type T struct { + A int + B string + } + t := T{23, "skidoo"} + s := reflect.ValueOf(&t).Elem() + typeOfT := s.Type() + for i := 0; i < s.NumField(); i++ { + f := s.Field(i) + fmt.Printf("%d: %s %s = %v\n", i, + typeOfT.Field(i).Name, f.Type(), f.Interface()) + } + // STOP OMIT + // START f8b OMIT + s.Field(0).SetInt(77) + s.Field(1).SetString("Sunset Strip") + fmt.Println("t is now", t) + // STOP OMIT +} + +func f9() { + // START f9 OMIT + var x float64 = 3.4 + fmt.Println("value:", reflect.ValueOf(x)) + // STOP OMIT +} diff --git a/doc/progs/json1.go b/doc/progs/json1.go new file mode 100644 index 000000000..9e10f4743 --- /dev/null +++ b/doc/progs/json1.go @@ -0,0 +1,88 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "encoding/json" + "log" + "reflect" +) + +type Message struct { + Name string + Body string + Time int64 +} + +// STOP OMIT + +func Encode() { + m := Message{"Alice", "Hello", 1294706395881547000} + b, err := json.Marshal(m) + + if err != nil { + panic(err) + } + + expected := []byte(`{"Name":"Alice","Body":"Hello","Time":1294706395881547000}`) + if !reflect.DeepEqual(b, expected) { + log.Panicf("Error marshalling %q, expected %q, got %q.", m, expected, b) + } + +} + +func Decode() { + b := []byte(`{"Name":"Alice","Body":"Hello","Time":1294706395881547000}`) + var m Message + err := json.Unmarshal(b, &m) + + if err != nil { + panic(err) + } + + expected := Message{ + Name: "Alice", + Body: "Hello", + Time: 1294706395881547000, + } + + if !reflect.DeepEqual(m, expected) { + log.Panicf("Error unmarshalling %q, expected %q, got %q.", b, expected, m) + } + + m = Message{ + Name: "Alice", + Body: "Hello", + Time: 1294706395881547000, + } + + // STOP OMIT +} + +func PartialDecode() { + b := []byte(`{"Name":"Bob","Food":"Pickle"}`) + var m Message + err := json.Unmarshal(b, &m) + + // STOP OMIT + + if err != nil { + panic(err) + } + + expected := Message{ + Name: "Bob", + } + + if !reflect.DeepEqual(expected, m) { + log.Panicf("Error unmarshalling %q, expected %q, got %q.", b, expected, m) + } +} + +func main() { + Encode() + Decode() + PartialDecode() +} diff --git a/doc/progs/json2.go b/doc/progs/json2.go new file mode 100644 index 000000000..6089ae671 --- /dev/null +++ b/doc/progs/json2.go @@ -0,0 +1,42 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "fmt" + "math" +) + +func InterfaceExample() { + var i interface{} + i = "a string" + i = 2011 + i = 2.777 + + // STOP OMIT + + r := i.(float64) + fmt.Println("the circle's area", math.Pi*r*r) + + // STOP OMIT + + switch v := i.(type) { + case int: + fmt.Println("twice i is", v*2) + case float64: + fmt.Println("the reciprocal of i is", 1/v) + case string: + h := len(v) / 2 + fmt.Println("i swapped by halves is", v[h:]+v[:h]) + default: + // i isn't one of the types above + } + + // STOP OMIT +} + +func main() { + InterfaceExample() +} diff --git a/doc/progs/json3.go b/doc/progs/json3.go new file mode 100644 index 000000000..a04fdfa50 --- /dev/null +++ b/doc/progs/json3.go @@ -0,0 +1,73 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "encoding/json" + "fmt" + "log" + "reflect" +) + +func Decode() { + b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`) + + var f interface{} + err := json.Unmarshal(b, &f) + + // STOP OMIT + + if err != nil { + panic(err) + } + + expected := map[string]interface{}{ + "Name": "Wednesday", + "Age": float64(6), + "Parents": []interface{}{ + "Gomez", + "Morticia", + }, + } + + if !reflect.DeepEqual(f, expected) { + log.Panicf("Error unmarshalling %q, expected %q, got %q", b, expected, f) + } + + f = map[string]interface{}{ + "Name": "Wednesday", + "Age": 6, + "Parents": []interface{}{ + "Gomez", + "Morticia", + }, + } + + // STOP OMIT + + m := f.(map[string]interface{}) + + for k, v := range m { + switch vv := v.(type) { + case string: + fmt.Println(k, "is string", vv) + case int: + fmt.Println(k, "is int", vv) + case []interface{}: + fmt.Println(k, "is an array:") + for i, u := range vv { + fmt.Println(i, u) + } + default: + fmt.Println(k, "is of a type I don't know how to handle") + } + } + + // STOP OMIT +} + +func main() { + Decode() +} diff --git a/doc/progs/json4.go b/doc/progs/json4.go new file mode 100644 index 000000000..492630220 --- /dev/null +++ b/doc/progs/json4.go @@ -0,0 +1,45 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "encoding/json" + "log" + "reflect" +) + +type FamilyMember struct { + Name string + Age int + Parents []string +} + +// STOP OMIT + +func Decode() { + b := []byte(`{"Name":"Bob","Age":20,"Parents":["Morticia", "Gomez"]}`) + var m FamilyMember + err := json.Unmarshal(b, &m) + + // STOP OMIT + + if err != nil { + panic(err) + } + + expected := FamilyMember{ + Name: "Bob", + Age: 20, + Parents: []string{"Morticia", "Gomez"}, + } + + if !reflect.DeepEqual(expected, m) { + log.Panicf("Error unmarshalling %q, expected %q, got %q", b, expected, m) + } +} + +func main() { + Decode() +} diff --git a/doc/progs/json5.go b/doc/progs/json5.go new file mode 100644 index 000000000..6d7a4ca8c --- /dev/null +++ b/doc/progs/json5.go @@ -0,0 +1,31 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "encoding/json" + "log" + "os" +) + +func main() { + dec := json.NewDecoder(os.Stdin) + enc := json.NewEncoder(os.Stdout) + for { + var v map[string]interface{} + if err := dec.Decode(&v); err != nil { + log.Println(err) + return + } + for k := range v { + if k != "Name" { + delete(v, k) + } + } + if err := enc.Encode(&v); err != nil { + log.Println(err) + } + } +} diff --git a/doc/progs/print.go b/doc/progs/print.go deleted file mode 100644 index 8f44ba8c6..000000000 --- a/doc/progs/print.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import "fmt" - -func main() { - var u64 uint64 = 1<<64 - 1 - fmt.Printf("%d %d\n", u64, int64(u64)) - - // harder stuff - type T struct { - a int - b string - } - t := T{77, "Sunset Strip"} - a := []int{1, 2, 3, 4} - fmt.Printf("%v %v %v\n", u64, t, a) - fmt.Print(u64, " ", t, " ", a, "\n") - fmt.Println(u64, t, a) -} diff --git a/doc/progs/print_string.go b/doc/progs/print_string.go deleted file mode 100644 index 46ab1d91a..000000000 --- a/doc/progs/print_string.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import "fmt" - -type testType struct { - a int - b string -} - -func (t *testType) String() string { - return fmt.Sprint(t.a) + " " + t.b -} - -func main() { - t := &testType{77, "Sunset Strip"} - fmt.Println(t) -} diff --git a/doc/progs/run b/doc/progs/run index 81781c9d2..92c8da5cd 100755 --- a/doc/progs/run +++ b/doc/progs/run @@ -5,81 +5,108 @@ set -e -eval $(gomake --no-print-directory -f ../../src/Make.inc go-env) - -if [ -z "$O" ]; then - echo 'missing $O - maybe no Make.$GOARCH?' 1>&2 - exit 1 +goos=$(go env GOOS) + +defer_panic_recover=" + defer + defer2 +" + +effective_go=" + eff_bytesize + eff_qr + eff_sequence +" + +error_handling=" + error + error2 + error3 + error4 +" + +law_of_reflection=" + interface + interface2 +" + +c_go_cgo=" + cgo1 + cgo2 + cgo3 + cgo4 +" +# cgo1 and cgo2 don't run on freebsd, srandom has a different signature +if [ "$goos" == "freebsd" ]; then + c_go_cgo="cgo3 cgo4" fi -rm -f *.$O - -if [ "$GOOS" = "windows" ];then - $GC -o file.8 file_windows.go -else - $GC file.go -fi - -for i in \ - helloworld.go \ - helloworld3.go \ - echo.go \ - cat.go \ - cat_rot13.go \ - sum.go \ - sort.go \ - sortmain.go \ - print.go \ - print_string.go \ - sieve.go \ - sieve1.go \ - server1.go \ - strings.go \ -; do - $GC $i +timeout=" + timeout1 + timeout2 +" + +gobs=" + gobs1 + gobs2 +" + +json=" + json1 + json2 + json3 + json4 + json5 +" + +image_package=" + image_package1 + image_package2 + image_package3 + image_package4 + image_package5 + image_package6 +" + +all=$(echo $defer_panic_recover $effective_go $error_handling $law_of_reflection $c_go_cgo $timeout $gobs $json $image_package slices go1) + +for i in $all; do + go build $i.go done -function testit { - $LD $1.$O - x=$(echo $(./$O.out $2 2>&1)) # extra echo canonicalizes - if [ "$x" != "$3" ] - then - echo $1 failed: '"'$x'"' is not '"'$3'"' - fi -} +# Write to temporary file to avoid mingw bash bug. +TMPFILE="${TMPDIR:-/tmp}/gotest3.$USER" -function testitpipe { - $LD $1.$O - x=$(echo $(./$O.out | $2 2>&1)) # extra echo canonicalizes - if [ "$x" != "$3" ] +function testit { + ./$1 >"$TMPFILE" 2>&1 || true + x=$(echo $(cat "$TMPFILE")) # extra echo canonicalizes + if ! echo "$x" | grep "$2" > /dev/null then - echo $1 failed: '"'$x'"' is not '"'$3'"' + echo $1 failed: '"'$x'"' is not '"'$2'"' fi } -testit helloworld "" "Hello, world; or Καλημέρα κόσμε; or こんにちは 世界" -testit helloworld3 "" "hello, world can't open file; err=no such file or directory" -testit echo "hello, world" "hello, world" -testit sum "" "6" -testit strings "" "" +testit defer '^0 3210 2$' +testit defer2 '^Calling g. Printing in g 0 Printing in g 1 Printing in g 2 Printing in g 3 Panicking! Defer in g 3 Defer in g 2 Defer in g 1 Defer in g 0 Recovered in f 4 Returned normally from f.$' -alphabet=abcdefghijklmnopqrstuvwxyz -rot13=nopqrstuvwxyzabcdefghijklm -echo $alphabet | testit cat "" $alphabet -echo $alphabet | testit cat_rot13 "--rot13" $rot13 -echo $rot13 | testit cat_rot13 "--rot13" $alphabet +testit eff_bytesize '^1.00YB 9.09TB$' +testit eff_sequence '^\[-1 2 6 16 44\]$' -testit sortmain "" "Sunday Monday Tuesday Wednesday Thursday Friday Saturday" +testit go1 '^Christmas is a holiday: true Sleeping for 0.123s.*go1.go already exists$' -testit print "" "18446744073709551615 -1 18446744073709551615 {77 Sunset Strip} [1 2 3 4] 18446744073709551615 {77 Sunset Strip} [1 2 3 4] 18446744073709551615 {77 Sunset Strip} [1 2 3 4]" -testit print_string "" "77 Sunset Strip" +testit interface2 "^type: float64$" -testitpipe sieve "sed 10q" "2 3 5 7 11 13 17 19 23 29" -testitpipe sieve "sed 10q" "2 3 5 7 11 13 17 19 23 29" +testit json1 "^$" +testit json2 "the reciprocal of i is" +testit json3 "Age is int 6" +testit json4 "^$" -# server hangs; don't run it, just compile it -$GC server.go -testit server1 "" "" +testit image_package1 "^X is 2 Y is 1$" +testit image_package2 "^3 4 false$" +testit image_package3 "^3 4 true$" +testit image_package4 "^image.Point{X:2, Y:1}$" +testit image_package5 "^{255 0 0 255}$" +testit image_package6 "^8 4 true$" -rm -f $O.out *.$O +rm -f $all "$TMPFILE" diff --git a/doc/progs/server.go b/doc/progs/server.go deleted file mode 100644 index b498b53a6..000000000 --- a/doc/progs/server.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import "fmt" - -type request struct { - a, b int - replyc chan int -} - -type binOp func(a, b int) int - -func run(op binOp, req *request) { - reply := op(req.a, req.b) - req.replyc <- reply -} - -func server(op binOp, service chan *request) { - for { - req := <-service - go run(op, req) // don't wait for it - } -} - -func startServer(op binOp) chan *request { - req := make(chan *request) - go server(op, req) - return req -} - -func main() { - adder := startServer(func(a, b int) int { return a + b }) - const N = 100 - var reqs [N]request - for i := 0; i < N; i++ { - req := &reqs[i] - req.a = i - req.b = i + N - req.replyc = make(chan int) - adder <- req - } - for i := N - 1; i >= 0; i-- { // doesn't matter what order - if <-reqs[i].replyc != N+2*i { - fmt.Println("fail at", i) - } - } - fmt.Println("done") -} diff --git a/doc/progs/server1.go b/doc/progs/server1.go deleted file mode 100644 index a4093924b..000000000 --- a/doc/progs/server1.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import "fmt" - -type request struct { - a, b int - replyc chan int -} - -type binOp func(a, b int) int - -func run(op binOp, req *request) { - reply := op(req.a, req.b) - req.replyc <- reply -} - -func server(op binOp, service chan *request, quit chan bool) { - for { - select { - case req := <-service: - go run(op, req) // don't wait for it - case <-quit: - return - } - } -} - -func startServer(op binOp) (service chan *request, quit chan bool) { - service = make(chan *request) - quit = make(chan bool) - go server(op, service, quit) - return service, quit -} - -func main() { - adder, quit := startServer(func(a, b int) int { return a + b }) - const N = 100 - var reqs [N]request - for i := 0; i < N; i++ { - req := &reqs[i] - req.a = i - req.b = i + N - req.replyc = make(chan int) - adder <- req - } - for i := N - 1; i >= 0; i-- { // doesn't matter what order - if <-reqs[i].replyc != N+2*i { - fmt.Println("fail at", i) - } - } - quit <- true -} diff --git a/doc/progs/sieve.go b/doc/progs/sieve.go deleted file mode 100644 index b31530981..000000000 --- a/doc/progs/sieve.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import "fmt" - -// Send the sequence 2, 3, 4, ... to channel 'ch'. -func generate(ch chan int) { - for i := 2; ; i++ { - ch <- i // Send 'i' to channel 'ch'. - } -} - -// Copy the values from channel 'in' to channel 'out', -// removing those divisible by 'prime'. -func filter(in, out chan int, prime int) { - for { - i := <-in // Receive value of new variable 'i' from 'in'. - if i%prime != 0 { - out <- i // Send 'i' to channel 'out'. - } - } -} - -// The prime sieve: Daisy-chain filter processes together. -func main() { - ch := make(chan int) // Create a new channel. - go generate(ch) // Start generate() as a goroutine. - for i := 0; i < 100; i++ { // Print the first hundred primes. - prime := <-ch - fmt.Println(prime) - ch1 := make(chan int) - go filter(ch, ch1, prime) - ch = ch1 - } -} diff --git a/doc/progs/sieve1.go b/doc/progs/sieve1.go deleted file mode 100644 index e1411a334..000000000 --- a/doc/progs/sieve1.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import "fmt" - -// Send the sequence 2, 3, 4, ... to returned channel -func generate() chan int { - ch := make(chan int) - go func() { - for i := 2; ; i++ { - ch <- i - } - }() - return ch -} - -// Filter out input values divisible by 'prime', send rest to returned channel -func filter(in chan int, prime int) chan int { - out := make(chan int) - go func() { - for { - if i := <-in; i%prime != 0 { - out <- i - } - } - }() - return out -} - -func sieve() chan int { - out := make(chan int) - go func() { - ch := generate() - for { - prime := <-ch - out <- prime - ch = filter(ch, prime) - } - }() - return out -} - -func main() { - primes := sieve() - for i := 0; i < 100; i++ { // Print the first hundred primes. - fmt.Println(<-primes) - } -} diff --git a/doc/progs/slices.go b/doc/progs/slices.go new file mode 100644 index 000000000..8e440103e --- /dev/null +++ b/doc/progs/slices.go @@ -0,0 +1,63 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "io/ioutil" + "regexp" +) + +func AppendByte(slice []byte, data ...byte) []byte { + m := len(slice) + n := m + len(data) + if n > cap(slice) { // if necessary, reallocate + // allocate double what's needed, for future growth. + newSlice := make([]byte, (n+1)*2) + copy(newSlice, slice) + slice = newSlice + } + slice = slice[0:n] + copy(slice[m:n], data) + return slice +} + +// STOP OMIT + +// Filter returns a new slice holding only +// the elements of s that satisfy f() +func Filter(s []int, fn func(int) bool) []int { + var p []int // == nil + for _, i := range s { + if fn(i) { + p = append(p, i) + } + } + return p +} + +// STOP OMIT + +var digitRegexp = regexp.MustCompile("[0-9]+") + +func FindDigits(filename string) []byte { + b, _ := ioutil.ReadFile(filename) + return digitRegexp.Find(b) +} + +// STOP OMIT + +func CopyDigits(filename string) []byte { + b, _ := ioutil.ReadFile(filename) + b = digitRegexp.Find(b) + c := make([]byte, len(b)) + copy(c, b) + return c +} + +// STOP OMIT + +func main() { + // place holder; no need to run +} diff --git a/doc/progs/sort.go b/doc/progs/sort.go deleted file mode 100644 index 894693f0d..000000000 --- a/doc/progs/sort.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package sort - -type Interface interface { - Len() int - Less(i, j int) bool - Swap(i, j int) -} - -func Sort(data Interface) { - for i := 1; i < data.Len(); i++ { - for j := i; j > 0 && data.Less(j, j-1); j-- { - data.Swap(j, j-1) - } - } -} - -func IsSorted(data Interface) bool { - n := data.Len() - for i := n - 1; i > 0; i-- { - if data.Less(i, i-1) { - return false - } - } - return true -} - -// Convenience types for common cases - -type IntSlice []int - -func (p IntSlice) Len() int { return len(p) } -func (p IntSlice) Less(i, j int) bool { return p[i] < p[j] } -func (p IntSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -type Float64Slice []float64 - -func (p Float64Slice) Len() int { return len(p) } -func (p Float64Slice) Less(i, j int) bool { return p[i] < p[j] } -func (p Float64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -type StringSlice []string - -func (p StringSlice) Len() int { return len(p) } -func (p StringSlice) Less(i, j int) bool { return p[i] < p[j] } -func (p StringSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -// Convenience wrappers for common cases - -func SortInts(a []int) { Sort(IntSlice(a)) } -func SortFloat64s(a []float64) { Sort(Float64Slice(a)) } -func SortStrings(a []string) { Sort(StringSlice(a)) } - -func IntsAreSorted(a []int) bool { return IsSorted(IntSlice(a)) } -func Float64sAreSorted(a []float64) bool { return IsSorted(Float64Slice(a)) } -func StringsAreSorted(a []string) bool { return IsSorted(StringSlice(a)) } diff --git a/doc/progs/sortmain.go b/doc/progs/sortmain.go deleted file mode 100644 index c1babb01f..000000000 --- a/doc/progs/sortmain.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import ( - "fmt" - "./sort" -) - -func ints() { - data := []int{74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586} - a := sort.IntSlice(data) - sort.Sort(a) - if !sort.IsSorted(a) { - panic("fail") - } -} - -func strings() { - data := []string{"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"} - a := sort.StringSlice(data) - sort.Sort(a) - if !sort.IsSorted(a) { - panic("fail") - } -} - -type day struct { - num int - shortName string - longName string -} - -type dayArray struct { - data []*day -} - -func (p *dayArray) Len() int { return len(p.data) } -func (p *dayArray) Less(i, j int) bool { return p.data[i].num < p.data[j].num } -func (p *dayArray) Swap(i, j int) { p.data[i], p.data[j] = p.data[j], p.data[i] } - -func days() { - Sunday := day{0, "SUN", "Sunday"} - Monday := day{1, "MON", "Monday"} - Tuesday := day{2, "TUE", "Tuesday"} - Wednesday := day{3, "WED", "Wednesday"} - Thursday := day{4, "THU", "Thursday"} - Friday := day{5, "FRI", "Friday"} - Saturday := day{6, "SAT", "Saturday"} - data := []*day{&Tuesday, &Thursday, &Wednesday, &Sunday, &Monday, &Friday, &Saturday} - a := dayArray{data} - sort.Sort(&a) - if !sort.IsSorted(&a) { - panic("fail") - } - for _, d := range data { - fmt.Printf("%s ", d.longName) - } - fmt.Printf("\n") -} - - -func main() { - ints() - strings() - days() -} diff --git a/doc/progs/strings.go b/doc/progs/strings.go deleted file mode 100644 index e6739b385..000000000 --- a/doc/progs/strings.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import "os" - -func main() { - s := "hello" - if s[1] != 'e' { - os.Exit(1) - } - s = "good bye" - var p *string = &s - *p = "ciao" -} diff --git a/doc/progs/sum.go b/doc/progs/sum.go deleted file mode 100644 index e022195ed..000000000 --- a/doc/progs/sum.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import "fmt" - -func sum(a []int) int { // returns an int - s := 0 - for i := 0; i < len(a); i++ { - s += a[i] - } - return s -} - -func main() { - s := sum([3]int{1, 2, 3}[:]) // a slice of the array is passed to sum - fmt.Print(s, "\n") -} diff --git a/doc/progs/timeout1.go b/doc/progs/timeout1.go new file mode 100644 index 000000000..5221770ec --- /dev/null +++ b/doc/progs/timeout1.go @@ -0,0 +1,28 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +package timeout + +import ( + "time" +) + +func Timeout() { + ch := make(chan bool, 1) + timeout := make(chan bool, 1) + go func() { + time.Sleep(1 * time.Second) + timeout <- true + }() + + // STOP OMIT + + select { + case <-ch: + // a read from ch has occurred + case <-timeout: + // the read from ch has timed out + } + + // STOP OMIT +} diff --git a/doc/progs/timeout2.go b/doc/progs/timeout2.go new file mode 100644 index 000000000..7145bc93e --- /dev/null +++ b/doc/progs/timeout2.go @@ -0,0 +1,27 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +package query + +type Conn string + +func (c Conn) DoQuery(query string) Result { + return Result("result") +} + +type Result string + +func Query(conns []Conn, query string) Result { + ch := make(chan Result, 1) + for _, conn := range conns { + go func(c Conn) { + select { + case ch <- c.DoQuery(query): + default: + } + }(conn) + } + return <-ch +} + +// STOP OMIT diff --git a/doc/reference.html b/doc/reference.html new file mode 100644 index 000000000..beaac431d --- /dev/null +++ b/doc/reference.html @@ -0,0 +1,71 @@ +<!--{ + "Title": "References", + "Path": "/ref/" +}--> + +<img class="gopher" src="/doc/gopher/ref.png" /> + +<p>Good bedtime reading.</p> + +<div> + +<h3 id="pkg"><a href="/pkg/">Package Documentation</a></h3> +<p> +The documentation for the Go standard library. +</p> + +<h3 id="cmd"><a href="/doc/cmd">Command Documentation</a></h3> +<p> +The documentation for the Go tools. +</p> + +<h3 id="spec"><a href="/ref/spec">Language Specification</a></h3> +<p> +The official Go Language specification. +</p> + +<h3 id="appengine"><a href="http://code.google.com/appengine/docs/go/">App Engine Go Runtime Documentation</a></h3> +<p> +The documentation for +<a href="http://code.google.com/appengine/">Google App Engine</a>'s Go runtime. +</p> + +<h3 id="go_mem"><a href="/ref/mem">The Go Memory Model</a></h3> +<p> +A document that specifies the conditions under which reads of a variable in +one goroutine can be guaranteed to observe values produced by writes to the +same variable in a different goroutine. +</p> + +<h4 id="subrepos">Sub-repositories</h4> + +<p> +These packages are part of the Go Project but outside the main Go tree. +They are developed under looser <a href="/doc/go1compat.html">compatibility +requirements</a> than the Go core. +Install them with "<code><a href="/cmd/go/#Download_and_install_packages_and_dependencies">go get</a></code>". +</p> + +<ul> +<li><a href="http://code.google.com/p/go/source/browse?repo=codereview"><code>code.google.com/p/go.codereview</code></a> [<a href="http://gopkgdoc.appspot.com/pkg/code.google.com/p/go.codereview">docs</a>] +<li><a href="http://code.google.com/p/go/source/browse?repo=crypto"><code>code.google.com/p/go.crypto</code></a> [<a href="http://gopkgdoc.appspot.com/pkg/code.google.com/p/go.crypto">docs</a>] +<li><a href="http://code.google.com/p/go/source/browse?repo=image"><code>code.google.com/p/go.image</code></a> [<a href="http://gopkgdoc.appspot.com/pkg/code.google.com/p/go.image">docs</a>] +<li><a href="http://code.google.com/p/go/source/browse?repo=net"><code>code.google.com/p/go.net</code></a> [<a href="http://gopkgdoc.appspot.com/pkg/code.google.com/p/go.net">docs</a>] +</ul> + +<h4 id="articles">Articles</h4> + +<ul> +<li><a href="/doc/articles/c_go_cgo.html">C? Go? Cgo!</a> - linking against C code with <a href="/cmd/cgo/">cgo</a>.</li> +<li><a href="/doc/gdb">Debugging Go Code with GDB</a></li> +<li><a href="/doc/articles/defer_panic_recover.html">Defer, Panic, and Recover</a></li> +<li><a href="/doc/articles/slices_usage_and_internals.html">Go Slices: usage and internals</a></li> +<li><a href="/doc/articles/godoc_documenting_go_code.html">Godoc: documenting Go code</a> - writing good documentation for <a href="/cmd/godoc/">godoc</a>.</li> +<li><a href="http://blog.golang.org/2011/06/profiling-go-programs.html">Profiling Go Programs</a></li> +</ul> + +<p> +See the <a href="/doc/#articles">documentation page</a> for more articles. +</p> + +</div> diff --git a/doc/root.html b/doc/root.html index 2d9a8979b..3b92229cb 100644 --- a/doc/root.html +++ b/doc/root.html @@ -1,101 +1,138 @@ -<link rel="stylesheet" type="text/css" href="/doc/frontpage.css"> +<!--{ + "Path": "/" +}--> -<script src="http://www.google.com/jsapi" type="text/javascript"></script> +<div class="left"> + +<div id="learn"> +<img class="icon share" src="/doc/share.png" alt="View full screen" title="View full screen"> +<div class="rootHeading">Try Go</div> +<div class="input"> +<textarea spellcheck="false" class="code">// You can edit this code! +// Click here and start typing. +package main + +import "fmt" + +func main() { + fmt.Println("Hello, 世界") +}</textarea> +</div> +<div class="output"> +<pre> +Hello, 世界 +</pre> +</div> +<div class="buttons"> +<a class="run" href="#" title="Run this code [shift-enter]">Run</a> +<a class="share" href="#" title="Share this code">Share</a> +<a class="tour" href="http://tour.golang.org/" title="Learn Go from your browser">Tour</a> +</div> +<div class="toys"> +<select> + <option value="hello.go">Hello, World!</option> + <option value="fib.go">Fibonacci Closure</option> + <option value="peano.go">Peano Integers</option> + <option value="pi.go">Concurrent pi</option> + <option value="sieve.go">Concurrent Prime Sieve</option> + <option value="solitaire.go">Peg Solitaire Solver</option> + <option value="tree.go">Tree Comparison</option> +</select> +</div> +</div> + +</div> + +<div class="right"> + +<div id="about"> +Go is an open source programming environment that makes it easy to build +simple, reliable, and efficient software. +</div> + +<div id="gopher"></div> + +<a href="/doc/install" id="start"> +<div class="big">Download Go</div> +<div class="desc"> +Binary distributions available for<br> +Linux, Mac OS X, Windows, and more. +</div> +</a> + +</div> + +<div style="clear: both"></div> + +<div class="left"> + +<div id="video"> +<div class="rootHeading">Featured video</div> +<a class="title" href="http://www.youtube.com/watch?v=Mo1YKpIF1PQ">Building integrated apps on Google's cloud platform with Go</a> +<iframe width="415" height="241" src="http://www.youtube.com/embed/Mo1YKpIF1PQ" frameborder="0" allowfullscreen></iframe> +</div> + +</div> + +<div class="right"> + +<div id="blog"> +<div class="rootHeading">Featured articles</div> +<div class="read"><a href="http://blog.golang.org/">Read more</a></div> +</div> + +</div> + +<div style="clear: both;"></div> + +<script type="text/javascript" src="https://www.google.com/jsapi"></script> +<script type="text/javascript" src="/doc/play/playground.js"></script> <script type="text/javascript"> -function loadFeed() { - var url = "http://blog.golang.org/feeds/posts/default"; - var divId = "blogFeed"; - var feed = new google.feeds.Feed(url); - feed.setNumEntries(4) - feed.load(function (result) { - var container = document.getElementById(divId) - if (result.error) { - container.innerHTML = "Error loading feed."; - return; - } - container.innerHTML = ""; - var entries = result.feed.entries; - for (var i=0; i<entries.length; i++) { - var li = document.createElement("li"); - var a = document.createElement("a"); - a.setAttribute("href", entries[i].link); - var span_title = document.createElement("span"); - span_title.appendChild(document.createTextNode(entries[i].title)); - span_title.className = "title"; - a.appendChild(span_title); - li.appendChild(a); - var span_date = document.createElement("span"); - span_date.appendChild(document.createTextNode(entries[i].publishedDate.substr(0, 11))); - span_date.className = "date"; - a.appendChild(span_date); - container.appendChild(li); - } - }); -} google.load("feeds", "1"); -google.setOnLoadCallback(loadFeed); -</script> +google.load("jquery", "1.7.1"); - <div id="frontpage"> - <div class="left-column"> - <p style="margin-top: 0;"> - The Go programming language is an open source project to make - programmers more productive. Go is expressive, concise, clean, - and efficient. Its concurrency mechanisms make it easy to write - programs that get the most out of multicore and networked machines, - while its novel type system enables flexible and modular program - construction. Go compiles quickly to machine code yet has the - convenience of garbage collection and the power of run-time reflection. - It's a fast, statically typed, compiled language that feels like a - dynamically typed, interpreted language. - </p> - <h2> - Get started now with - <a target="_blank" href="http://go-tour.appspot.com/">A Tour of Go</a>. - </h2> - <p> - <div class="how">[<a href="/doc/playground.html">How does this work?</a>]</div> - Or try it right here in your browser:</p> - <div id="playground" class="small"></div> - <script src="/doc/play/playground.js"></script> - </div> - <div class="right-column"> - <div id="content-rotating"> - <div id="content-videos"> - <h2>Go Videos <span class="more">| <a href="/doc/docs.html#videos_talks">More...</a></span></h2> - <a class="video" href="http://www.youtube.com/watch?v=-i0hat7pdpk"><img src="/doc/play_overlay.png" class="thumbnail _005" /> <span class="caption title">“Writing Web Apps in Go”</span> <span class="caption description">Google I/O 2011</span></a> - </div> - <h2>Go Blog <span class="more">| <a href="http://blog.golang.org/">More...</a></span></h2> - <div id="content-blog"> - <ul id="blogFeed"> - </ul> - </div> - </div> - <h2>Quick Links</h2> - <div id="resources"> - <div id="resources-users"> - <h3>For newcomers:</h3> - <ul> - <li><a href="/doc/install.html">Getting Started</a></li> - <li><a href="/doc/go_tutorial.html">Tutorial</a></li> - <li><a href="/doc/effective_go.html">Effective Go</a></li> - <li><a href="/doc/go_faq.html">Go FAQ</a></li> - <li><a href="/doc/docs.html">Other Documentation</a></li> - <li><a href="http://code.google.com/appengine/docs/go/">Go for Google App Engine</a> <sup class="new">New!</sup></li> - </ul> - </div> - <div id="resources-contributors" > - <h3>For developers:</h3> - <ul> - <li><a href="http://godashboard.appspot.com/package">Package Dashboard</a></li> - <li><a href="http://code.google.com/p/go/issues">Issue Tracker</a></li> - <li><a href="http://godashboard.appspot.com/">Build Status</a></li> - <li><a href="http://code.google.com/p/go/source/browse/">Go Source</a> [<a href="http://code.google.com/p/go/source/list">changes</a>]</li> - <li><a href="/pkg/">Package Reference</a></li> - <li><a href="/doc/go_spec.html">Language Specification</a></li> - </ul> - </div> - </div> - </div> - <div class="end-columns"></div> - </div> +function feedLoaded(result) { + if (result.error) { + console.log(result.error); + return; + } + var blog = document.getElementById("blog"); + var read = blog.getElementsByClassName("read")[0]; + for (var i = 0; i < result.feed.entries.length && i < 2; i++) { + var entry = result.feed.entries[i]; + var title = document.createElement("a"); + title.className = "title"; + title.href = entry.link; + title.innerHTML = entry.title; + blog.insertBefore(title, read); + var extract = document.createElement("div"); + extract.className = "extract"; + extract.innerHTML = entry.contentSnippet; + blog.insertBefore(extract, read); + var when = document.createElement("div"); + when.className = "when"; + var pub = entry.publishedDate.split(" ").slice(1,3).join(" "); + when.innerHTML = "Published " + pub + blog.insertBefore(when, read); + } +} + +function init() { + // Load blog feed. + var feed = new google.feeds.Feed("http://blog.golang.org/feeds/posts/default"); + feed.load(feedLoaded); + + // Set up playground. + playground({ + "simple": true, + "codeEl": "#learn .code", + "outputEl": "#learn .output", + "runEl": "#learn .run", + "shareEl": "#learn .share", + "shareRedirect": "http://play.golang.org/p/", + "toysEl": "#learn .toys select" + }); +} + +google.setOnLoadCallback(init); +</script> diff --git a/doc/share.png b/doc/share.png Binary files differnew file mode 100644 index 000000000..c04f0c71a --- /dev/null +++ b/doc/share.png diff --git a/doc/style.css b/doc/style.css new file mode 100644 index 000000000..95be3a17a --- /dev/null +++ b/doc/style.css @@ -0,0 +1,391 @@ +body { + margin: 0; + font-family: Helvetica, Arial, sans-serif; + font-size: 16px; +} +pre, +code { + font-family: Menlo, monospace; + font-size: 14px; +} +pre { + line-height: 18px; +} +pre .comment { + color: #375EAB; +} +pre .highlight, +pre .highlight-comment, +pre .selection-highlight, +pre .selection-highlight-comment { + background: #FFFF00; +} +pre .selection, +pre .selection-comment { + background: #FF9632; +} +pre .ln { + color: #999; +} +body { + color: #222; +} +a, +.exampleHeading .text { + color: #375EAB; + text-decoration: none; +} +a:hover, +.exampleHeading .text:hover { + text-decoration: underline; +} +p, +pre, +ul, +ol { + margin: 20px; +} +pre { + background: #e9e9e9; + padding: 10px; + + -webkit-border-radius: 5px; + -moz-border-radius: 5px; + border-radius: 5px; +} + +h1, +h2, +h3, +h4, +.rootHeading { + margin: 20px 0; + padding: 0; + color: #375EAB; + font-weight: bold; +} +h1 { + font-size: 24px; +} +h2 { + font-size: 20px; + background: #E0EBF5; + padding: 2px 5px; +} +h3 { + font-size: 20px; +} +h3, +h4 { + margin: 20px 5px; +} +h4 { + font-size: 16px; +} +.rootHeading { + font-size: 20px; + margin: 0; +} + +dl { + margin: 20px; +} +dd { + margin: 2px 20px; +} +dl, +dd { + font-size: 14px; +} +div#nav table td { + vertical-align: top; +} + +table.dir th { + text-align: left; +} +table.dir td { + word-wrap: break-word; + vertical-align: top; +} + +.alert { + color: #AA0000; +} + +div#heading { + float: left; + margin: 0 0 10px 0; + padding: 21px 0; + font-size: 20px; + font-weight: normal; +} +div#heading a { + color: #222; + text-decoration: none; +} + +div#topbar { + background: #E0EBF5; + height: 64px; +} + +body { + text-align: center; +} +div#page, +div#topbar > .container { + clear: both; + text-align: left; + margin-left: auto; + margin-right: auto; + padding: 0 20px; + width: 900px; +} +div#page.wide, +div#topbar > .wide { + width: auto; +} +div#plusone { + float: right; +} + +div#footer { + color: #666; + font-size: 14px; + margin: 40px 0; +} + +div#menu > a, +div#menu > input, +div#learn .buttons a, +div#blog .read a { + padding: 10px; + + text-decoration: none; + font-size: 16px; + + -webkit-border-radius: 5px; + -moz-border-radius: 5px; + border-radius: 5px; +} +div#menu > a, +div#menu > input { + border: 1px solid #375EAB; +} +div#menu > a { + color: white; + background: #375EAB; +} +a#start, +div#learn .buttons a, +div#blog .read a { + color: #222; + border: 1px solid #375EAB; + background: #E0EBF5; +} + +div#menu { + float: right; + min-width: 590px; + padding: 10px 0; + text-align: right; +} +div#menu > a { + margin-right: 5px; + margin-bottom: 10px; + + padding: 10px; +} +div#menu > input { + position: relative; + top: 1px; + width: 60px; + background: white; + color: #222; +} +div#menu > input.inactive { + color: #999; +} + +div.left { + float: left; +} +div.right { + float: right; +} +div.left, +div.right { + width: 415px; +} + +div#learn, +div#about { + padding-top: 20px; +} +div#learn h2, +div#about { + margin: 0; +} +div#about { + font-size: 20px; +} + +div#about { + height: 96px; +} +div#gopher { + background: url(/doc/gopher/frontpage.png) no-repeat; + background-position: center top; + height: 155px; +} +a#start { + display: block; + padding: 10px; + + text-align: center; + text-decoration: none; + + -webkit-border-radius: 5px; + -moz-border-radius: 5px; + border-radius: 5px; +} +a#start .big { + font-weight: bold; + font-size: 20px; +} +a#start .desc { + font-size: 14px; + font-weight: normal; + margin-top: 5px; +} + +div#learn .icon { + float: right; + cursor: pointer; +} +div#learn pre, +div#learn textarea { + padding: 0; + margin: 0; + font-family: Menlo, monospace; + font-size: 14px; +} +div#learn .input { + padding: 10px; + margin-top: 10px; + height: 150px; + + -webkit-border-top-left-radius: 5px; + -webkit-border-top-right-radius: 5px; + -moz-border-radius-topleft: 5px; + -moz-border-radius-topright: 5px; + border-top-left-radius: 5px; + border-top-right-radius: 5px; +} +div#learn .input textarea { + width: 100%; + height: 100%; + border: none; + outline: none; + resize: none; +} +div#learn .output { + border-top: none !important; + + padding: 10px; + height: 59px; + overflow: auto; + + -webkit-border-bottom-right-radius: 5px; + -webkit-border-bottom-left-radius: 5px; + -moz-border-radius-bottomright: 5px; + -moz-border-radius-bottomleft: 5px; + border-bottom-right-radius: 5px; + border-bottom-left-radius: 5px; +} +div#learn .output pre { + padding: 0; + + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; +} +div#learn .input, +div#learn .input textarea, +div#learn .output, +div#learn .output pre { + background: #FFFFD8; +} +div#learn .input, +div#learn .output { + border: 1px solid #375EAB; +} +div#learn .buttons { + float: right; + padding: 20px 0 10px 0; + text-align: right; +} +div#learn .buttons a { + height: 16px; + margin-left: 5px; + padding: 10px; +} +div#learn .toys { + margin-top: 8px; +} +div#learn .toys select { + border: 1px solid #375EAB; + margin: 0; +} + +div#blog, +div#video { + margin-top: 40px; +} +div#blog > a, +div#blog > div, +div#blog > h2, +div#video > a, +div#video > div, +div#video > h2 { + margin-bottom: 10px; +} +div#blog .title, +div#video .title { + display: block; + font-size: 20px; +} +div#blog .when { + color: #666; + font-size: 14px; +} +div#blog .read { + text-align: right; +} + +.toggleButton { cursor: pointer; } +.toggle .collapsed { display: block; } +.toggle .expanded { display: none; } +.toggleVisible .collapsed { display: none; } +.toggleVisible .expanded { display: block; } + +table.codetable { margin-left: auto; margin-right: auto; border-style: none; } +hr { border-style: none; border-top: 1px solid black; } + +img.gopher { + float: right; + margin-left: 10px; + margin-bottom: 10px; +} +.pkgGopher { + text-align: right; +} +.pkgGopher .gopher { + float: none; + position: relative; + top: -40px; + margin-bottom: -120px; +} +h2 { clear: right; } + diff --git a/doc/talks/go_talk-20100323.html b/doc/talks/go_talk-20100323.html index 3143b079a..7330dd2ae 100644 --- a/doc/talks/go_talk-20100323.html +++ b/doc/talks/go_talk-20100323.html @@ -380,7 +380,7 @@ containing other data structures as continuous blocks of memory." <h2>And more:</h2> <ul> <li>I haven't talked about the type system, interfaces, slices, closures, selects, ...</li> - <li>Tutorial, documentation, mailing list, source code all online</li> + <li>Documentation, mailing list, source code all online</li> </ul> </div> diff --git a/doc/talks/io2010/balance.go b/doc/talks/io2010/balance.go index b01f7468c..a3825cbc5 100644 --- a/doc/talks/io2010/balance.go +++ b/doc/talks/io2010/balance.go @@ -8,7 +8,7 @@ import ( "container/heap" "flag" "fmt" - "rand" + "math/rand" "time" ) diff --git a/doc/talks/io2010/decrypt.go b/doc/talks/io2010/decrypt.go index 0a6c006e2..e63418b1a 100644 --- a/doc/talks/io2010/decrypt.go +++ b/doc/talks/io2010/decrypt.go @@ -15,7 +15,7 @@ import ( "os" ) -func EncryptAndGzip(dstfile, srcfile string, key, iv []byte) os.Error { +func EncryptAndGzip(dstfile, srcfile string, key, iv []byte) error { r, err := os.Open(srcfile) if err != nil { return err @@ -39,7 +39,7 @@ func EncryptAndGzip(dstfile, srcfile string, key, iv []byte) os.Error { return err } -func DecryptAndGunzip(dstfile, srcfile string, key, iv []byte) os.Error { +func DecryptAndGunzip(dstfile, srcfile string, key, iv []byte) error { f, err := os.Open(srcfile) if err != nil { return err diff --git a/doc/talks/io2010/encrypt.go b/doc/talks/io2010/encrypt.go index c6508bba1..57c888c74 100644 --- a/doc/talks/io2010/encrypt.go +++ b/doc/talks/io2010/encrypt.go @@ -15,7 +15,7 @@ import ( "os" ) -func EncryptAndGzip(dstfile, srcfile string, key, iv []byte) os.Error { +func EncryptAndGzip(dstfile, srcfile string, key, iv []byte) error { r, err := os.Open(srcfile) if err != nil { return err diff --git a/doc/talks/io2010/eval1.go b/doc/talks/io2010/eval1.go index 2d7fc3be6..582f43e8e 100644 --- a/doc/talks/io2010/eval1.go +++ b/doc/talks/io2010/eval1.go @@ -101,7 +101,6 @@ func main() { } } - // Custom grammar and values var precTab = map[string]int{ @@ -125,7 +124,7 @@ func newVal(lit string) Value { if err == nil { return Int(x) } - b, err := strconv.Atob(lit) + b, err := strconv.ParseBool(lit) if err == nil { return Bool(b) } @@ -175,7 +174,7 @@ func (x Int) BinaryOp(op string, y Value) Value { type Bool bool -func (x Bool) String() string { return strconv.Btoa(bool(x)) } +func (x Bool) String() string { return strconv.FormatBool(bool(x)) } func (x Bool) BinaryOp(op string, y Value) Value { switch y := y.(type) { case Error: @@ -195,7 +194,6 @@ func (x Bool) BinaryOp(op string, y Value) Value { return Error(fmt.Sprintf("illegal operation: '%v %s %v'", x, op, y)) } - func trace(newVal func(string) Value) func(string) Value { return func(s string) Value { v := newVal(s) diff --git a/doc/talks/io2010/eval2.go b/doc/talks/io2010/eval2.go index 5524c8b3a..6f826e12d 100644 --- a/doc/talks/io2010/eval2.go +++ b/doc/talks/io2010/eval2.go @@ -101,7 +101,6 @@ func main() { } } - // Custom grammar and values var precTab = map[string]int{ @@ -125,7 +124,7 @@ func newVal(lit string) Value { if err == nil { return Int(x) } - b, err := strconv.Atob(lit) + b, err := strconv.ParseBool(lit) if err == nil { return Bool(b) } @@ -184,7 +183,7 @@ func (x Int) BinaryOp(op string, y Value) Value { type Bool bool -func (x Bool) String() string { return strconv.Btoa(bool(x)) } +func (x Bool) String() string { return strconv.FormatBool(bool(x)) } func (x Bool) BinaryOp(op string, y Value) Value { switch y := y.(type) { case Error: @@ -227,7 +226,6 @@ func (x String) BinaryOp(op string, y Value) Value { return Error(fmt.Sprintf("illegal operation: '%v %s %v'", x, op, y)) } - func trace(newVal func(string) Value) func(string) Value { return func(s string) Value { v := newVal(s) diff --git a/doc/tmpltohtml.go b/doc/tmpltohtml.go deleted file mode 100644 index f4d2e2c2c..000000000 --- a/doc/tmpltohtml.go +++ /dev/null @@ -1,176 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - - -// The template uses the function "code" to inject program -// source into the output by extracting code from files and -// injecting them as HTML-escaped <pre> blocks. -// -// The syntax is simple: 1, 2, or 3 space-separated arguments: -// -// Whole file: -// {{code "foo.go"}} -// One line (here the signature of main): -// {{code "foo.go" `/^func.main/`}} -// Block of text, determined by start and end (here the body of main): -// {{code "foo.go" `/^func.main/` `/^}/` -// -// Patterns can be `/regular expression/`, a decimal number, or "$" -// to signify the end of the file. -package main - -import ( - "exp/template" - "flag" - "fmt" - "io/ioutil" - "log" - "os" - "regexp" - "strings" -) - -func Usage() { - fmt.Fprintf(os.Stderr, "usage: tmpltohtml file\n") - os.Exit(2) -} - -func main() { - flag.Usage = Usage - flag.Parse() - if len(flag.Args()) != 1 { - Usage() - } - - // Read and parse the input. - name := flag.Args()[0] - tmpl := template.New(name).Funcs(template.FuncMap{"code": code}) - if _, err := tmpl.ParseFile(name); err != nil { - log.Fatal(err) - } - - // Execute the template. - if err := tmpl.Execute(os.Stdout, 0); err != nil { - log.Fatal(err) - } -} - -// contents reads a file by name and returns its contents as a string. -func contents(name string) string { - file, err := ioutil.ReadFile(name) - if err != nil { - log.Fatal(err) - } - return string(file) -} - -// format returns a textual representation of the arg, formatted according to its nature. -func format(arg interface{}) string { - switch arg := arg.(type) { - case int: - return fmt.Sprintf("%d", arg) - case string: - if len(arg) > 2 && arg[0] == '/' && arg[len(arg)-1] == '/' { - return fmt.Sprintf("%#q", arg) - } - return fmt.Sprintf("%q", arg) - default: - log.Fatalf("unrecognized argument: %v type %T", arg, arg) - } - return "" -} - -func code(file string, arg ...interface{}) (string, os.Error) { - text := contents(file) - var command string - switch len(arg) { - case 0: - // text is already whole file. - command = fmt.Sprintf("code %q", file) - case 1: - command = fmt.Sprintf("code %q %s", file, format(arg[0])) - text = oneLine(file, text, arg[0]) - case 2: - command = fmt.Sprintf("code %q %s %s", file, format(arg[0]), format(arg[1])) - text = multipleLines(file, text, arg[0], arg[1]) - default: - return "", fmt.Errorf("incorrect code invocation: code %q %q", file, arg) - } - // Replace tabs by spaces, which work better in HTML. - text = strings.Replace(text, "\t", " ", -1) - // Escape the program text for HTML. - text = template.HTMLEscapeString(text) - // Include the command as a comment. - text = fmt.Sprintf("<pre><!--{{%s}}\n-->%s</pre>", command, text) - return text, nil -} - -// parseArg returns the integer or string value of the argument and tells which it is. -func parseArg(arg interface{}, file string, max int) (ival int, sval string, isInt bool) { - switch n := arg.(type) { - case int: - if n <= 0 || n > max { - log.Fatalf("%q:%d is out of range", file, n) - } - return n, "", true - case string: - return 0, n, false - } - log.Fatalf("unrecognized argument %v type %T", arg, arg) - return -} - -// oneLine returns the single line generated by a two-argument code invocation. -func oneLine(file, text string, arg interface{}) string { - lines := strings.SplitAfter(contents(file), "\n") - line, pattern, isInt := parseArg(arg, file, len(lines)) - if isInt { - return lines[line-1] - } - return lines[match(file, 0, lines, pattern)-1] -} - -// multipleLines returns the text generated by a three-argument code invocation. -func multipleLines(file, text string, arg1, arg2 interface{}) string { - lines := strings.SplitAfter(contents(file), "\n") - line1, pattern1, isInt1 := parseArg(arg1, file, len(lines)) - line2, pattern2, isInt2 := parseArg(arg2, file, len(lines)) - if !isInt1 { - line1 = match(file, 0, lines, pattern1) - } - if !isInt2 { - line2 = match(file, line1, lines, pattern2) - } else if line2 < line1 { - log.Fatal("lines out of order for %q: %d %d", line1, line2) - } - return strings.Join(lines[line1-1:line2], "") -} - -// match identifies the input line that matches the pattern in a code invocation. -// If start>0, match lines starting there rather than at the beginning. -// The return value is 1-indexed. -func match(file string, start int, lines []string, pattern string) int { - // $ matches the end of the file. - if pattern == "$" { - if len(lines) == 0 { - log.Fatal("%q: empty file", file) - } - return len(lines) - } - // /regexp/ matches the line that matches the regexp. - if len(pattern) > 2 && pattern[0] == '/' && pattern[len(pattern)-1] == '/' { - re, err := regexp.Compile(pattern[1 : len(pattern)-1]) - if err != nil { - log.Fatal(err) - } - for i := start; i < len(lines); i++ { - if re.MatchString(lines[i]) { - return i + 1 - } - } - log.Fatalf("%s: no match for %#q", file, pattern) - } - log.Fatalf("unrecognized pattern: %q", pattern) - return 0 -} diff --git a/doc/tos.html b/doc/tos.html new file mode 100644 index 000000000..67b107dca --- /dev/null +++ b/doc/tos.html @@ -0,0 +1,11 @@ +<!--{ + "Title": "Terms of service" +}--> + +<p> +The Go website (the "Website") is hosted by Google. +By using and/or visiting the Website, you consent to be bound by Google's general +<a href="http://www.google.com/intl/en/policies/terms/">Terms of Service</a> +and Google's general +<a href="http://www.google.com/intl/en/privacy/privacy-policy.html">Privacy Policy</a>. +</p> diff --git a/doc/video-001.png b/doc/video-001.png Binary files differdeleted file mode 100644 index d3468bbe8..000000000 --- a/doc/video-001.png +++ /dev/null diff --git a/doc/video-002.png b/doc/video-002.png Binary files differdeleted file mode 100644 index 4f7c5d184..000000000 --- a/doc/video-002.png +++ /dev/null diff --git a/doc/video-003.png b/doc/video-003.png Binary files differdeleted file mode 100644 index 3dff68602..000000000 --- a/doc/video-003.png +++ /dev/null diff --git a/doc/video-004.png b/doc/video-004.png Binary files differdeleted file mode 100644 index 92144549a..000000000 --- a/doc/video-004.png +++ /dev/null diff --git a/doc/video-005.jpg b/doc/video-005.jpg Binary files differdeleted file mode 100644 index 32371581f..000000000 --- a/doc/video-005.jpg +++ /dev/null |