From d39f5aa373a4422f7a5f3ee764fb0f6b0b719d61 Mon Sep 17 00:00:00 2001
From: Ondřej Surý
-Now that we've removed the fmt.Sprintf
statement, we can remove
+Now that we've removed the fmt.Fprintf
statement, we can remove
"fmt"
from the import
list.
-Now that we've removed the fmt.Sprintf
statement, we can remove
+Now that we've removed the fmt.Fprintf
statement, we can remove
"fmt"
from the import
list.
If you spot bugs, mistakes, or inconsistencies in the Go project's code or @@ -19,7 +19,7 @@ a new one.) We pride ourselves on being meticulous; no issue is too small.
-Go is an open source project and we welcome contributions from the community. @@ -39,7 +39,7 @@ are particularly in need of outside help.
View the status of Go builds across the supported operating @@ -49,7 +49,10 @@ systems and architectures.
Features and ideas being developed or discussed by the Go team.
A summary of the changes between tagged releases of Go.
+A summary of the changes between Go releases.
+ +A summary of the changes between weekly snapshots of Go.
The golang-dev
diff --git a/doc/contribute.html b/doc/contribute.html
index ba70c9600..c4b1ce2b5 100644
--- a/doc/contribute.html
+++ b/doc/contribute.html
@@ -209,7 +209,8 @@ The Reviewer
line lists the reviewers assigned
to this change, and the CC
line lists people to
notify about the change.
These can be code review nicknames or arbitrary email addresses.
-If you don't know who is best to review the change, set the
+Unless explicitly told otherwise, such as in the discussion leading
+up to sending in the change list, set the
reviewer field to the
golang-dev@googlegroups.com
mailing list.
diff --git a/doc/devel/release.html b/doc/devel/release.html
index 84ca622fa..d632200d3 100644
--- a/doc/devel/release.html
+++ b/doc/devel/release.html
@@ -14,6 +14,78 @@ hg pull
hg update release.rNN
+
+The r58 release corresponds to
+weekly.2011-06-09
+with additional bug fixes.
+This section highlights the most significant changes in this release.
+For a more detailed summary, see the
+weekly release notes.
+For complete information, see the
+Mercurial change list.
+
+This release fixes a use of uninitialized memory in programs that misuse goto
.
+
+As usual, gofix will handle the bulk of the rewrites +necessary for these changes to package APIs. +
+ +
+Package http drops the finalURL
return
+value from the Client.Get method. The value
+is now available via the new Request
field on http.Response.
+Most instances of the type map[string][]string in have been
+replaced with the new Values type.
+
+Package exec has been redesigned with a more +convenient and succinct API. +
+ +
+Package strconv's Quote
+function now escapes only those Unicode code points not classified as printable
+by unicode.IsPrint.
+Previously Quote would escape all non-ASCII characters.
+This also affects the fmt package's "%q"
+formatting directive. The previous quoting behavior is still available via
+strconv's new QuoteToASCII function.
+
+Package os/signal's +Signal and +UnixSignal types have been moved to the +os package. +
+ +
+Package image/draw is the new name for
+exp/draw
. The GUI-related code from exp/draw
is now
+located in the exp/gui package.
+
+Goinstall now observes the GOPATH environment +variable to build and install your own code and external libraries outside of +the Go tree (and avoid writing Makefiles). +
+ +diff --git a/doc/devel/roadmap.html b/doc/devel/roadmap.html index 343203cdb..d3c494715 100644 --- a/doc/devel/roadmap.html +++ b/doc/devel/roadmap.html @@ -43,8 +43,6 @@ Improved garbage collector.
+This release 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. + +The strconv package's Quote function now escapes only those Unicode code points +not classified as printable by unicode.IsPrint. Previously Quote would escape +all non-ASCII characters. This also affects the fmt package's "%q" formatting +directive. The previous quoting behavior is still available via strconv's new +QuoteToASCII function. + +Most instances of the type map[string][]string in the http package have been +replaced with the new Values type. The http.Values type has the Get, Set, Add, +and Del helper methods to make working with query parameters and form values +more convenient. + +The exp/draw package has been split into the image/draw and exp/gui packages. + +Other changes: +* 8l, ld: initial adjustments for Plan 9 native compilation of 8l (thanks Lucio De Re). +* arm: floating point improvements (thanks Fan Hongjian). +* big: Improved speed of nat-to-string conversion (thanks Michael T. Jones), + Rat outputs the requested precision from FloatString (thanks Graham Miller), + gobs for big.Rats. +* cgo: support non intel gcc machine flags (thanks Dave Cheney). +* compress/lzw: do not use background goroutines, + reduce decoder buffer size from 3*4096 to 2*4096. +* crypto/twofish: fix Reset index overflow bug. +* crypto: reorg, cleanup and add function for generating CRLs. +* exec: export the underlying *os.Process in Cmd. +* gc: enable building under clang/2.9 (thanks Dave Cheney), + preparatory work toward escape analysis, compact stack frames. +* go/build: new incomplete package for building go programs. +* godefs: do not assume forward type references are enums (thanks Robert Hencke). +* gofix, gofmt: fix diff regression from exec change. +* html: improve attribute parsing, note package status. +* http: don't fail on accept hitting EMFILE, + fix handling of 0-length HTTP requests. +* image/draw: fix clipping bug where sp/mp were not shifted when r.Min was. +* image/gif: fix buglet in graphics extension. +* image/tiff: support for bit depths other than 8 (thanks Benny Siegert). +* ld: fix and simplify ELF symbol generation (thanks Anthony Martin) +* libmach: use the standardized format for designated initializers (thanks Jeff Hodges) +* mail: address list parsing. +* net: add network interface identification API (thanks Mikio Hara), + fix bug in net.Interfaces: handle elastic sdl_data size correctly (thanks Mikio Hara). +* netchan: added drain method to importer (thanks David Jakob Fritz). +* os: add Process.Kill and Process.Signal (thanks Evan Shaw), + fix Getenv for Plan 9 (thanks Yuval Pavel Zholkover). +* runtime: improve memmove by checking memory overlap (thanks Quan Yong Zhai), + support for Linux grsecurity systems (thanks Jonathan Mark). +* spec: handle a corner case for shifts. +* testing: check that tests and benchmarks do not affect GOMAXPROCS (thanks Dmitriy Vyukov). +* unicode: add IsPrint and related properties, general categories. ++ +
+This release 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. +This code: + args := []string{"diff", "-u", "file1.txt", "file2.txt"} + p, err := exec.Run("/usr/bin/diff", args, os.Environ(), "", + exec.DevNull, exec.Pipe, exec.DevNull) + if err != nil { + return nil, err + } + var buf bytes.Buffer + io.Copy(&buf, p.Stdout) + w, err := p.Wait(0) + p.Close() + if err != nil { + return nil, err + } + return buf.Bytes(), err +can be rewritten as: + return exec.Command("diff", "-u", "file1.txt", "file2.txt").Output() +See the exec package documentation for the details ("godoc exec"). + +By setting the GOPATH environment variable you can use goinstall to build and +install your own code and external libraries outside of the Go tree (and avoid +writing Makefiles). +See the goinstall command documentation for the details ("godoc goinstall"). + +Other changes: +* 5g: alignment fixes. +* 6l, 8l: fix Mach-O binaries with many dynamic libraries. +* 8l: emit resources (.rsrc) in Windows PE. (thanks Wei Guangjing). +* asn1: fix marshalling of empty optional RawValues (thanks Mikkel Krautz). +* big: make Int and Rat implement fmt.Scanner (thanks Evan Shaw), + ~8x faster number scanning, + remove some unnecessary conversions. +* cgo: restrict #cgo directives to prevent shell expansion (thanks Gustavo Niemeyer), + support pkg-config for flags and libs (thanks Gustavo Niemeyer). +* compress/flate: fix Huffman tree bug, + do not use background goroutines. +* crypto/openpgp: add support for symmetrically encrypting files. +* crypto/tls/generate_cert.go: fix misspelling of O_CREATE. +* dashboard: send notification emails when the build breaks. +* doc: mention go/printer instead of container/vector in effective go, + put Release History link on 'Documentation' page, + put Weekly Snapshot History link on 'Contributing' page. +* encoding/base64: add DecodeString and EncodeToString. +* encoding/binary: add a non-reflect fast path for Read, + add a non-reflect fast path for Write. +* encoding/hex: add hex dumping. +* encoding/line: delete package. Its functionality is now in bufio. +* filepath: Abs must always return a clean path (thanks Gustavo Niemeyer). +* fmt: fix bug in UnreadRune, + make %q work for integers, printing a quoted character literal, + return EOF when out of input in Scan*. +* gc: check parameter declarations in interface fields (thanks Anthony Martin), + disallow ... in type conversions (thanks Anthony Martin), + do not force heap allocation on referencing outer variable in a closure, + fix m[x], _ = y.(T), + implement new shift rules, + patch y.tab.c to fix build when using Bison 2.5, + relax assignability of method receivers (thanks Anthony Martin), + typecheck the whole tree before walking. +* go/scanner: don't allow "0x" and "0X" as integers (thanks Evan Shaw). +* gobuilder: fixes for windows (thanks Alex Brainman). +* godoc: basic setup for running godoc on local app engine emulator, + display advert for the package dashboard on package list page. +* 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: Transport hook to register non-http(s) protocols, + add client+server benchmark, + catch Handler goroutine panics, + fix Set-Cookie date parsing, + have client set Content-Length when possible, + let Transport use a custom net.Dial function, + propagate Set-Cookie in reverse proxy, + ServeFile shouldn't send Content-Length when Content-Encoding is set. +* image: add a SubImage method. +* image/gif: simplify blockReader.Read. +* image/png: fix encoding of images that don't start at (0, 0). +* io, net, http: sendfile support. +* io: add ByteScanner, RuneScanner interfaces. +* ld: add -w to disable dwarf, make errors obviously from dwarf. +* mail: new package. +* mime/multipart: misc code/doc fixes. +* misc/cgo: remove reference to 'destroy' function. +* misc/emacs: don't select the mark after gofmt (thanks Eric Eisner). +* misc/gophertool: Chrome extension to aid in Go development +* misc/vim: limit Fmt command to Go buffers (thanks Yasuhiro Matsumoto). +* net: if we stop polling, remove any pending events for the socket, + update IP multicast socket options (thanks Mikio Hara). +* os: Fix test to work on Solaris, + fix Readdir(0) on EOF, + fix Readdir, Readdirnames (thanks Yuval Pavel Zholkover), + fix os.MkdirAll with backslash path separator (thanks Yasuhiro Matsumoto), + handle OpenFile flag parameter properly on Windows (thanks Alex Brainman). +* path/filepath: remove string constants. +* pkg: spelling tweaks, I-Z (thanks Robert Hencke). +* quietgcc: fix typo, respect $TMPDIR. +* runtime: do not garbage collect windows callbacks (thanks Alex Brainman), + fix mmap error return on linux (thanks Dmitry Chestnykh), + reset GOMAXPROCS during tests, + save cdecl registers in Windows SEH handler (thanks Alexey Borzenkov). +* spec: be precise with the use of the informal ellipsis and the Go token, + clarify rules for shifts. +* strconv: add QuoteRune; analogous to Quote but for runes rather than strings. +* strings: implement UnreadByte, UnreadRune. +* sync: always wake up sleeping goroutines on Cond.Signal (thanks Gustavo Niemeyer). +* sync/atomic: fix check64. +* syscall: add ProcAttr field to pass an unescaped command line on windows (thanks Vincent Vanackere), + add routing messages support for Linux and BSD (thanks Mikio Hara). +* template: fixes and clean-ups (thanks Gustavo Niemeyer). +* time: fix Format bug: midnight/noon are 12AM/PM not 0AM/PM. +* unicode: make the tables smaller. ++ +
+This release 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. +This value is now accessible via the new Request field on http.Response. +For example, this code: + + res, finalURL, err := http.Get(...) + +should be rewritten as: + + res, err := http.Get(...) + if err != nil { + // ... + } + finalURL := res.Request.URL.String() + +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 +between 2 and 5 times faster in typical use cases. + +Other changes: +* 5a, 6a, 8a, cc: remove old environment variables. +* 5c, 5g: fix build with too-smart gcc. +* 5l, 8l: add ELF symbol table to binary. +* 5l: delete pre-ARMv4 instruction implementations, other fixes. +* 6l, 8l: emit windows dwarf sections like other platforms (thanks Alex Brainman). +* 6l: fix emit windows dwarf sections (thanks Wei Guangjing). +* 8g: fix conversion from float to uint64 (thanks Anthony Martin). +* Make.cmd: create TARGDIR if necessary (thanks Gustavo Niemeyer). +* asn1: add big support. +* big: add Int methods to act on numbered bits (thanks Roger Peppe), + better support for string conversions, + support %v and # modifier, better handling of unknown formats. +* cgi: export RequestFromMap (thanks Evan Shaw), + set Request.TLS and Request.RemoteAddr for children. +* cgo: use packed struct to fix Windows behavior. +* codereview: add release branch support, + fetch metadata using JSON API, not XML scraping, + handle 'null as missing field' in rietveld json. +* compress/lzw: silently drop implied codes that are too large. +* compress/zlib: actually use provided dictionary in NewWriterDict +* crypto/openpgp: add key generation support, + change PublicKey.Serialize to include the header. +* crypto/rand: add utility functions for number generation (thanks Anthony Martin). +* crypto/tls: export the verified chains. +* crypto/x509/crl: add package. +* crypto/x509: export raw SubjectPublicKeyInfo, + support DSA public keys in X.509 certs, + support parsing and verifying DSA signatures (thanks Jonathan Allie). +* doc/roadmap: put "App Engine support" under "Done". +* doc: add I/O 2011 talks to talks/, docs.html, and front page. +* effective go: explain about values/pointers in String() example, + update to new Open signature. +* exp/draw: fast paths for drawing a YCbCr or an NRGBA onto an RGBA. +* filepath: make EvalSymlinks work on Windows (thanks Alex Brainman). +* flag: allow distinct sets of flags. +* gc: fix type switch error message for invalid cases (thanks Lorenzo Stoakes), + fix unsafe.Sizeof, + preserve original expression for errors. +* go/ast, go/doc, godoc: consider struct fields and interface methods when filtering ASTs. +* go/ast: consider anonymous fields and set Incomplete bit when filtering ASTs, + properly maintain map of package global imports. +* go/doc, godoc: when filtering for godoc, don't remove elements of a declaration. +* go/parser: accept parenthesized receive operations in select statements, + always introduce an ast.Object when declaring an identifier. +* go/printer, gofmt: fix alignment of "=" in const/var declarations, + fix formatting of expression lists (missing blank). +* go/printer: added simple performance benchmark, + make tests follow syntactic restrictions, + more accurate comment for incomplete structs/interfaces, +* go/token: faster FileSet.Position implementation. +* go/types: type checker API + testing infrastructure. +* godoc: added -index flag to enable/disable search index, + if there is no search box, don't run the respective JS code. +* gofmt: update test.sh (exclude a file w/ incorrect syntax). +* html: parse empty, unquoted, and single-quoted attribute values. +* http/cgi: correctly set request Content-Type (thanks Evan Shaw), + pass down environment variables for IRIX and Solaris. +* http/pprof: fix POST reading bug. +* http/spdy: new incomplete package (thanks Ross Light). +* http: Client.Do should follow redirects for GET and HEAD, + add Header.Write method (thanks Evan Shaw), + add Request.SetBasicAuth method, + add Transport.ProxySelector, + add http.SetCookie(ResponseWriter, *Cookie), + don't Clean query string in relative redirects, + fix FormFile nil pointer dereference on missing multipart form, + fix racy test with a simpler version, + fix two Transport gzip+persist crashes, + include Host header in requests, + make HEAD client request follow redirects (thanks Eivind Uggedal). + update cookie doc to reference new RFC 6265, + write cookies according to RFC 6265 (thanks Christian Himpel). +* image/bmp: implement a BMP decoder. +* image/gif: new package provides a GIF decoder. +* image/jpeg: decode grayscale images, not just color images. + optimizations and tweaks. +* image/png: encode paletted images with alpha channel (thanks Dmitry Chestnykh), + speed up opaque RGBA encoding. +* 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. +* 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. +* make.bash: remove old bash version of gotest on Windows (thanks Alex Brainman). +* make: add nuke target for C commands and libs (thanks Anthony Martin). +* mime/multipart: add FileName accessor on Part, + add Writer, + return an error on Reader EOF, not (nil, nil). +* misc/cgo/test: run tests. +* misc/emacs: use UTF-8 when invoking gofmt as a subprocess (thanks Sameer Ajmani). +* misc/vim: new Vim indentation script. +* net, http: add and make use of IP address scope identification API (thanks Mikio Hara). +* net: default to 127.0.0.1, not localhost, in TestICMP, + don't crash on unexpected DNS SRV responses, + enable SO_REUSEPORT on BSD variants (thanks Mikio Hara), + 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, + make Setenv update C environment variables. +* reflect: allow unexported key in Value.MapIndex. +* runtime, sync/atomic: fix arm cas. +* runtime: add newline to "finalizer already set" error (thanks Albert Strasheim), + handle out-of-threads on Linux gracefully (thanks Albert Strasheim), + fix function args not checked warning on ARM (thanks Dave Cheney), + make StackSystem part of StackGuard (thanks Alexey Borzenkov), + maybe fix Windows build broken by cgo setenv CL. +* spec: clarify semantics of integer division, + clarify semantics of range clause, + fix error in production syntax, + narrow syntax for expression and select statements, + newlines cannot be used inside a char or "" string literal, + restricted expressions may still be parenthesized. +* strings: make Reader.Read use copy instead of an explicit loop. +* syscall: add Windows file mapping functions and constants (thanks Evan Shaw), + add IPv6 scope zone ID support (thanks Mikio Hara), + add netlink support for linux/386, linux/amd64, linux/arm (thanks Mikio Hara), + add Sendfile, + adjust freebsd syscalls.master URL properly (thanks Mikio Hara), + change Overlapped.HEvent type, it is a handle (thanks Alex Brainman). +* syslog: fix skipping of net tests (thanks Gustavo Niemeyer). +* template: support string, int and float literals (thanks Gustavo Niemeyer). +* xml: fix reflect error. ++
This release includes revisions to the reflect package to make it more -efficient, after the last weekly’s major API update. If your code uses reflect +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 http://codereview.appspot.com/4435042 @@ -168,7 +501,7 @@ The os package's Open function has been replaced by three functions: Open(name) // same as old Open(name, O_RDONLY, 0) Create(name) // same as old Open(name, O_RDWR|O_TRUNC|O_CREAT, 0666) -To update your code to use the new APIs, run "gofix path/to/code". Gofix can’t +To update your code to use the new APIs, run "gofix path/to/code". Gofix can't handle all situations perfectly, so read and test the changes it makes before committing them. @@ -298,8 +631,8 @@ produce memory and CPU profiling data when invoked with the -test.memprofile and -test.cpuprofile flags. Run "godoc gotest" for details. We have also introduced a way for tests to run quickly when an exhaustive test -is unnecessary. Gotest’s new -test.short flag in combination with the testing -package’s new Short function allows you to write tests that can be run in +is unnecessary. Gotest's new -test.short flag in combination with the testing +package's new Short function allows you to write tests that can be run in normal or "short" mode; short mode is now used by all.bash to reduce installation time. The Makefiles know about the flag - you can just run "make testshort". diff --git a/doc/docs.html b/doc/docs.html index d4e78446f..9fd3dcebe 100644 --- a/doc/docs.html +++ b/doc/docs.html @@ -70,6 +70,12 @@ An introduction to Go for C++ programmers.Non-English Documentation
+Belarusian — Беларуская
+ +
A summary of the changes between Go releases.
+A document that specifies the conditions under which reads of a variable in @@ -128,6 +142,22 @@ same variable in a different goroutine.
+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 +and unveils the Go runtime for App Engine. +See the presentation slides. +
+ ++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 +and provides four examples of Go programs that solve real problems. +See the presentation slides. +
+A presentation delivered by Rob Pike and Russ Cox at Google I/O 2010. It diff --git a/doc/effective_go.html b/doc/effective_go.html index a7e6b7bdf..972772d33 100644 --- a/doc/effective_go.html +++ b/doc/effective_go.html @@ -297,9 +297,9 @@ determines just which package is being used.
Another convention is that the package name is the base name of
its source directory;
-the package in src/pkg/container/vector
-is imported as "container/vector"
but has name vector
,
-not container_vector
and not containerVector
.
+the package in src/pkg/encoding/base64
+is imported as "encoding/base64"
but has name base64
,
+not encoding_base64
and not encodingBase64
.
@@ -504,7 +504,7 @@ the body ends in break
, continue
,
-f, err := os.Open(name, os.O_RDONLY, 0) +f, err := os.Open(name) if err != nil { return err } @@ -520,7 +520,7 @@ statements, the resulting code needs noelse
statements.-f, err := os.Open(name, os.O_RDONLY, 0) +f, err := os.Open(name) if err != nil { return err } @@ -813,7 +813,7 @@ canonical examples are unlocking a mutex or closing a file.// Contents returns the file's contents as a string. func Contents(filename string) (string, os.Error) { - f, err := os.Open(filename, os.O_RDONLY, 0) + f, err := os.Open(filename) if err != nil { return "", err } @@ -935,13 +935,14 @@ example of its possibilities.-Data
-Allocation with
+new()
Allocation with
new
-Go has two allocation primitives,
new()
andmake()
. +Go has two allocation primitives, the built-in functions +new
andmake
. They do different things and apply to different types, which can be confusing, but the rules are simple. -Let's talk aboutnew()
first. +Let's talk aboutnew
first. It's a built-in function essentially the same as its namesakes in other languages:new(T)
allocates zeroed storage for a new item of typeT
and returns its address, a value of type*T
. @@ -950,9 +951,9 @@ In Go terminology, it returns a pointer to a newly allocated zero value of type-Since the memory returned by
new()
is zeroed, it's helpful to arrange that the +Since the memory returned bynew
is zeroed, it's helpful to arrange that the zeroed object can be used without further initialization. This means a user of -the data structure can create one withnew()
and get right to +the data structure can create one withnew
and get right to work. For example, the documentation forbytes.Buffer
states that "the zero value forBuffer
is an empty buffer ready to use." @@ -1065,7 +1066,7 @@ s := []string {Enone: "no error", Eio: "Eio", Einval: "invalid argument"} m := map[int]string{Enone: "no error", Eio: "Eio", Einval: "invalid argument"}Allocation with
+make()
Allocation with
make
Back to allocation. @@ -1099,8 +1100,8 @@ In contrast,
new([]int)
returns a pointer to a newly allocated, zer structure, that is, a pointer to anil
slice value.-These examples illustrate the difference between
new()
and -make()
. +These examples illustrate the difference betweennew
and +make
.@@ -1116,9 +1117,9 @@ v := make([]int, 100)-Remember that
make()
applies only to maps, slices and channels +Remember thatmake
applies only to maps, slices and channels and does not return a pointer. -To obtain an explicit pointer allocate withnew()
. +To obtain an explicit pointer allocate withnew
.Arrays
@@ -1473,7 +1474,7 @@ map[string] intIf you want to control the default format for a custom type, all that's required is to define -a method
String() string
on the type. +a method with the signatureString() string
on the type. For our simple typeT
, that might look like this.@@ -1489,7 +1490,13 @@ to print in the format 7/-2.35/"abc\tdef"-Our
+String()
method is able to callSprintf
because the +(If you need to print values of typeT
as well as pointers toT
, +the receiver forString
must be of value type; this example used a pointer because +that's more efficient and idiomatic for struct types. +See the section below on pointers vs. value receivers for more information.) ++Our
String
method is able to callSprintf
because the print routines are fully reentrant and can be used recursively. We can even go one step further and pass a print routine's arguments directly to another such routine. The signature ofPrintf
uses the type...interface{}
@@ -1677,19 +1684,20 @@ var (The init function
-Finally, each source file can define its own
init()
function to -set up whatever state is required. The only restriction is that, although +Finally, each source file can define its own niladicinit
function to +set up whatever state is required. (Actually each file can have multiple +init
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. -And finally means finally:init()
is called after all the +And finally means finally:init
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 initialized.Besides initializations that cannot be expressed as declarations, -a common use of
@@ -1893,7 +1901,7 @@ on every instance of a common method. In such cases, the constructor should return an interface value rather than the implementing type. As an example, in the hash libraries -bothinit()
functions is to verify or repair +a common use ofinit
functions is to verify or repair correctness of the program state before real execution begins.crc32.NewIEEE()
andadler32.New()
+bothcrc32.NewIEEE
andadler32.New
return the interface typehash.Hash32
. Substituting the CRC-32 algorithm for Adler-32 in a Go program requires only changing the constructor call; @@ -2675,7 +2683,7 @@ field for recoverable failures.for try := 0; try < 2; try++ { - file, err = os.Open(filename, os.O_RDONLY, 0) + file, err = os.Open(filename) if err == nil { return } diff --git a/doc/frontpage.css b/doc/frontpage.css index bcdca6401..299855ce9 100644 --- a/doc/frontpage.css +++ b/doc/frontpage.css @@ -80,6 +80,9 @@ span.keyword { #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; diff --git a/doc/go_faq.html b/doc/go_faq.html index 5f92b0528..560ab3617 100644 --- a/doc/go_faq.html +++ b/doc/go_faq.html @@ -26,6 +26,7 @@ are not well supported by popular systems languages.
We believe it's worth trying again with a new language, a concurrent, @@ -49,12 +50,14 @@ concurrent execution and communication. By its design, Go proposes an approach for the construction of system software on multicore machines. +
“Ogle” would be a good name for a Go debugger. +
6
is the architecture letter for amd64 (or x86-64, if you prefer), while
g
stands for Go.
+
@@ -117,6 +120,7 @@ language. Programmers who could were choosing ease over safety and efficiency by moving to dynamically typed languages such as Python and JavaScript rather than C++ or, to a lesser extent, Java.
+Go is an attempt to combine the ease of programming of an interpreted, dynamically typed @@ -131,7 +135,6 @@ and so on. These cannot be addressed well by libraries or tools; a new language was called for.
-@@ -147,7 +150,6 @@ about what programmers do and how to make programming, at least the kind of programming we do, more effective, which means more fun.
-@@ -179,26 +181,17 @@ interfaces represent abstraction; and so on. Orthogonality makes it easier to understand what happens when things combine.
--Go is an experiment. We hope adventurous users will give it a try and see -if they enjoy it. Not every programmer -will, but we hope enough will find satisfaction in the approach it -offers to justify further development. -
Yes. There are now several Go programs deployed in +
+Yes. There are now several Go programs deployed in
production inside Google. For instance, the server behind
http://golang.org is a Go program;
in fact it's just the godoc
document server running in a production configuration.
-
+
Gccgo
is a GCC front-end that can, with care, be linked with
GCC-compiled C or C++ programs.
+
The cgo program provides the mechanism for a “foreign function interface” to allow safe calling of C libraries from Go code. SWIG extends this capability to C++ libraries. +
+If it bothers you that Go is missing feature X, please forgive us and investigate the features that Go does have. You might find that they compensate in interesting ways for the lack of X. +
Generics are convenient but they come at a cost in complexity in the type system and run-time. We haven't yet found a @@ -298,6 +298,7 @@ plus the ability to use the empty interface to construct containers (with explicit unboxing) mean in many cases it is possible to write code that does what generics would enable, if less smoothly.
+This remains an open issue.
@@ -311,6 +312,7 @@ convoluted code. It also tends to encourage programmers to label too many ordinary errors, such as failing to open a file, as exceptional. +Go takes a different approach. Instead of exceptions, it has a couple of built-in functions to signal and recover from truly exceptional @@ -319,11 +321,11 @@ function's state being torn down after an error, which is sufficient to handle catastrophe but requires no extra control structures and, when used well, can result in clean error-handling code.
+See the Defer, Panic, and Recover article for details.
-
The same arguments apply to the use of assert()
in test programs. Proper
@@ -348,17 +351,20 @@ 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.
+
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. +
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. +
One of the most successful models for providing high-level linguistic support for concurrency comes from Hoare's Communicating Sequential Processes, or CSP. @@ -392,6 +399,7 @@ The result, which we call goroutines, can be very cheap: unless they spend a lot in long-running system calls, they cost little more than the memory for the stack.
+To make the stacks small, Go's run-time uses segmented stacks. A newly minted goroutine is given a few kilobytes, which is almost always enough. @@ -420,7 +428,6 @@ as when hosting an untrusted program, the implementation could interlock map access.
-Also, the lack of type hierarchy makes “objects” in Go feel much more lightweight than in languages such as C++ or Java. +
The only way to have dynamically dispatched methods is through an interface. Methods on structs or other types are always resolved statically. +
Rather than requiring the programmer to declare ahead of time that two types are related, in Go a type automatically satisfies any interface @@ -469,6 +480,7 @@ or for testing—without annotating the original types. Because there are no explicit relationships between types and interfaces, there is no type hierarchy to manage or discuss.
+
It's possible to use these ideas to construct something analogous to
type-safe Unix pipes. For instance, see how fmt.Fprintf
@@ -479,6 +491,7 @@ stream ciphers. All these ideas stem from a single interface
(io.Writer
) representing a single method
(Write
). And that's only scratching the surface.
It takes some getting used to but this implicit style of type dependency is one of the most exciting things about Go. @@ -503,6 +516,7 @@ but that it could also be confusing and fragile in practice. Matching only by n and requiring consistency in the types was a major simplifying decision in Go's type system.
+Regarding operator overloading, it seems more a convenience than an absolute requirement. Again, things are simpler without it. @@ -574,6 +588,23 @@ the interface idea. Sometimes, though, they're necessary to resolve ambiguities among similar interfaces.
+
+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 int
to a slice of
+interface{}
:
+
+t := []int{1, 2, 3, 4} +s := make([]interface{}, len(t)) +for i, v := range t { + s[i] = v +} +
A related detail is that, unlike in C, int
and int64
are distinct types even if int
is a 64-bit type. The int
@@ -610,7 +642,6 @@ If a specific application can benefit from a custom implementation, it's possibl
to write one but it will not be as convenient syntactically; this seems a reasonable tradeoff.
@@ -637,7 +668,6 @@ language but they have a large effect on usability: Go became a more productive, comfortable language when they were introduced.
-godoc
implements the full site at
http://golang.org/.
+
gofmt
is a pretty-printer
whose purpose is to enforce layout rules; it replaces the usual
compendium of do's and don'ts that allows interpretation.
All the Go code in the repository has been run through gofmt
.
+
The library sources are in go/src/pkg
.
If you want to make a significant change, please discuss on the mailing list before embarking.
+
See the document Contributing to the Go project for more information about how to proceed. - +
The storage location does have an effect on writing efficient programs. @@ -759,11 +793,13 @@ 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. +
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. +
GOMAXPROCS
should be set on a per-application basis.
-
Gc
is written in C using
Although it's a new program, it fits in the Plan 9 C compiler suite
(http://plan9.bell-labs.com/sys/doc/compiler.html)
and uses a variant of the Plan 9 loader to generate ELF binaries.
+
We considered writing 6g
, the original Go compiler, in Go itself but
@@ -1003,10 +1039,12 @@ set up a Go environment. Gccgo
, which came later, makes it possible
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 /pkg/go
.)
+
We also considered using LLVM for 6g
but we felt it was too large and
slow to meet our performance goals.
+
gccgo
.
+
5l
, 6l
, and 8l
) only
generate statically linked binaries. 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.
+
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. +
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 @@ -1195,6 +1236,7 @@ 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.)
+Another point is that a large part of the difficulty of concurrent and multi-threaded programming is memory management; @@ -1205,8 +1247,8 @@ Of course, implementing garbage collection in a concurrent environment is itself a challenge, but meeting it once rather than in every program helps everyone.
+Finally, concurrency aside, garbage collection makes interfaces simpler because they don't need to specify how memory is managed across them.
- diff --git a/doc/go_mem.html b/doc/go_mem.html index da45a07d7..906b858e8 100644 --- a/doc/go_mem.html +++ b/doc/go_mem.html @@ -1,5 +1,14 @@ + +
@@ -213,6 +222,17 @@ the corresponding receive on c
completes, which happens before
the print
.
+The closing of a channel happens before a receive that returns a zero value +because the channel is closed. +
+ +
+In the previous example, replacing
+c <- 0
with close(c)
+yields a program with the same guaranteed behavior.
+
A receive from an unbuffered channel happens before the send on that channel completes. diff --git a/doc/go_spec.html b/doc/go_spec.html index 886f89d12..abf5b8f50 100644 --- a/doc/go_spec.html +++ b/doc/go_spec.html @@ -1,5 +1,5 @@ - + +-->
-[]T{x1, x2, ... xn} +[]T{x1, x2, … xn}
@@ -2104,7 +2110,7 @@ and is a shortcut for a slice operation applied to an array literal:
-[n]T{x1, x2, ... xn}[0 : n] +[n]T{x1, x2, … xn}[0 : n]
@@ -2130,8 +2136,8 @@ parentheses.
-if x == (T{a,b,c}[i]) { ... } -if (x == T{a,b,c}[i]) { ... } +if x == (T{a,b,c}[i]) { … } +if (x == T{a,b,c}[i]) { … }
@@ -2335,11 +2341,11 @@ p.M0 // ((*p).T0).M0 - +-->
a
of type S
where S
is a run-time panic occursM
is a map type:
x
,
a[x]
is the map value with key x
and the type of a[x]
is the value type of M
nil
or does not contain such an entry,
a[x]
is the zero value
for the value type of M
-Similarly, if an assignment to a map has the special form +Similarly, if an assignment to a map element has the special form
@@ -2439,6 +2445,11 @@ the entry for key@@ -3557,17 +3592,13 @@ begins. Communication blocks until the send can proceed, at which point the value is transmitted on the channel. 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 ax
is deleted from the map; if a regular assignment to an element of the map. ++Assigning to an element of a
+nil
map causes a +run-time panic. +Slices
@@ -2559,11 +2570,11 @@ Given an expressionf
of function type-f(a1, a2, ... an) +f(a1, a2, … an)-calls
f
with argumentsa1, a2, ... an
. +callsf
with argumentsa1, a2, … an
. Except for one special case, arguments must be single-valued expressions assignable to the parameter types ofF
and are evaluated before the function is called. @@ -2642,7 +2653,7 @@ arguments bound to the final parameter and may differ for each call site. Given the function and call-func Greeting(prefix string, who ... string) +func Greeting(prefix string, who ...string) Greeting("hello:", "Joe", "Anna", "Eileen")@@ -2693,42 +2704,39 @@ unary_op = "+" | "-" | "!" | "^" | "*" | "&" | "<-" .Comparisons are discussed elsewhere. For other binary operators, the operand types must be identical -unless the operation involves channels, shifts, or untyped constants. +unless the operation involves shifts or untyped constants. For operations involving constants only, see the section on constant expressions.
-In a channel send, the first operand is always a channel and the second -must be a value assignable -to the channel's element type. -
- --Except for shift operations, -if one operand is an untyped constant +Except for shift operations, if one operand is an untyped constant and the other operand is not, the constant is converted to the type of the other operand.
-The right operand in a shift operation must have unsigned integer type +The right operand in a shift expression must have unsigned integer type or be an untyped constant that can be converted to unsigned integer type. -
- --If the left operand of a non-constant shift operation is an untyped constant, -the type of constant is what it would be if the shift operation were replaced by -the left operand alone. +If the left operand of a non-constant shift expression is an untyped constant, +the type of the constant is what it would be if the shift expression were +replaced by its left operand alone; the type is
int
if it cannot +be determined from the context (for instance, if the shift expression is an +operand in a comparison against an untyped constant).var s uint = 33 -var i = 1<<s // 1 has type int -var j = int32(1<<s) // 1 has type int32; j == 0 -var u = uint64(1<<s) // 1 has type uint64; u == 1<<33 -var f = float32(1<<s) // illegal: 1 has type float32, cannot shift -var g = float32(1<<33) // legal; 1<<33 is a constant shift operation; g == 1<<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 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 expressionOperator precedence
@@ -2808,15 +2816,18 @@ s += " and good bye" String addition creates a new string by concatenating the operands.-For integer values,
/
and%
satisfy the following relationship: +For two integer valuesx
andy
, the integer quotient +q = x / y
and remainderr = x % y
satisfy the following +relationships:-(a / b) * b + a % b == a +x = q*y + r and |r| < |y|-with
(a / b)
truncated towards zero. +withx / y
truncated towards zero +("truncated division").@@ -2827,6 +2838,20 @@ with+(a / b)
truncated towards zero. -5 -3 1 -2+As an exception to this rule, if the dividend
+ +x
is the most +negative value for the int type ofx
, the quotient +q = x / -1
is equal tox
(andr = 0
). ++ x, q +int8 -128 +int16 -32768 +int32 -2147483648 +int64 -9223372036854775808 ++If the divisor is zero, a run-time panic occurs. If the dividend is positive and the divisor is a constant power of 2, @@ -2843,8 +2868,8 @@ be replaced by a bitwise "and" operation:
The shift operators shift the left operand by the shift count specified by the right operand. They implement arithmetic shifts if the left operand is a signed -integer and logical shifts if it is an unsigned integer. The shift count must -be an unsigned integer. There is no upper limit on the shift count. Shifts behave +integer and logical shifts if it is an unsigned integer. +There is no upper limit on the shift count. Shifts behave as if the left operand is shifted
n
times by 1 for a shift count ofn
. As a result,x << 1
is the same asx*2
@@ -3025,6 +3050,7 @@ For an operandch
of channel type, the value of the receive operation<-ch
is the value received from the channelch
. The type of the value is the element type of the channel. The expression blocks until a value is available. +Receiving from anil
channel blocks forever.@@ -3052,17 +3078,12 @@ or is a zero value returned because the channel is closed and empty (- +-->false
). --Receiving from a
- - +-->nil
channel causes a -run-time panic. -Method expressions
@@ -3360,21 +3381,35 @@ 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/
and%
). -Similarly, -untyped integer or floating-point constants may be used as operands +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.-Applying an operator to untyped constants results in an untyped +A constant comparison always yields +a constant of type
+bool
. If the left operand of a constant +shift expression 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 +(§Arithmetic operators). +Applying all other operators to untyped constants results in an untyped constant of the same kind (that is, a boolean, integer, floating-point, -complex, or string constant), except for -comparison operators, which result in -a constant of typebool
. +complex, or string constant).+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 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) ++Imaginary literals are untyped complex constants (with zero real part) and may be combined in binary @@ -3431,7 +3466,7 @@ int8(^1) // same as int8(-2) ^int8(1) // same as -1 ^ int8(1) = -2
Order of evaluation
@@ -3522,10 +3557,9 @@ Error: log.Panic("error encountered")Function calls, method calls, and receive operations -can appear in statement context. +can appear in statement context. Such statements may be parenthesized.
-ExpressionStmt = Expression .@@ -3534,6 +3568,7 @@ ExpressionStmt = Expression . h(x+y) f.Close() <-ch +(<-ch)
nil
channel blocks forever.
ch <- 3-
-Sending to a nil
channel causes a
-run-time panic.
-
Each left-hand side operand must be addressable, -a map index expression, -or the blank identifier. +a map index expression, or the blank identifier. +Operands may be parenthesized.
x = 1 *p = f() a[i] = 23 -k = <-ch +(k) = <-ch // same as: k = <-ch
@@ -3966,10 +3997,14 @@ As with an assignment, the operands on the left must be addressable or map index expressions; they denote the iteration variables. If the range expression is a channel, only one iteration variable is permitted, otherwise there may be one or two. +If the second iteration variable is the blank identifier, +the range clause is equivalent to the same clause with only the first variable present.
-The range expression is evaluated once before beginning the loop. +The range expression is evaluated once before beginning the loop +except if the expression is an array, in which case, depending on +the expression, it might not be evaluated (see below). Function calls on the left are evaluated once per iteration. For each iteration, iteration values are produced as follows:
@@ -3985,8 +4020,11 @@ channel c chan E element e Ea
, the index iteration
+values are produced in increasing order, starting at element index 0. As a special
+case, if only the first iteration variable is present, the range loop produces
+iteration values from 0 up to len(a)
and does not index into the array
+or slice itself. For a nil
slice, the number of iterations is 0.
nil
, the number of iterations is 0.
close
).
+the channel until the channel is closed. If the channel
+is nil
, the range expression blocks forever.
+var testdata *struct { + a *[7]int +} +for i, _ := range testdata.a { + // testdata.a is never evaluated; len(testdata.a) is constant + // i ranges from 0 to 6 + f(i) +} + var a [10]string m := map[string]int{"mon":0, "tue":1, "wed":2, "thu":3, "fri":4, "sat":5, "sun":6} - for i, s := range a { // type of i is int // type of s is string @@ -4047,6 +4094,11 @@ for key, val = range m { } // key == last map key encountered in iteration // val == map[key] + +var ch chan Work = producer() +for w := range ch { + doWork(w) +}@@ -4131,7 +4183,7 @@ case i1 = <-c1: print("received ", i1, " from c1\n") case c2 <- i2: print("sent ", i2, " to c2\n") -case i3, ok := <-c3: +case i3, ok := (<-c3): // same as: i3, ok := <-c3 if ok { print("received ", i3, " from c3\n") } else { @@ -4229,7 +4281,7 @@ func (devnull) Write(p []byte) (n int, _ os.Error) { Regardless of how they are declared, all the result values are initialized to the zero values for their type (§The zero value) upon entry to the function. - +-->
is erroneous because the jump to label L
skips
the creation of v
.
-
+-->
int
-Call Argument type Result
+Call Argument type Result
-len(s) string type string length in bytes
- [n]T, *[n]T array length (== n)
- []T slice length
- map[K]T map length (number of defined keys)
- chan T number of elements queued in channel buffer
+len(s) string type string length in bytes
+ [n]T, *[n]T array length (== n)
+ []T slice length
+ map[K]T map length (number of defined keys)
+ chan T number of elements queued in channel buffer
-cap(s) [n]T, *[n]T array length (== n)
- []T slice capacity
- chan T channel buffer capacity
+cap(s) [n]T, *[n]T array length (== n)
+ []T slice capacity
+ chan T channel buffer capacity
@@ -4449,20 +4501,17 @@ The length and capacity of a nil
slice, map, or channel are 0.
-The expression
-len(s)
is a
-constant if s
is a string constant.
-The expressions
-len(s)
and
-cap(s)
are
-constants if s
is an (optionally parenthesized)
-identifier or
-qualified identifier
-denoting an array or pointer to array.
-Otherwise invocations of len
and cap
are not
-constant.
+The expression len(s)
is constant if
+s
is a string constant. The expressions len(s)
and
+cap(s)
are constants if the type of s
is an array
+or pointer to an array and the expression s
does not contain
+channel receives or
+function calls; in this case s
is not evaluated.
+Otherwise, invocations of len
and cap
are not
+constant and s
is evaluated.
+
Allocation
@@ -4575,7 +4624,7 @@ a source src
to a destination dst
and returns the
number of elements copied. Source and destination may overlap.
Both arguments must have identical element type T
and must be
assignable to a slice of type []T
.
-The number of arguments copied is the minimum of
+The number of elements copied is the minimum of
len(src)
and len(dst)
.
As a special case, copy
also accepts a destination argument assignable
to type []byte
with a source argument of a string type.
@@ -4850,7 +4899,7 @@ package main
import "fmt"
-// Send the sequence 2, 3, 4, ... to channel 'ch'.
+// 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'.
@@ -4890,7 +4939,7 @@ func main() {
The zero value
When memory is allocated to store a value, either through a declaration
-or make()
or new()
call,
+or a call of make
or new
,
and no explicit initialization is provided, the memory is
given a default initialization. Each element of such a value is
set to the zero value for its type: false
for booleans,
@@ -4948,7 +4997,7 @@ func init()
defined in its source.
A package may contain multiple
-init()
functions, even
+init
functions, even
within a single source file; they execute
in unspecified order.
@@ -4978,8 +5027,8 @@ program is complete. Therefore, all initialization code is run in a single
goroutine.
-An init()
function cannot be referred to from anywhere
-in a program. In particular, init()
cannot be called explicitly,
+An init
function cannot be referred to from anywhere
+in a program. In particular, init
cannot be called explicitly,
nor can a pointer to init
be assigned to a function variable.
@@ -5001,7 +5050,7 @@ arguments and returns no value.
-func main() { ... }
+func main() { … }
@@ -5151,5 +5200,8 @@ The following minimal alignment properties are guaranteed:
Implementation differences - TODO
- - Implementation does not honor the restriction on goto statements and targets (no intervening declarations).
+ - The restriction on
goto
statements and targets (no intervening declarations) is not honored.
+ len(a)
is only a constant if a
is a (qualified) identifier denoting an array or pointer to an array.
+ nil
maps are not treated like empty maps.
+ - Trying to send/receive from a
nil
channel causes a run-time panic.
diff --git a/doc/go_tutorial.html b/doc/go_tutorial.html
index 4470f2748..aa85134b3 100644
--- a/doc/go_tutorial.html
+++ b/doc/go_tutorial.html
@@ -28,9 +28,9 @@ Let's start in the usual way:
05 package main
-
+
07 import fmt "fmt" // Package implementing formatted I/O.
-
+
09 func main() {
10 fmt.Printf("Hello, world; or Καλημέρα κόσμε; or こんにちは 世界\n")
11 }
@@ -118,19 +118,19 @@ Next up, here's a version of the Unix utility echo(1)
:
05 package main
-
+
07 import (
08 "os"
09 "flag" // command line option parser
10 )
-
+
12 var omitNewline = flag.Bool("n", false, "don't print final newline")
-
+
14 const (
15 Space = " "
16 Newline = "\n"
17 )
-
+
19 func main() {
20 flag.Parse() // Scans the arg list and sets up flags
21 var s string = ""
@@ -340,7 +340,7 @@ Using slices one can write this function (from sum.go
):
15 }
-Note how the return type (int
) is defined for sum()
by stating it
+Note how the return type (int
) is defined for sum
by stating it
after the parameter list.
To call the function, we slice the array. This intricate call (we'll show
@@ -372,7 +372,7 @@ There are also maps, which you can initialize like this:
m := map[string]int{"one":1 , "two":2}
-The built-in function len()
, which returns number of elements,
+The built-in function len
, which returns number of elements,
makes its first appearance in sum
. It works on strings, arrays,
slices, maps, and channels.
@@ -400,7 +400,7 @@ for more examples of its use.
Most types in Go are values. If you have an int
or a struct
or an array, assignment
copies the contents of the object.
-To allocate a new variable, use new()
, which
+To allocate a new variable, use the built-in function new
, which
returns a pointer to the allocated storage.
@@ -417,7 +417,7 @@ or the more idiomatic
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 make()
:
+types you want to use the built-in function make
:
m := make(map[string]int)
@@ -431,11 +431,11 @@ If you just declare the map, as in
it creates a nil
reference that cannot hold anything. To use the map,
-you must first initialize the reference using make()
or by assignment from an
+you must first initialize the reference using make
or by assignment from an
existing map.
Note that new(T)
returns type *T
while make(T)
returns type
-T
. If you (mistakenly) allocate a reference object with new()
,
+T
. If you (mistakenly) allocate a reference object with new
rather than make
,
you receive a pointer to a nil reference, equivalent to
declaring an uninitialized variable and taking its address.
@@ -478,12 +478,12 @@ open/close/read/write interface. Here's the start of file.go
:
05 package file
-
+
07 import (
08 "os"
09 "syscall"
10 )
-
+
12 type File struct {
13 fd int // file descriptor number
14 name string // file name at Open time
@@ -600,7 +600,7 @@ the tricky standard arguments to open and, especially, to create a file:
41 O_CREATE = syscall.O_CREAT
42 O_TRUNC = syscall.O_TRUNC
43 )
-
+
45 func Open(name string) (file *File, err os.Error) {
46 return OpenFile(name, O_RDONLY, 0)
47 }
@@ -631,7 +631,7 @@ each of which declares a receiver variable file
.
61 }
62 return nil
63 }
-
+
65 func (file *File) Read(b []byte) (ret int, err os.Error) {
66 if file == nil {
67 return -1, os.EINVAL
@@ -642,7 +642,7 @@ each of which declares a receiver variable file
.
72 }
73 return int(r), err
74 }
-
+
76 func (file *File) Write(b []byte) (ret int, err os.Error) {
77 if file == nil {
78 return -1, os.EINVAL
@@ -653,7 +653,7 @@ each of which declares a receiver variable file
.
83 }
84 return int(r), err
85 }
-
+
87 func (file *File) String() string {
88 return file.name
89 }
@@ -676,13 +676,13 @@ We can now use our new package:
05 package main
-
+
07 import (
08 "./file"
09 "fmt"
10 "os"
11 )
-
+
13 func main() {
14 hello := []byte("hello, world\n")
15 file.Stdout.Write(hello)
@@ -719,14 +719,14 @@ Building on the file
package, here's a simple version of the Unix u
05 package main
-
+
07 import (
08 "./file"
09 "flag"
10 "fmt"
11 "os"
12 )
-
+
14 func cat(f *file.File) {
15 const NBUF = 512
16 var buf [NBUF]byte
@@ -745,7 +745,7 @@ Building on the file
package, here's a simple version of the Unix u
29 }
30 }
31 }
-
+
33 func main() {
34 flag.Parse() // Scans the arg list and sets up flags
35 if flag.NArg() == 0 {
@@ -766,7 +766,7 @@ Building on the file
package, here's a simple version of the Unix u
By now this should be easy to follow, but the switch
statement introduces some
new features. Like a for
loop, an if
or switch
can include an
initialization statement. The switch
on line 18 uses one to create variables
-nr
and er
to hold the return values from f.Read()
. (The if
on line 25
+nr
and er
to hold the return values from the call to f.Read
. (The if
on line 25
has the same idea.) The switch
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
@@ -778,14 +778,14 @@ in a for
statement, a missing value means true
. In fa
is a form of if-else
chain. While we're here, it should be mentioned that in
switch
statements each case
has an implicit break
.
-Line 25 calls Write()
by slicing the incoming buffer, which is itself a slice.
+Line 25 calls Write
by slicing the incoming buffer, which is itself a slice.
Slices provide the standard Go way to handle I/O buffers.
Now let's make a variant of cat
that optionally does rot13
on its input.
It's easy to do by just processing the bytes, but instead we will exploit
Go's notion of an interface.
-The cat()
subroutine uses only two methods of f
: Read()
and String()
,
+The cat
subroutine uses only two methods of f
: Read
and String
,
so let's start by defining an interface that has exactly those two methods.
Here is code from progs/cat_rot13.go
:
@@ -810,11 +810,11 @@ we have a second implementation of the reader
interface.
31 type rotate13 struct {
32 source reader
33 }
-
+
35 func newRotate13(source reader) *rotate13 {
36 return &rotate13{source}
37 }
-
+
39 func (r13 *rotate13) Read(b []byte) (ret int, err os.Error) {
40 r, e := r13.source.Read(b)
41 for i := 0; i < r; i++ {
@@ -822,7 +822,7 @@ we have a second implementation of the reader
interface.
43 }
44 return r, e
45 }
-
+
47 func (r13 *rotate13) String() string {
48 return r13.source.String()
49 }
@@ -837,13 +837,13 @@ To use the new feature, we define a flag:
14 var rot13Flag = flag.Bool("rot13", false, "rot13 the input")
-and use it from within a mostly unchanged cat()
function:
+and use it from within a mostly unchanged cat
function:
52 func cat(r reader) {
53 const NBUF = 512
54 var buf [NBUF]byte
-
+
56 if *rot13Flag {
57 r = newRotate13(r)
58 }
@@ -865,7 +865,7 @@ and use it from within a mostly unchanged cat()
function:
74 }
-(We could also do the wrapping in main
and leave cat()
mostly alone, except
+(We could also do the wrapping in main
and leave cat
mostly alone, except
for changing the type of the argument; consider that an exercise.)
Lines 56 through 58 set it all up: If the rot13
flag is true, wrap the reader
we received into a rotate13
and proceed. Note that the interface variables
@@ -936,7 +936,7 @@ arrays of integers, strings, etc.; here's the code for arrays of int
33 type IntArray []int
-
+
35 func (p IntArray) Len() int { return len(p) }
36 func (p IntArray) Less(i, j int) bool { return p[i] < p[j] }
37 func (p IntArray) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
@@ -969,11 +969,11 @@ to implement the three methods for that type, like this:
32 shortName string
33 longName string
34 }
-
+
36 type dayArray struct {
37 data []*day
38 }
-
+
40 func (p *dayArray) Len() int { return len(p.data) }
41 func (p *dayArray) Less(i, j int) bool { return p.data[i].num < p.data[j].num }
42 func (p *dayArray) Swap(i, j int) { p.data[i], p.data[j] = p.data[j], p.data[i] }
@@ -1054,7 +1054,7 @@ to that of the Printf
call above.
If you have your own type you'd like Printf
or Print
to format,
-just give it a String()
method that returns a string. The print
+just give it a String
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.
@@ -1064,25 +1064,25 @@ Here's a simple example.
10 a int
11 b string
12 }
-
+
14 func (t *testType) String() string {
15 return fmt.Sprint(t.a) + " " + t.b
16 }
-
+
18 func main() {
19 t := &testType{77, "Sunset Strip"}
20 fmt.Println(t)
21 }
-Since *testType
has a String()
method, the
+Since *testType
has a String
method, the
default formatter for that type will use it and produce the output
77 Sunset Strip
-Observe that the String()
method calls Sprint
(the obvious Go
+Observe that the String
method calls Sprint
(the obvious Go
variant that returns a string) to do its formatting; special formatters
can use the fmt
library recursively.
@@ -1095,7 +1095,7 @@ and such, but that's getting a little off the main thread so we'll leave it
as an exploration exercise.
You might ask, though, how Printf
can tell whether a type implements
-the String()
method. Actually what it does is ask if the value can
+the String
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 v
, it does this:
@@ -1140,7 +1140,7 @@ interface type defined in the io
library:
(This interface is another conventional name, this time for Write
; there are also
io.Reader
, io.ReadWriter
, and so on.)
-Thus you can call Fprintf
on any type that implements a standard Write()
+Thus you can call Fprintf
on any type that implements a standard Write
method, not just files but also network channels, buffers, whatever
you want.
@@ -1346,7 +1346,7 @@ code that invokes the operation and responds to the request:
14 type binOp func(a, b int) int
-
+
16 func run(op binOp, req *request) {
17 reply := op(req.a, req.b)
18 req.replyc <- reply
diff --git a/doc/go_tutorial.txt b/doc/go_tutorial.txt
index 3e0b21d99..513190ef2 100644
--- a/doc/go_tutorial.txt
+++ b/doc/go_tutorial.txt
@@ -271,7 +271,7 @@ Using slices one can write this function (from "sum.go"):
--PROG progs/sum.go /sum/ /^}/
-Note how the return type ("int") is defined for "sum()" by stating it
+Note how the return type ("int") is defined for "sum" by stating it
after the parameter list.
To call the function, we slice the array. This intricate call (we'll show
@@ -295,7 +295,7 @@ There are also maps, which you can initialize like this:
m := map[string]int{"one":1 , "two":2}
-The built-in function "len()", which returns number of elements,
+The built-in function "len", which returns number of elements,
makes its first appearance in "sum". It works on strings, arrays,
slices, maps, and channels.
@@ -320,7 +320,7 @@ An Interlude about Allocation
Most types in Go are values. If you have an "int" or a "struct"
or an array, assignment
copies the contents of the object.
-To allocate a new variable, use "new()", which
+To allocate a new variable, use the built-in function "new", which
returns a pointer to the allocated storage.
type T struct { a, b int }
@@ -333,7 +333,7 @@ or the more idiomatic
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 "make()":
+types you want to use the built-in function "make":
m := make(map[string]int)
@@ -343,11 +343,11 @@ If you just declare the map, as in
var m map[string]int
it creates a "nil" reference that cannot hold anything. To use the map,
-you must first initialize the reference using "make()" or by assignment from an
+you must first initialize the reference using "make" or by assignment from an
existing map.
Note that "new(T)" returns type "*T" while "make(T)" returns type
-"T". If you (mistakenly) allocate a reference object with "new()",
+"T". If you (mistakenly) allocate a reference object with "new" rather than "make",
you receive a pointer to a nil reference, equivalent to
declaring an uninitialized variable and taking its address.
@@ -525,7 +525,7 @@ Building on the "file" package, here's a simple version of the Unix utility "cat
By now this should be easy to follow, but the "switch" statement introduces some
new features. Like a "for" loop, an "if" or "switch" can include an
initialization statement. The "switch" on line 18 uses one to create variables
-"nr" and "er" to hold the return values from "f.Read()". (The "if" on line 25
+"nr" and "er" to hold the return values from the call to "f.Read". (The "if" on line 25
has the same idea.) The "switch" 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
@@ -537,14 +537,14 @@ in a "for" statement, a missing value means "true". In fact, such a "switch"
is a form of "if-else" chain. While we're here, it should be mentioned that in
"switch" statements each "case" has an implicit "break".
-Line 25 calls "Write()" by slicing the incoming buffer, which is itself a slice.
+Line 25 calls "Write" by slicing the incoming buffer, which is itself a slice.
Slices provide the standard Go way to handle I/O buffers.
Now let's make a variant of "cat" that optionally does "rot13" on its input.
It's easy to do by just processing the bytes, but instead we will exploit
Go's notion of an interface.
-The "cat()" subroutine uses only two methods of "f": "Read()" and "String()",
+The "cat" subroutine uses only two methods of "f": "Read" and "String",
so let's start by defining an interface that has exactly those two methods.
Here is code from "progs/cat_rot13.go":
@@ -568,11 +568,11 @@ To use the new feature, we define a flag:
--PROG progs/cat_rot13.go /rot13Flag/
-and use it from within a mostly unchanged "cat()" function:
+and use it from within a mostly unchanged "cat" function:
--PROG progs/cat_rot13.go /func.cat/ /^}/
-(We could also do the wrapping in "main" and leave "cat()" mostly alone, except
+(We could also do the wrapping in "main" and leave "cat" mostly alone, except
for changing the type of the argument; consider that an exercise.)
Lines 56 through 58 set it all up: If the "rot13" flag is true, wrap the "reader"
we received into a "rotate13" and proceed. Note that the interface variables
@@ -700,19 +700,19 @@ to that of the "Printf" call above.
--PROG progs/print.go 'NR==21' 'NR==22'
If you have your own type you'd like "Printf" or "Print" to format,
-just give it a "String()" method that returns a string. The print
+just give it a "String" 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.
--PROG progs/print_string.go 'NR==9' END
-Since "*testType" has a "String()" method, the
+Since "*testType" has a "String" method, the
default formatter for that type will use it and produce the output
77 Sunset Strip
-Observe that the "String()" method calls "Sprint" (the obvious Go
+Observe that the "String" method calls "Sprint" (the obvious Go
variant that returns a string) to do its formatting; special formatters
can use the "fmt" library recursively.
@@ -725,7 +725,7 @@ and such, but that's getting a little off the main thread so we'll leave it
as an exploration exercise.
You might ask, though, how "Printf" can tell whether a type implements
-the "String()" method. Actually what it does is ask if the value can
+the "String" 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 "v", it does this:
@@ -764,7 +764,7 @@ interface type defined in the "io" library:
(This interface is another conventional name, this time for "Write"; there are also
"io.Reader", "io.ReadWriter", and so on.)
-Thus you can call "Fprintf" on any type that implements a standard "Write()"
+Thus you can call "Fprintf" on any type that implements a standard "Write"
method, not just files but also network channels, buffers, whatever
you want.
diff --git a/doc/godocs.js b/doc/godocs.js
index 2b3ab065f..946c4c39f 100644
--- a/doc/godocs.js
+++ b/doc/godocs.js
@@ -28,6 +28,10 @@ function godocs_onload() {
function godocs_bindSearchEvents() {
var search = document.getElementById('search');
+ if (!search) {
+ // no search box (index disabled)
+ return;
+ }
function clearInactive() {
if (search.className == "inactive") {
search.value = "";
@@ -100,7 +104,7 @@ function godocs_generateTOC() {
}
}
- if (!toc_items.length) { return; }
+ if (toc_items.length <= 1) { return; }
var dl1 = document.createElement('dl');
var dl2 = document.createElement('dl');
diff --git a/doc/htmlgen.go b/doc/htmlgen.go
index 4d68767c3..3a8feb8bc 100644
--- a/doc/htmlgen.go
+++ b/doc/htmlgen.go
@@ -5,7 +5,7 @@
// Process plain text into HTML.
// - h2's are made from lines followed by a line "----\n"
// - tab-indented blocks become
blocks
-// - blank lines become marks
+// - blank lines become
marks (except inside
tags)
// - "quoted strings" become quoted strings
package main
@@ -35,9 +35,9 @@ var (
func main() {
read()
headings()
- paragraphs()
coalesce(preStart, foldPre)
coalesce(tab, foldTabs)
+ paragraphs()
quotes()
write()
}
diff --git a/doc/root.html b/doc/root.html
index f98f9c243..8d76928c8 100644
--- a/doc/root.html
+++ b/doc/root.html
@@ -60,7 +60,7 @@ google.setOnLoadCallback(loadFeed);
Go Videos | More...
-
“Practical Go Programming” OSDC Tech Talk
+
“Writing Web Apps in Go” Google I/O 2011
Go Blog | More...
@@ -78,9 +78,10 @@ google.setOnLoadCallback(loadFeed);
Effective Go
Go FAQ
Other Documentation
+ Go for Google App Engine New!
-
+
For developers:
- Package Dashboard
diff --git a/doc/talks/io2011/Real_World_Go.pdf b/doc/talks/io2011/Real_World_Go.pdf
new file mode 100644
index 000000000..2a187116b
Binary files /dev/null and b/doc/talks/io2011/Real_World_Go.pdf differ
diff --git a/doc/talks/io2011/Writing_Web_Apps_in_Go.pdf b/doc/talks/io2011/Writing_Web_Apps_in_Go.pdf
new file mode 100644
index 000000000..ca4702ee9
Binary files /dev/null and b/doc/talks/io2011/Writing_Web_Apps_in_Go.pdf differ
diff --git a/doc/video-005.jpg b/doc/video-005.jpg
new file mode 100644
index 000000000..32371581f
Binary files /dev/null and b/doc/video-005.jpg differ
--
cgit v1.2.3