From f154da9e12608589e8d5f0508f908a0c3e88a1bb Mon Sep 17 00:00:00 2001
From: Tianon Gravi
http://
prefix. Subdirectories are named by
-adding to that path. For example, the supplemental networking
-libraries for Go are obtained by running
+adding to that path.
+For example, the Go example programs are obtained by running
-hg clone http://code.google.com/p/go.net +git clone https://github.com/golang/example
and thus the import path for the root directory of that repository is
-"code.google.com/p/go.net
". The websocket package is stored in a
-subdirectory, so its import path is
-"code.google.com/p/go.net/websocket
".
github.com/golang/example
".
+The stringutil
+package is stored in a subdirectory, so its import path is
+"github.com/golang/example/stringutil
".
These paths are on the long side, but in exchange we get an automatically managed name space for import paths and the ability for @@ -99,7 +100,7 @@ deduce where to obtain the source code.
in a known way from the import path. Specifically, the first choice is$GOPATH/src/<import-path>
. If $GOPATH
is
unset, the go command will fall back to storing source code alongside the
-standard Go packages, in $GOROOT/src/pkg/<import-path>
.
+standard Go packages, in $GOROOT/src/<import-path>
.
If $GOPATH
is set to a list of paths, the go command tries
<dir>/src/<import-path>
for each of the directories in
that list.
diff --git a/doc/articles/race_detector.html b/doc/articles/race_detector.html
index 282db8ba4..6defd98f9 100644
--- a/doc/articles/race_detector.html
+++ b/doc/articles/race_detector.html
@@ -57,35 +57,35 @@ Here is an example:
WARNING: DATA RACE
Read by goroutine 185:
net.(*pollServer).AddFD()
- src/pkg/net/fd_unix.go:89 +0x398
+ src/net/fd_unix.go:89 +0x398
net.(*pollServer).WaitWrite()
- src/pkg/net/fd_unix.go:247 +0x45
+ src/net/fd_unix.go:247 +0x45
net.(*netFD).Write()
- src/pkg/net/fd_unix.go:540 +0x4d4
+ src/net/fd_unix.go:540 +0x4d4
net.(*conn).Write()
- src/pkg/net/net.go:129 +0x101
+ src/net/net.go:129 +0x101
net.func·060()
- src/pkg/net/timeout_test.go:603 +0xaf
+ src/net/timeout_test.go:603 +0xaf
Previous write by goroutine 184:
net.setWriteDeadline()
- src/pkg/net/sockopt_posix.go:135 +0xdf
+ src/net/sockopt_posix.go:135 +0xdf
net.setDeadline()
- src/pkg/net/sockopt_posix.go:144 +0x9c
+ src/net/sockopt_posix.go:144 +0x9c
net.(*conn).SetDeadline()
- src/pkg/net/net.go:161 +0xe3
+ src/net/net.go:161 +0xe3
net.func·061()
- src/pkg/net/timeout_test.go:616 +0x3ed
+ src/net/timeout_test.go:616 +0x3ed
Goroutine 185 (running) created at:
net.func·061()
- src/pkg/net/timeout_test.go:609 +0x288
+ src/net/timeout_test.go:609 +0x288
Goroutine 184 (running) created at:
net.TestProlongTimeout()
- src/pkg/net/timeout_test.go:618 +0x298
+ src/net/timeout_test.go:618 +0x298
testing.tRunner()
- src/pkg/testing/testing.go:301 +0xe8
+ src/testing/testing.go:301 +0xe8
-The race detector runs on darwin/amd64
, linux/amd64
, and windows/amd64
.
+The race detector runs on darwin/amd64
, freebsd/amd64
,
+linux/amd64
, and windows/amd64
.
The SB
pseudo-register can be thought of as the origin of memory, so the symbol foo(SB)
is the name foo
as an address in memory.
+This form is used to name global functions and data.
+Adding <>
to the name, as in foo<>(SB)
, makes the name
+visible only in the current source file, like a top-level static
declaration in a C file.
@@ -128,8 +131,11 @@ Thus 0(FP)
is the first argument to the function,
When referring to a function argument this way, it is conventional to place the name
at the beginning, as in first_arg+0(FP)
and second_arg+8(FP)
.
Some of the assemblers enforce this convention, rejecting plain 0(FP)
and 8(FP)
.
-For assembly functions with Go prototypes, go vet
will check that the argument names
+For assembly functions with Go prototypes, go
vet
will check that the argument names
and offsets match.
+On 32-bit systems, the low and high 32 bits of a 64-bit value are distinguished by adding
+a _lo
or _hi
suffix to the name, as in arg_lo+0(FP)
or arg_hi+4(FP)
.
+If a Go prototype does not name its result, the expected assembly name is ret
.
@@ -149,7 +155,7 @@ hardware's SP
register.
Instructions, registers, and assembler directives are always in UPPER CASE to remind you
that assembly programming is a fraught endeavor.
-(Exceptions: the m
and g
register renamings on ARM.)
+(Exception: the g
register renaming on ARM.)
@@ -206,6 +212,8 @@ The frame size $24-8
states that the function has a 24-byte frame
and is called with 8 bytes of argument, which live on the caller's frame.
If NOSPLIT
is not specified for the TEXT
,
the argument size must be provided.
+For assembly functions with Go prototypes, go
vet
will check that the
+argument size is correct.
@@ -216,19 +224,20 @@ simple name profileloop
.
-For DATA
directives, the symbol is followed by a slash and the number
-of bytes the memory associated with the symbol occupies.
-The arguments are optional flags and the data itself.
-For instance,
-
DATA
directives followed by a GLOBL
directive.
+Each DATA
directive initializes a section of the
+corresponding memory.
+The memory not explicitly initialized is zeroed.
+The general form of the DATA
directive is
-DATA runtime·isplan9(SB)/4, $1 +DATA symbol+offset(SB)/width, value
-declares the local symbol runtime·isplan9
of size 4 and value 1.
-Again the symbol has the middle dot and is offset from SB
.
+which initializes the symbol memory at the given offset and width with the given value.
+The DATA
directives for a given symbol must be written with increasing offsets.
@@ -237,15 +246,26 @@ The arguments are optional flags and the size of the data being declared as a gl
which will have initial value all zeros unless a DATA
directive
has initialized it.
The GLOBL
directive must follow any corresponding DATA
directives.
-This example
+
+For example,
-GLOBL runtime·tlsoffset(SB),$4 +DATA divtab<>+0x00(SB)/4, $0xf4f8fcff +DATA divtab<>+0x04(SB)/4, $0xe6eaedf0 +... +DATA divtab<>+0x3c(SB)/4, $0x81828384 +GLOBL divtab<>(SB), RODATA, $64 + +GLOBL runtime·tlsoffset(SB), NOPTR, $4
-declares runtime·tlsoffset
to have size 4.
+declares and initializes divtab<>
, a read-only 64-byte table of 4-byte integer values,
+and declares runtime·tlsoffset
, a 4-byte, implicitly zeroed variable that
+contains no pointers.
@@ -253,7 +273,7 @@ There may be one or two arguments to the directives.
If there are two, the first is a bit mask of flags,
which can be written as numeric expressions, added or or-ed together,
or can be set symbolically for easier absorption by a human.
-Their values, defined in the file src/cmd/ld/textflag.h
, are:
+Their values, defined in the standard #include
file textflag.h
, are:
recover
+For garbage collection to run correctly, the runtime must know the +location of pointers in all global data and in most stack frames. +The Go compiler emits this information when compiling Go source files, +but assembly programs must define it explicitly. +
+ +
+A data symbol marked with the NOPTR
flag (see above)
+is treated as containing no pointers to runtime-allocated data.
+A data symbol with the RODATA
flag
+is allocated in read-only memory and is therefore treated
+as implicitly marked NOPTR
.
+A data symbol with a total size smaller than a pointer
+is also treated as implicitly marked NOPTR
.
+It is not possible to define a symbol containing pointers in an assembly source file;
+such a symbol must be defined in a Go source file instead.
+Assembly source can still refer to the symbol by name
+even without DATA
and GLOBL
directives.
+A good general rule of thumb is to define all non-RODATA
+symbols in Go instead of in assembly.
+
+Each function also needs annotations giving the location of
+live pointers in its arguments, results, and local stack frame.
+For an assembly function with no pointer results and
+either no local stack frame or no function calls,
+the only requirement is to define a Go prototype for the function
+in a Go source file in the same package.
+For more complex situations, explicit annotation is needed.
+These annotations use pseudo-instructions defined in the standard
+#include
file funcdata.h
.
+
+If a function has no arguments and no results,
+the pointer information can be omitted.
+This is indicated by an argument size annotation of $n-0
+on the TEXT
instruction.
+Otherwise, pointer information must be provided by
+a Go prototype for the function in a Go source file,
+even for assembly functions not called directly from Go.
+(The prototype will also let go
vet
check the argument references.)
+At the start of the function, the arguments are assumed
+to be initialized but the results are assumed uninitialized.
+If the results will hold live pointers during a call instruction,
+the function should start by zeroing the results and then
+executing the pseudo-instruction GO_RESULTS_INITIALIZED
.
+This instruction records that the results are now initialized
+and should be scanned during stack movement and garbage collection.
+It is typically easier to arrange that assembly functions do not
+return pointers or do not contain call instructions;
+no assembly functions in the standard library use
+GO_RESULTS_INITIALIZED
.
+
+If a function has no local stack frame,
+the pointer information can be omitted.
+This is indicated by a local frame size annotation of $0-n
+on the TEXT
instruction.
+The pointer information can also be omitted if the
+function contains no call instructions.
+Otherwise, the local stack frame must not contain pointers,
+and the assembly must confirm this fact by executing the
+pseudo-instruction NO_LOCAL_POINTERS
.
+Because stack resizing is implemented by moving the stack,
+the stack pointer may change during any function call:
+even pointers to stack data must not be kept in local variables.
+
@@ -344,7 +438,7 @@ Here follows some descriptions of key Go-specific details for the supported arch
-The runtime pointers to the m
and g
structures are maintained
+The runtime pointer to the g
structure is maintained
through the value of an otherwise unused (as far as Go is concerned) register in the MMU.
A OS-dependent macro get_tls
is defined for the assembler if the source includes
an architecture-dependent header file, like this:
@@ -356,14 +450,15 @@ an architecture-dependent header file, like this:
Within the runtime, the get_tls
macro loads its argument register
-with a pointer to a pair of words representing the g
and m
pointers.
+with a pointer to the g
pointer, and the g
struct
+contains the m
pointer.
The sequence to load g
and m
using CX
looks like this:
get_tls(CX) -MOVL g(CX), AX // Move g into AX. -MOVL m(CX), BX // Move m into BX. +MOVL g(CX), AX // Move g into AX. +MOVL g_m(AX), BX // Move g->m into BX.
MOVQ
rather than
get_tls(CX) -MOVQ g(CX), AX // Move g into AX. -MOVQ m(CX), BX // Move m into BX. +MOVQ g(CX), AX // Move g into AX. +MOVQ g_m(AX), BX // Move g->m into BX.
-The registers R9
, R10
, and R11
+The registers R10
and R11
are reserved by the compiler and linker.
-R9
and R10
point to the m
(machine) and g
-(goroutine) structures, respectively.
-Within assembler source code, these pointers must be referred to as m
and g
;
-the names R9
and R10
are not recognized.
+R10
points to the g
(goroutine) structure.
+Within assembler source code, this pointer must be referred to as g
;
+the name R10
is not recognized.
@@ -434,13 +528,10 @@ Here's how the 386 runtime defines the 64-bit atomic load function. // so actually // void atomicload64(uint64 *res, uint64 volatile *addr); TEXT runtime·atomicload64(SB), NOSPLIT, $0-8 - MOVL 4(SP), BX - MOVL 8(SP), AX - // MOVQ (%EAX), %MM0 - BYTE $0x0f; BYTE $0x6f; BYTE $0x00 - // MOVQ %MM0, 0(%EBX) - BYTE $0x0f; BYTE $0x7f; BYTE $0x03 - // EMMS - BYTE $0x0F; BYTE $0x77 + MOVL ptr+0(FP), AX + LEAL ret_lo+4(FP), BX + BYTE $0x0f; BYTE $0x6f; BYTE $0x00 // MOVQ (%EAX), %MM0 + BYTE $0x0f; BYTE $0x7f; BYTE $0x03 // MOVQ %MM0, 0(%EBX) + BYTE $0x0F; BYTE $0x77 // EMMS RET diff --git a/doc/cmd.html b/doc/cmd.html index 725666f1d..5d20d3887 100644 --- a/doc/cmd.html +++ b/doc/cmd.html @@ -62,10 +62,10 @@ details.
"go test -coverprofile"
.
+generated by "go test -coverprofile"
.bin/ - streak # command executable - todo # command executable + hello # command executable + outyet # command executable pkg/ linux_amd64/ - code.google.com/p/goauth2/ - oauth.a # package object - github.com/nf/todo/ - task.a # package object + github.com/golang/example/ + stringutil.a # package object src/ - code.google.com/p/goauth2/ - .hg/ # mercurial repository metadata - oauth/ - oauth.go # package source - oauth_test.go # test source - github.com/nf/ - streak/ - .git/ # git repository metadata - oauth.go # command source - streak.go # command source - todo/ - .git/ # git repository metadata - task/ - task.go # package source - todo.go # command source + github.com/golang/example/ + .git/ # Git repository metadata + hello/ + hello.go # command source + outyet/ + main.go # command source + main_test.go # test source + stringutil/ + reverse.go # package source + reverse_test.go # test source
-This workspace contains three repositories (goauth2
,
-streak
, and todo
) comprising two commands
-(streak
and todo
) and two libraries
-(oauth
and task
).
+This workspace contains one repository (example
)
+comprising two commands (hello
and outyet
)
+and one library (stringutil
).
+
+A typical workspace would contain many source repositories containing many +packages and commands. Most Go programmers keep all their Go source code +and dependencies in a single workspace.
@@ -277,29 +275,29 @@ Let's write a library and use it from the hello
program.
Again, the first step is to choose a package path (we'll use
-github.com/user/newmath
) and create the package directory:
+github.com/user/stringutil
) and create the package directory:
-$ mkdir $GOPATH/src/github.com/user/newmath +$ mkdir $GOPATH/src/github.com/user/stringutil
-Next, create a file named sqrt.go
in that directory with the
+Next, create a file named reverse.go
in that directory with the
following contents.
-// Package newmath is a trivial example package. -package newmath - -// Sqrt returns an approximation to the square root of x. -func Sqrt(x float64) float64 { - z := 1.0 - for i := 0; i < 1000; i++ { - z -= (z*z - x) / (2 * z) +// Package stringutil contains utility functions for working with strings. +package stringutil + +// Reverse returns its argument string reversed rune-wise left to right. +func Reverse(s string) string { + r := []rune(s) + for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { + r[i], r[j] = r[j], r[i] } - return z + return string(r) }@@ -308,7 +306,7 @@ Now, test that the package compiles with
go build
:
-$ go build github.com/user/newmath +$ go build github.com/user/stringutil
@@ -326,7 +324,7 @@ directory of the workspace.
-After confirming that the newmath
package builds,
+After confirming that the stringutil
package builds,
modify your original hello.go
(which is in
$GOPATH/src/github.com/user/hello
) to use it:
Whenever the go
tool installs a package or binary, it also
-installs whatever dependencies it has. So when you install the hello
-program
+installs whatever dependencies it has.
+So when you install the hello
program
@@ -356,16 +354,16 @@ $ go install github.com/user/hello
-the newmath
package will be installed as well, automatically.
+the stringutil
package will be installed as well, automatically.
-Running the new version of the program, you should see some numerical output: +Running the new version of the program, you should see a new, reversed message:
$ hello -Hello, world. Sqrt(2) = 1.414213562373095 +Hello, Go!
@@ -374,22 +372,22 @@ After the steps above, your workspace should look like this:
bin/ - hello # command executable + hello # command executable pkg/ - linux_amd64/ # this will reflect your OS and architecture + linux_amd64/ # this will reflect your OS and architecture github.com/user/ - newmath.a # package object + stringutil.a # package object src/ github.com/user/ hello/ - hello.go # command source - newmath/ - sqrt.go # package source + hello.go # command source + stringutil/ + reverse.go # package source
-Note that go install
placed the newmath.a
object in a
-directory inside pkg/linux_amd64
that mirrors its source
+Note that go install
placed the stringutil.a
object
+in a directory inside pkg/linux_amd64
that mirrors its source
directory.
This is so that future invocations of the go
tool can find the
package object and avoid recompiling the package unnecessarily.
@@ -457,20 +455,29 @@ if the function calls a failure function such as t.Error
or
-Add a test to the newmath
package by creating the file
-$GOPATH/src/github.com/user/newmath/sqrt_test.go
containing the
-following Go code.
+Add a test to the stringutil
package by creating the file
+$GOPATH/src/github.com/user/stringutil/reverse_test.go
containing
+the following Go code.
-package newmath +package stringutil import "testing" -func TestSqrt(t *testing.T) { - const in, out = 4, 2 - if x := Sqrt(in); x != out { - t.Errorf("Sqrt(%v) = %v, want %v", in, x, out) +func TestReverse(t *testing.T) { + cases := []struct { + in, want string + }{ + {"Hello, world", "dlrow ,olleH"}, + {"Hello, 世界", "界世 ,olleH"}, + {"", ""}, + } + for _, c := range cases { + got := Reverse(c.in) + if got != c.want { + t.Errorf("Reverse(%q) == %q, want %q", c.in, got, c.want) + } } }@@ -480,8 +487,8 @@ Then run the test with
go test
:
-$ go test github.com/user/newmath -ok github.com/user/newmath 0.165s +$ go test github.com/user/stringutil +ok github.com/user/stringutil 0.165s
@@ -491,7 +498,7 @@ directory, you can omit the package path:
$ go test -ok github.com/user/newmath 0.165s +ok github.com/user/stringutil 0.165s
@@ -507,16 +514,16 @@ An import path can describe how to obtain the package source code using a
revision control system such as Git or Mercurial. The go
tool 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.google.com/p/go.example
.
+Git repository hosted at GitHub
+github.com/golang/example
.
If you include the repository URL in the package's import path,
go get
will fetch, build, and install it automatically:
-$ go get code.google.com/p/go.example/hello +$ go get github.com/golang/example/hello $ $GOPATH/bin/hello -Hello, world. Sqrt(2) = 1.414213562373095 +Hello, Go examples!
@@ -533,43 +540,45 @@ tree should now look like this:
bin/ - hello # command executable + hello # command executable pkg/ linux_amd64/ - code.google.com/p/go.example/ - newmath.a # package object + github.com/golang/example/ + stringutil.a # package object github.com/user/ - newmath.a # package object + stringutil.a # package object src/ - code.google.com/p/go.example/ + github.com/golang/example/ + .git/ # Git repository metadata hello/ - hello.go # command source - newmath/ - sqrt.go # package source - sqrt_test.go # test source + hello.go # command source + stringutil/ + reverse.go # package source + reverse_test.go # test source github.com/user/ hello/ - hello.go # command source - newmath/ - sqrt.go # package source - sqrt_test.go # test source + hello.go # command source + stringutil/ + reverse.go # package source + reverse_test.go # test source
-The hello
command hosted at Google Code depends on the
-newmath
package within the same repository. The imports in
-hello.go
file use the same import path convention, so the go
-get
command is able to locate and install the dependent package, too.
+The hello
command hosted at GitHub depends on the
+stringutil
package within the same repository. The imports in
+hello.go
file use the same import path convention, so the
+go get
command is able to locate and install the dependent
+package, too.
-import "code.google.com/p/go.example/newmath" +import "github.com/golang/example/stringutil"
This convention is the easiest way to make your Go packages available for others to use. -The Go Wiki +The Go Wiki and godoc.org provide lists of external Go projects.
@@ -618,5 +627,5 @@ The official mailing list for discussion of the Go language isReport bugs using the -Go issue tracker. +Go issue tracker.
diff --git a/doc/contrib.html b/doc/contrib.html index a615fc67a..93a609fb2 100644 --- a/doc/contrib.html +++ b/doc/contrib.html @@ -30,21 +30,16 @@ We encourage all Go users to subscribe toA summary of the changes between Go releases.
--A guide for updating your code to work with Go 1. -
+A summary of the changes between Go releases. Notes for the major releases:
--A list of significant changes in Go 1.1, with instructions for updating -your code where necessary. -Each point release includes a similar document appropriate for that -release: Go 1.2, Go 1.3, -and so on. -
+@@ -55,7 +50,7 @@ Go 1 matures.
Check out the Go source code.
If you spot bugs, mistakes, or inconsistencies in the Go project's code or documentation, please let us know by -filing a ticket -on our issue tracker. +filing a ticket +on our issue tracker. (Of course, you should check it's not an existing issue before creating a new one.)
@@ -106,8 +101,8 @@ To get started, read these contribution guidelines for information on design, testing, and our code review process.-Check the tracker for +Check the tracker for open issues that interest you. Those labeled -HelpWanted +helpwanted are particularly in need of outside help.
diff --git a/doc/contribute.html b/doc/contribute.html index 392734985..ba550d528 100644 --- a/doc/contribute.html +++ b/doc/contribute.html @@ -6,9 +6,21 @@This document explains how to contribute changes to the Go project. -It assumes you have installed Go using the +It assumes you have installed Go from source: +
+ +
+$ git clone https://go.googlesource.com/go +$ cd go/src +$ ./all.bash ++ + +
(Note that the gccgo
frontend lives elsewhere;
see Contributing to gccgo.)
-After running for a while, the command should print "ALL TESTS PASSED
".
+After running for a while, the command should print
+"ALL
TESTS
PASSED
".
git-review
,
+discussed below, helps manage the code review process through a Google-hosted
+instance of the code review
+system called Gerrit.
-
-Using Mercurial with the code review extension is not the same
-as using standard Mercurial.
+The Git code hosting server and Gerrit code review server both use a Google
+Account to authenticate. You therefore need a Google Account to proceed.
+(If you can use the account to
+sign in at google.com,
+you can use it to sign in to the code review server.)
+The email address you use with the code review system
+will be recorded in the change log
+and in the CONTRIBUTORS
file.
+You can create a Google Account
+associated with any address where you receive email.
+
+Visit the site go.googlesource.com +and log in using your Google Account. +Click on the "Generate Password" link that appears at the top of the page.
-The Go repository is maintained as a single line of reviewed changes;
-we prefer to avoid the complexity of Mercurial's arbitrary change graph.
-The code review extension helps here: its hg submit
command
-automatically checks for and warns about the local repository
-being out of date compared to the remote one.
-The hg submit
command also verifies other
-properties about the Go repository.
-For example,
-it checks that Go code being checked in is formatted in the standard style,
-as defined by gofmt,
-and it checks that the author of the code is properly recorded for
-copyright purposes.
+Click the radio button that says "Only go.googlesource.com
"
+to use this authentication token only for the Go project.
-To help ensure changes are only created by hg submit
,
-the code review extension disables the standard hg commit
-command.
+Further down the page is a box containing commands to install
+the authentication cookie in file called .gitcookies
in your home
+directory.
+Copy the text for the commands into a Unix shell window to execute it.
+That will install the authentication token.
+(If you are on a Windows computer, you should instead follow the instructions +in the yellow box to run the command.) +
-Edit .hg/hgrc
in the root of your Go checkout to add:
-[extensions] -codereview = /path/to/go/lib/codereview/codereview.py ++Now that you have a Google account and the authentication token, +you need to register your account with Gerrit, the code review system. +To do this, visit golang.org/cl +and log in using the same Google Account you used above. +That is all that is required. +
-[ui] -username = Your Name <you@server.dom> +Install the git-review command
+ ++Now install the
+ +git-review
command by running, ++go get -u golang.org/x/review/git-review-The
+username
information will not be used unless -you are a committer (see below), but Mercurial complains if it is missing. +Make suregit-review
is installed in your shell path, so that the +git
command can find it. Check that+$ git review help ++-As the codereview extension is only enabled for your Go checkout, the remainder of this document assumes you -are inside the go directory when issuing commands. +prints help text, not an error.
-To contribute to subrepositories, edit the
.hg/hgrc
for each -subrepository in the same way. For example, add the codereview extension to -code.google.com/p/go.tools/.hg/hgrc
. ++Note to Git aficionados: The
-git-review
command is not required to +upload and manage Gerrit code reviews. For those who prefer plain Git, the text +below gives the Git equivalent of each git-review command. If you do use plain +Git, note that you still need the commit hooks that the git-review command +configures; those hooks add a GerritChange-Id
line to the commit +message and check that all Go source files have been formatted with gofmt. Even +if you intend to use plain Git for daily work, install the hooks in a new Git +checkout by runninggit-review
hooks
).Understanding the extension
+Set up git aliases
-After adding the code review extension, you can run
++The
git-review
command can be run directly from the shell +by typing, for instance, +-$ hg help codereview +$ git review sync-to learn more about its commands. To learn about a specific code-review-specific -command such as
+change
, run+but it is more convenient to set up aliases for
git-review
's own +subcommands, so that the above becomes, +-$ hg help change +$ git sync--Windows users may need to perform extra steps to get the code review -extension working. See the -CodeReview page -on the Go Wiki for details.
- -Log in to the code review site.
+Thegit-review
subcommands have been chosen to be distinct from +Git's own, so it's safe to do so. +-The code review server uses a Google Account to authenticate. -(If you can use the account to -sign in at google.com, -you can use it to sign in to the code review server.) -The email address you use on the Code Review site -will be recorded in the Mercurial change log -and in the
CONTRIBUTORS
file. -You can create a Google Account -associated with any address where you receive email. -If you've enabled the two-step verification feature, don't forget to generate an -application-specific password and use that when prompted for a password. +The aliases are optional, but in the rest of this document we will assume +they are installed. +To install them, copy this text into your Git configuration file +(usually.gitconfig
in your home directory):-$ hg code-login -Email (login for uploading to codereview.appspot.com): rsc@golang.org -Password for rsc@golang.org: - -Saving authentication cookies to /Users/rsc/.codereview_upload_cookies_codereview.appspot.com +[alias] + change = review change + gofmt = review gofmt + mail = review mail + pending = review pending + sync = review sync-Configure your account settings.
+Understanding the git-review command
-Edit your code review settings. -Grab a nickname. -Many people prefer to set the Context option to -“Whole file” to see more context when reviewing changes. -
+After installing the
+ +git-review
command, you can run+$ git review help +-Once you have chosen a nickname in the settings page, others -can use that nickname as a shorthand for naming reviewers and the CC list. -For example,
rsc
is an alias forrsc@golang.org
. ++to learn more about its commands. +You can also read the command documentation.
-Switch to the default branch
+Switch to the master branch
Most Go installations use a release branch, but new changes should -only be made to the default branch. (They may be applied later to a release -branch as part of the release process.) -Before making a change, make sure you use the default branch: +only be made based on the master branch. +(They may be applied later to a release branch as part of the release process, +but most contributors won't do this themselves.) +Before making a change, make sure you start on the master branch:
-$ hg update default +$ git checkout master +$ git sync++(In Git terms,
+git
sync
runs +git
pull
-r
.) +Make a change
The entire checked-out tree is writable. -If you need to edit files, just edit them: Mercurial will figure out which ones changed. -You do need to inform Mercurial of added, removed, copied, or renamed files, -by running -
-hg add
, -hg rm
, -hg cp
, -or -hg mv
. +Once you have edited files, you must tell Git that they have been modified. +You must also tell Git about any files that are added, removed, or renamed files. +These operations are done with the usual Git commands, +git
add
, +git
rm
, +and +git
mv
.When you are ready to send a change out for review, run
++If you wish to checkpoint your work, or are ready to send the code out for review, run
-$ hg change +$ git change <branch>-from any directory in your Go repository. -Mercurial will open a change description file in your editor. -(It uses the editor named by the
$EDITOR
environment variable,vi
by default.) -The file will look like: ++from any directory in your Go repository to commit the changes so far. +The name <branch> is an arbitrary one you choose to identify the +local branch containing your changes.
--# Change list. -# Lines beginning with # are ignored. -# Multi-line values should be indented. ++(In Git terms,
-Reviewer: -CC: +git
change
<branch>
+runsgit
checkout
-b
branch
, +thengit
branch
--set-upstream-to
origin/master
, +thengit
commit
.) ++Git will open a change description file in your editor. +(It uses the editor named by the
-Description: - <enter description here> +$EDITOR
environment variable, +vi
by default.) +The file will look like: +-Files: - src/pkg/math/sin.go - src/pkg/math/tan.go - src/pkg/regexp/regexp.go +# Please enter the commit message for your changes. Lines starting +# with '#' will be ignored, and an empty message aborts the commit. +# On branch foo +# Changes not staged for commit: +# modified: editedfile.go +#-The
- -Reviewer
line lists the reviewers assigned -to this change, and theCC
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, leave the reviewer field blank. -This means that the -golang-codereviews@googlegroups.com -mailing list will be used as the reviewer. --Replace “
- -<enter description here>
” -with a description of your change. +At the beginning of this file is a blank line; replace it +with a thorough description of your change. The first line of the change description is conventionally a one-line summary of the change, prefixed by the primary affected package, -and is used as the subject for code review mail; the rest of the -description elaborates. --The
Files
section lists all the modified files -in your client. -It is best to keep unrelated changes in different change lists. -In this example, we can include just the changes to packagemath
-by deleting the line mentioningregexp.go
. +and is used as the subject for code review mail. +The rest of the +description elaborates and should provide context for the +change and explain what it does. +If there is a helpful reference, mention it here.@@ -273,343 +307,314 @@ After editing, the template might now read:
-# Change list. -# Lines beginning with # are ignored. -# Multi-line values should be indented. +math: improved Sin, Cos and Tan precision for very large arguments -Reviewer: golang-codereviews@googlegroups.com -CC: math-nuts@swtch.com +The existing implementation has poor numerical properties for +large arguments, so use the McGillicutty algorithm to improve +accuracy above 1e10. -Description: - math: improved Sin, Cos and Tan precision for very large arguments. +The algorithm is described at http://wikipedia.org/wiki/McGillicutty_Algorithm - See Bimmler and Shaney, ``Extreme sinusoids,'' J. Math 3(14). - Fixes issue 159. +Fixes #159 -Files: - src/pkg/math/sin.go - src/pkg/math/tan.go +# Please enter the commit message for your changes. Lines starting +# with '#' will be ignored, and an empty message aborts the commit. +# On branch foo +# Changes not staged for commit: +# modified: editedfile.go +#-The special sentence “Fixes issue 159.” associates -the change with issue 159 in the Go issue tracker. +The commented section of the file lists all the modified files in your client. +It is best to keep unrelated changes in different change lists, +so if you see a file listed that should not be included, abort +the command and move that file to a different branch. +
+ ++The special notation "Fixes #159" associates the change with issue 159 in the +Go issue tracker. When this change is eventually submitted, the issue tracker will automatically mark the issue as fixed. -(These conventions are described in detail by the -Google Project Hosting Issue Tracker documentation.) +(There are several such conventions, described in detail in the +GitHub Issue Tracker documentation.)
-Save the file and exit the editor.
+Once you have finished writing the commit message, +save the file and exit the editor. +-The code review server assigns your change an issue number and URL, -which
hg change
will print, something like: +If you wish to do more editing, re-stage your changes using +git
add
, and then run-CL created: https://codereview.appspot.com/99999 +$ git change-Adding or removing files from an existing change
--If you need to re-edit the change description, or change the files included in the CL, -run
hg change 99999
. +to update the change description and incorporate the staged changes. The +change description contains aChange-Id
line near the bottom, +added by a Git commit hook during the initial +git
change
. +That line is used by Gerrit to match successive uploads of the same change. +Do not edit or delete it.-Alternatively, you can use +(In Git terms,
+ +git
change
with no branch name +runsgit
commit
--amend
.) +Mail the change for review
+ ++Once the change is ready, mail it out for review:
-$ hg file 99999 somefile +$ git mail-to add
somefile
to CL 99999, and +You can specify a reviewer or CC interested parties +using the-r
or-cc
options. +Both accept a comma-separated list of email addresses:-$ hg file -d 99999 somefile +$ git mail -r joe@golang.org -cc mabel@example.com,math-nuts@swtch.com-to remove
somefile
from the CL. +Unless explicitly told otherwise, such as in the discussion leading +up to sending in the change list, it's better not to specify a reviewer. +All changes are automatically CC'ed to the +golang-codereviews@googlegroups.com +mailing list.-A file may only belong to a single active CL at a time.
-hg file
-will issue a warning if a file is moved between changes. +(In Git terms,git
git
push
origin
+HEAD:refs/for/master
.)Synchronize your client
- -While you were working, others might have submitted changes -to the repository. To update your client, run
- --$ hg sync -- -(For Mercurial fans,
-hg sync
runshg pull -u
-but then also synchronizes the local change list state against the new data.)-If files you were editing have changed, Mercurial does its best to merge the -remote changes into your local changes. It may leave some files to merge by hand. +If your change relates to an open issue, please add a comment to the issue +announcing your proposed fix, including a link to your CL.
-For example, suppose you have edited
flag_test.go
but -someone else has committed an independent change. -When you runhg sync
, you will get the (scary-looking) output -(emphasis added): +The code review server assigns your change an issue number and URL, +whichgit
-$ hg sync -adding changesets -adding manifests -adding file changes -added 1 changeset with 2 changes to 2 files -getting src/pkg/flag/flag.go -couldn't find merge tool hgmerge -merging src/pkg/flag/flag_test.go -warning: conflicts during merge. -merging src/pkg/flag/flag_test.go failed! -1 file updated, 0 files merged, 0 files removed, 1 file unresolved -use 'hg resolve' to retry unresolved file merges -$ +remote: New Changes: +remote: https://go-review.googlesource.com/99999 math: improved Sin, Cos and Tan precision for very large arguments+Reviewing code
+-The only important part in that transcript is the italicized line: -Mercurial failed to merge your changes with the independent change. -When this happens, Mercurial leaves both edits in the file, -marked by
-<<<<<<<
and ->>>>>>>
. -it is now your job to edit the file to combine them. -Continuing the example, searching for those strings inflag_test.go
-might turn up: +Runninggit
- VisitAll(visitor); -<<<<<<< local - if len(m) != 7 { -======= - if len(m) != 8 { ->>>>>>> other - t.Error("VisitAll misses some flags"); -+Revise and upload
-Mercurial doesn't show it, but suppose the original text that both edits -started with was 6; you added 1 and the other change added 2, -so the correct answer might now be 9. First, edit the section -to remove the markers and leave the correct code: +You must respond to review comments through the web interface. +(Unlike with the old Rietveld review system, responding by mail has no effect.)
-- VisitAll(visitor); - if len(m) != 9 { - t.Error("VisitAll misses some flags"); ---Then ask Mercurial to mark the conflict as resolved: +When you have revised the code and are ready for another round of review, +stage those changes and use
-git
change
to update the +commit. +To send the update change list for another round of review, +rungit
-$ hg resolve -m flag_test.go ---If you had been editing the file, say for debugging, but do not -care to preserve your changes, you can run -
-hg revert flag_test.go
to abandon your -changes, but you may still need to run -hg resolve -m
to mark the conflict resolved. +The reviewer can comment on the new copy, and the process repeats. +The reviewer approves the change by giving it a positive score +(+1 or +2) and replyingLGTM
: looks good to me.Mail the change for review
--Creating or uploading the change uploads a copy of the diff to the code review server, -but it does not notify anyone about it. To do that, you need to run
-hg mail
-(see below). +You can see a list of your pending changes by runninggit
+pending
, and switch between change branches withgit
+change
<branch>
.To send out a change for review, run
- -hg mail
using the change list number -assigned duringhg change
:-$ hg mail 99999 -+Synchronize your client
-You can add to the
Reviewer:
andCC:
lines -using the-r
or--cc
options. -In the above example, we could have left theReviewer
andCC
-lines blank and then run: ++While you were working, others might have submitted changes to the repository. +To update your local branch, run
-$ hg mail -r golang-codereviews@googlegroups.com --cc math-nuts@swtch.com 99999 +$ git sync-to achieve the same effect.
- -Note that
--r
and--cc
cannot be spelled--r
or-cc
.-If your change relates to an open issue, please add a comment to the issue -announcing your proposed fix, including a link to your CL. +(In git terms, git sync runs +
-git
pull
-r
.)Reviewing code
--Running
- -hg mail
will send an email to you and the reviewers -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. +If files you were editing have changed, Git does its best to merge the +remote changes into your local changes. +It may leave some files to merge by hand.Revise and upload
--When you have revised the code and are ready for another round of review, -you can upload your change and send mail asking the reviewers to -please take another look (
+For example, suppose you have editedPTAL
). Use the change list number -assigned duringhg change
-sin.go
but +someone else has committed an independent change. +When you rungit
sync
, +you will get the (scary-looking) output:-$ hg mail 99999 +$ git sync +Failed to merge in the changes. +Patch failed at 0023 math: improved Sin, Cos and Tan precision for very large arguments +The copy of the patch that failed is found in: + /home/you/repo/.git/rebase-apply/patch + +When you have resolved this problem, run "git rebase --continue". +If you prefer to skip this patch, run "git rebase --skip" instead. +To check out the original branch and stop rebasing, run "git rebase --abort".--Or to upload your change without sending a notification, run +If this happens, run
-$ hg upload 99999 +$ git status-You will probably revise your code in response to the reviewer comments. -You might also visit the code review web page and reply to the comments, -letting the reviewer know that you've addressed them or explain why you -haven't. When you're done replying, click “Publish and Mail comments” -to send the line-by-line replies and any other comments. +to see which files failed to merge. +The output will look something like this:
--The reviewer can comment on the new copy, and the process repeats. -The reviewer approves the change by replying with a mail that says -
+LGTM
: looks good to me. -+rebase in progress; onto a24c3eb +You are currently rebasing branch 'mcgillicutty' on 'a24c3eb'. + (fix conflicts and then run "git rebase --continue") + (use "git rebase --skip" to skip this patch) + (use "git rebase --abort" to check out the original branch) --You can see a list of your pending changes by running
+Unmerged paths: + (use "git reset HEAD <file>..." to unstage) + (use "git add <file>..." to mark resolution) -hg pending
(hg p
for short). -Reviewing code by others
+ both modified: sin.go +-You can import a CL proposed by someone else into your local Mercurial client -by using the
hg clpatch
command. Running +The only important part in that transcript is the italicized "both modified" +line: Git failed to merge your changes with the conflicting change. +When this happens, Git leaves both sets of edits in the file, +with conflicts marked by<<<<<<<
and +>>>>>>>
. +It is now your job to edit the file to combine them. +Continuing the example, searching for those strings insin.go
+might turn up:-$ hg clpatch 99999 + arg = scale(arg) +<<<<<<< HEAD + if arg > 1e9 { +======= + if arg > 1e10 { +>>>>>>> mcgillicutty + largeReduce(arg)-will apply the latest diff for CL 99999 to your working copy. If any of the -files referenced in CL 99999 have local modifications,
- -clpatch
-will refuse to apply the whole diff. Once applied, CL 99999 will show up in -the output ofhg pending
and others. --To revert a CL you have applied locally, use the
hg revert
-command. Running +Git doesn't show it, but suppose the original text that both edits +started with was 1e8; you changed it to 1e10 and the other change to 1e9, +so the correct answer might now be 1e10. First, edit the section +to remove the markers and leave the correct code:-$ hg revert @99999 + arg = scale(arg) + if arg > 1e10 { + largeReduce(arg)-will revert any files mentioned on CL 99999 to their original state. This can -be an effective way of reverting one CL revision and applying another. +Then tell Git that the conflict is resolved by running
--Once the CL has been submitted, the next time you run
- -hg sync
-it will be removed from your local pending list. Occasionally the pending list -can get out of sync leaving stale references to closed or abandoned CLs. -You can usehg change -D 99999
to remove the reference to CL 99999. -Submit the change after the review
++$ git add sin.go +-After the code has been
+LGTM
'ed, it is time to submit -it to the Mercurial repository. +If you had been editing the file, say for debugging, but do not +care to preserve your changes, you can run +git
reset
HEAD
sin.go
+to abandon your changes. +Then rungit
rebase
--continue
to +restore the change commit.Reviewing code by others
+-If you are not a committer, you cannot submit the change directly. -Instead a committer, usually the reviewer who said
LGTM
, -will run: +You can import a change proposed by someone else into your local Git repository. +On the Gerrit review page, click the "Download ▼" link in the upper right +corner, copy the "Checkout" command and run it from your local Git repo. +It should look something like this:-$ hg clpatch 99999 -$ hg submit 99999 +$ git fetch https://go.googlesource.com/review refs/changes/21/1221/1 && git checkout FETCH_HEAD-The
+submit
command submits the code. You will be listed as the -author, but the change message will also indicate who the committer was. -Your local client will notice that the change has been submitted -when you next runhg sync
. +To revert, change back to the branch you were working in.Submit the change after the review
+-If you are a committer, you can run: +After the code has been
-LGTM
'ed, an approver may +submit it to the master branch using the Gerrit UI. +There is a "Submit" button on the web page for the change +that appears once the change is approved (marked +2).-$ hg submit 99999 --This checks the change into the repository. The change description will include a link to the code review, and the code review will be updated with a link to the change in the repository. +Since the method used to integrate the changes is "Cherry Pick", +the commit hashes in the repository will be changed by +the submit operation.
--If your local copy of the repository is out of date, -
- -hg submit
will refuse the change: --$ hg submit 99999 -local repository out of date; must sync before submit --More information
-In addition to the information here, the Go community maintains a CodeReview wiki page. +In addition to the information here, the Go community maintains a CodeReview wiki page. Feel free to contribute to this page as you learn the review process.
@@ -617,7 +622,8 @@ Feel free to contribute to this page as you learn the review process.Files in the Go repository don't list author names, both to avoid clutter and to avoid having to keep the lists up to date. -Instead, your name will appear in the Mercurial change log +Instead, your name will appear in the +change log and in the
diff --git a/doc/debugging_with_gdb.html b/doc/debugging_with_gdb.html index afaedf74c..836816419 100644 --- a/doc/debugging_with_gdb.html +++ b/doc/debugging_with_gdb.html @@ -120,7 +120,7 @@ For example:CONTRIBUTORS
file and perhaps theAUTHORS
file.If you'd like to see how this works, or want to extend it, take a look at src/pkg/runtime/runtime-gdb.py in +href="/src/runtime/runtime-gdb.py">src/runtime/runtime-gdb.py in the Go source distribution. It depends on some special magic types (
hash<T,U>
) and variables (runtime.m
andruntime.g
) that the linker @@ -153,7 +153,7 @@ the formpkg.(*MyType).Meth
.In this tutorial we will inspect the binary of the regexp package's unit tests. To build the binary, -change to
@@ -172,7 +172,7 @@ License GPLv 3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.htm 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/regexp.test... +Reading symbols from /home/user/go/src/regexp/regexp.test... done. Loading Go Runtime support. (gdb) @@ -180,7 +180,7 @@ Loading Go Runtime support.$GOROOT/src/pkg/regexp
and rungo test -c
. +change to$GOROOT/src/regexp
and rungo test -c
. This should produce an executable file namedregexp.test
.The message
"Loading Go Runtime support"
means that GDB loaded the -extension from$GOROOT/src/pkg/runtime/runtime-gdb.py
. +extension from$GOROOT/src/runtime/runtime-gdb.py
.@@ -199,7 +199,7 @@ it by hand by telling gdb (assuming you have the go sources in
-(gdb) source ~/go/src/pkg/runtime/runtime-gdb.py +(gdb) source ~/go/src/runtime/runtime-gdb.py Loading Go Runtime support.@@ -259,7 +259,7 @@ Set a breakpoint at theTestFind
function:(gdb) b 'regexp.TestFind' -Breakpoint 1 at 0x424908: file /home/user/go/src/pkg/regexp/find_test.go, line 148. +Breakpoint 1 at 0x424908: file /home/user/go/src/regexp/find_test.go, line 148.@@ -268,9 +268,9 @@ Run the program:
(gdb) run -Starting program: /home/user/go/src/pkg/regexp/regexp.test +Starting program: /home/user/go/src/regexp/regexp.test -Breakpoint 1, regexp.TestFind (t=0xf8404a89c0) at /home/user/go/src/pkg/regexp/find_test.go:148 +Breakpoint 1, regexp.TestFind (t=0xf8404a89c0) at /home/user/go/src/regexp/find_test.go:148 148 func TestFind(t *testing.T) {@@ -297,9 +297,9 @@ Look at the stack trace for where we’ve paused the program:(gdb) bt # backtrace -#0 regexp.TestFind (t=0xf8404a89c0) at /home/user/go/src/pkg/regexp/find_test.go:148 -#1 0x000000000042f60b in testing.tRunner (t=0xf8404a89c0, test=0x573720) at /home/user/go/src/pkg/testing/testing.go:156 -#2 0x000000000040df64 in runtime.initdone () at /home/user/go/src/pkg/runtime/proc.c:242 +#0 regexp.TestFind (t=0xf8404a89c0) at /home/user/go/src/regexp/find_test.go:148 +#1 0x000000000042f60b in testing.tRunner (t=0xf8404a89c0, test=0x573720) at /home/user/go/src/testing/testing.go:156 +#2 0x000000000040df64 in runtime.initdone () at /home/user/go/src/runtime/proc.c:242 #3 0x000000f8404a89c0 in ?? () #4 0x0000000000573720 in ?? () #5 0x0000000000000000 in ?? () @@ -311,18 +311,18 @@ The other goroutine, number 1, is stuck in+runtime.gosched
, blocked(gdb) goroutine 1 bt -#0 0x000000000040facb in runtime.gosched () at /home/user/go/src/pkg/runtime/proc.c:873 +#0 0x000000000040facb in runtime.gosched () at /home/user/go/src/runtime/proc.c:873 #1 0x00000000004031c9 in runtime.chanrecv (c=void, ep=void, selected=void, received=void) - 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 + at /home/user/go/src/runtime/chan.c:342 +#2 0x0000000000403299 in runtime.chanrecv1 (t=void, c=void) at/home/user/go/src/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 + 0x7ffff7f9ef60, tests= []testing.InternalTest = {...}) at /home/user/go/src/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 +at /home/user/go/src/testing/testing.go:168 +#5 0x0000000000400dc1 in main.main () at /home/user/go/src/regexp/_testmain.go:98 +#6 0x00000000004022e7 in runtime.mainstart () at /home/user/go/src/runtime/amd64/asm.s:78 +#7 0x000000000040ea6f in runtime.initdone () at /home/user/go/src/runtime/proc.c:243 #8 0x0000000000000000 in ?? ()@@ -333,7 +333,7 @@ The stack frame shows we’re currently executing theregexp.TestFind (gdb) info frame Stack level 0, frame at 0x7ffff7f9ff88: - rip = 0x425530 in regexp.TestFind (/home/user/go/src/pkg/regexp/find_test.go:148); + rip = 0x425530 in regexp.TestFind (/home/user/go/src/regexp/find_test.go:148); saved rip 0x430233 called by frame at 0x7ffff7f9ffa8 source language minimal. @@ -410,7 +410,7 @@ We can step into the
String
function call with"s"
:(gdb) s -regexp.(*Regexp).String (re=0xf84068d070, noname=void) at /home/user/go/src/pkg/regexp/regexp.go:97 +regexp.(*Regexp).String (re=0xf84068d070, noname=void) at /home/user/go/src/regexp/regexp.go:97 97 func (re *Regexp) String() string {@@ -421,12 +421,12 @@ Get a stack trace to see where we are:(gdb) bt #0 regexp.(*Regexp).String (re=0xf84068d070, noname=void) - at /home/user/go/src/pkg/regexp/regexp.go:97 + at /home/user/go/src/regexp/regexp.go:97 #1 0x0000000000425615 in regexp.TestFind (t=0xf840688b60) - at /home/user/go/src/pkg/regexp/find_test.go:151 + at /home/user/go/src/regexp/find_test.go:151 #2 0x0000000000430233 in testing.tRunner (t=0xf840688b60, test=0x5747b8) - 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 + at /home/user/go/src/testing/testing.go:156 +#3 0x000000000040ea6f in runtime.initdone () at /home/user/go/src/runtime/proc.c:243 ....diff --git a/doc/devel/release.html b/doc/devel/release.html index 1a8439134..5b5d6ab5e 100644 --- a/doc/devel/release.html +++ b/doc/devel/release.html @@ -3,8 +3,7 @@ }-->This page summarizes the changes between official stable releases of Go. -The Mercurial change log -has the full details.
+The change log has the full details.To update to a specific release, use:
@@ -13,6 +12,13 @@ hg pull hg update taggo1.4 (released 2014/12/10)
+ ++Go 1.4 is a major release of Go. +Read the Go 1.4 Release Notes for more information. +
+go1.3 (released 2014/06/18)
diff --git a/doc/devel/weekly.html b/doc/devel/weekly.html index 34c87dc64..5a9c51ef1 100644 --- a/doc/devel/weekly.html +++ b/doc/devel/weekly.html @@ -5,7 +5,7 @@
This page summarizes the changes between tagged weekly snapshots of Go. Such snapshots are no longer created. This page remains as a historical reference only.
-For recent information, see the Mercurial change log and development mailing list.
+For recent information, see the change log and development mailing list.
2012-03-27 (Go 1)
diff --git a/doc/docs.html b/doc/docs.html index 642f36dd4..7eb3a3ad2 100644 --- a/doc/docs.html +++ b/doc/docs.html @@ -147,8 +147,8 @@ Guided tours of Go programs.
-The Go package sources +The Go package sources are intended to serve not only as the core library but also as examples of how to use the language. @@ -344,7 +344,7 @@ 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/encoding/base64
+the package in src/encoding/base64
is imported as "encoding/base64"
but has name base64
,
not encoding_base64
and not encodingBase64
.
libgo/merge.sh
. Accordingly, most library changes
should be made in the main Go repository. The files outside
of libgo/go
are gccgo-specific; that said, some of the
files in libgo/runtime
are based on files
-in src/pkg/runtime
in the main Go repository.
+in src/runtime
in the main Go repository.
+The GCC 4.9 releases include a complete Go 1.2 implementation. +
+diff --git a/doc/go1.3.html b/doc/go1.3.html index 042de1bc7..d51052b2e 100644 --- a/doc/go1.3.html +++ b/doc/go1.3.html @@ -298,7 +298,7 @@ For example,
When invoked with the -analysis
flag,
-godoc
+godoc
now performs sophisticated static
analysis of the code it indexes.
The results of analysis are presented in both the source view and the
@@ -318,7 +318,7 @@ call sites and their callees.
The program misc/benchcmp
that compares
performance across benchmarking runs has been rewritten.
Once a shell and awk script in the main repository, it is now a Go program in the go.tools
repo.
-Documentation is here.
+Documentation is here.
diff --git a/doc/go1.4.html b/doc/go1.4.html new file mode 100644 index 000000000..b4f9619bb --- /dev/null +++ b/doc/go1.4.html @@ -0,0 +1,896 @@ + + +
+The latest Go release, version 1.4, arrives as scheduled six months after 1.3. +
+ +
+It contains only one tiny language change,
+in the form of a backwards-compatible simple variant of for
-range
loop,
+and a possibly breaking change to the compiler involving methods on pointers-to-pointers.
+
+The release focuses primarily on implementation work, improving the garbage collector
+and preparing the ground for a fully concurrent collector to be rolled out in the
+next few releases.
+Stacks are now contiguous, reallocated when necessary rather than linking on new
+"segments";
+this release therefore eliminates the notorious "hot stack split" problem.
+There are some new tools available including support in the go
command
+for build-time source code generation.
+The release also adds support for ARM processors on Android and Native Client (NaCl)
+and for AMD64 on Plan 9.
+
+As always, Go 1.4 keeps the promise +of compatibility, +and almost everything +will continue to compile and run without change when moved to 1.4. +
+ +
+Up until Go 1.3, for
-range
loop had two forms
+
+for i, v := range x { + ... +} ++ +
+and +
+ ++for i := range x { + ... +} ++ +
+If one was not interested in the loop values, only the iteration itself, it was still
+necessary to mention a variable (probably the blank identifier, as in
+for
_
=
range
x
), because
+the form
+
+for range x { + ... +} ++ +
+was not syntactically permitted. +
+ ++This situation seemed awkward, so as of Go 1.4 the variable-free form is now legal. +The pattern arises rarely but the code can be cleaner when it does. +
+ +
+Updating: The change is strictly backwards compatible to existing Go
+programs, but tools that analyze Go parse trees may need to be modified to accept
+this new form as the
+Key
field of RangeStmt
+may now be nil
.
+
+Given these declarations, +
+ ++type T int +func (T) M() {} +var x **T ++ +
+both gc
and gccgo
accepted the method call
+
+x.M() ++ +
+which is a double dereference of the pointer-to-pointer x
.
+The Go specification allows a single dereference to be inserted automatically,
+but not two, so this call is erroneous according to the language definition.
+It has therefore been disallowed in Go 1.4, which is a breaking change,
+although very few programs will be affected.
+
+Updating: Code that depends on the old, erroneous behavior will no longer +compile but is easy to fix by adding an explicit dereference. +
+ +
+Go 1.4 can build binaries for ARM processors running the Android operating system.
+It can also build a .so
library that can be loaded by an Android application
+using the supporting packages in the mobile subrepository.
+A brief description of the plans for this experimental port are available
+here.
+
+The previous release introduced Native Client (NaCl) support for the 32-bit x86
+(GOARCH=386
)
+and 64-bit x86 using 32-bit pointers (GOARCH=amd64p32).
+The 1.4 release adds NaCl support for ARM (GOARCH=arm).
+
+This release adds support for the Plan 9 operating system on AMD64 processors,
+provided the kernel supports the nsec
system call and uses 4K pages.
+
+The unsafe
package allows one
+to defeat Go's type system by exploiting internal details of the implementation
+or machine representation of data.
+It was never explicitly specified what use of unsafe
meant
+with respect to compatibility as specified in the
+Go compatibility guidelines.
+The answer, of course, is that we can make no promise of compatibility
+for code that does unsafe things.
+
+We have clarified this situation in the documentation included in the release.
+The Go compatibility guidelines and the
+docs for the unsafe
package
+are now explicit that unsafe code is not guaranteed to remain compatible.
+
+Updating: Nothing technical has changed; this is just a clarification +of the documentation. +
+ + ++Prior to Go 1.4, the runtime (garbage collector, concurrency support, interface management, +maps, slices, strings, ...) was mostly written in C, with some assembler support. +In 1.4, much of the code has been translated to Go so that the garbage collector can scan +the stacks of programs in the runtime and get accurate information about what variables +are active. +This change was large but should have no semantic effect on programs. +
+ ++This rewrite allows the garbage collector in 1.4 to be fully precise, +meaning that it is aware of the location of all active pointers in the program. +This means the heap will be smaller as there will be no false positives keeping non-pointers alive. +Other related changes also reduce the heap size, which is smaller by 10%-30% overall +relative to the previous release. +
+ ++A consequence is that stacks are no longer segmented, eliminating the "hot split" problem. +When a stack limit is reached, a new, larger stack is allocated, all active frames for +the goroutine are copied there, and any pointers into the stack are updated. +Performance can be noticeably better in some cases and is always more predictable. +Details are available in the design document. +
+ ++The use of contiguous stacks means that stacks can start smaller without triggering performance issues, +so the default starting size for a goroutine's stack in 1.4 has been reduced from 8192 bytes to 2048 bytes. +
+ ++As preparation for the concurrent garbage collector scheduled for the 1.5 release, +writes to pointer values in the heap are now done by a function call, +called a write barrier, rather than directly from the function updating the value. +In this next release, this will permit the garbage collector to mediate writes to the heap while it is running. +This change has no semantic effect on programs in 1.4, but was +included in the release to test the compiler and the resulting performance. +
+ ++The implementation of interface values has been modified. +In earlier releases, the interface contained a word that was either a pointer or a one-word +scalar value, depending on the type of the concrete object stored. +This implementation was problematical for the garbage collector, +so as of 1.4 interface values always hold a pointer. +In running programs, most interface values were pointers anyway, +so the effect is minimal, but programs that store integers (for example) in +interfaces will see more allocations. +
+ +
+As of Go 1.3, the runtime crashes if it finds a memory word that should contain
+a valid pointer but instead contains an obviously invalid pointer (for example, the value 3).
+Programs that store integers in pointer values may run afoul of this check and crash.
+In Go 1.4, setting the GODEBUG
variable
+invalidptr=0
disables
+the crash as a workaround, but we cannot guarantee that future releases will be
+able to avoid the crash; the correct fix is to rewrite code not to alias integers and pointers.
+
+The language accepted by the assemblers cmd/5a
, cmd/6a
+and cmd/8a
has had several changes,
+mostly to make it easier to deliver type information to the runtime.
+
+First, the textflag.h
file that defines flags for TEXT
directives
+has been copied from the linker source directory to a standard location so it can be
+included with the simple directive
+
+#include "textflag.h" ++ +
+The more important changes are in how assembler source can define the necessary
+type information.
+For most programs it will suffice to move data
+definitions (DATA
and GLOBL
directives)
+out of assembly into Go files
+and to write a Go declaration for each assembly function.
+The assembly document describes what to do.
+
+Updating:
+Assembly files that include textflag.h
from its old
+location will still work, but should be updated.
+For the type information, most assembly routines will need no change,
+but all should be examined.
+Assembly source files that define data,
+functions with non-empty stack frames, or functions that return pointers
+need particular attention.
+A description of the necessary (but simple) changes
+is in the assembly document.
+
+More information about these changes is in the assembly document. +
+ ++The release schedules for the GCC and Go projects do not coincide. +GCC release 4.9 contains the Go 1.2 version of gccgo. +The next release, GCC 5, will likely have the Go 1.4 version of gccgo. +
+ ++Go's package system makes it easy to structure programs into components with clean boundaries, +but there are only two forms of access: local (unexported) and global (exported). +Sometimes one wishes to have components that are not exported, +for instance to avoid acquiring clients of interfaces to code that is part of a public repository +but not intended for use outside the program to which it belongs. +
+ +
+The Go language does not have the power to enforce this distinction, but as of Go 1.4 the
+go
command introduces
+a mechanism to define "internal" packages that may not be imported by packages outside
+the source subtree in which they reside.
+
+To create such a package, place it in a directory named internal
or in a subdirectory of a directory
+named internal.
+When the go
command sees an import of a package with internal
in its path,
+it verifies that the package doing the import
+is within the tree rooted at the parent of the internal
directory.
+For example, a package .../a/b/c/internal/d/e/f
+can be imported only by code in the directory tree rooted at .../a/b/c
.
+It cannot be imported by code in .../a/b/g
or in any other repository.
+
+For Go 1.4, the internal package mechanism is enforced for the main Go repository; +from 1.5 and onward it will be enforced for any repository. +
+ ++Full details of the mechanism are in +the design document. +
+ +
+Code often lives in repositories hosted by public services such as github.com
,
+meaning that the import paths for packages begin with the name of the hosting service,
+github.com/rsc/pdf
for example.
+One can use
+an existing mechanism
+to provide a "custom" or "vanity" import path such as
+rsc.io/pdf
, but
+that creates two valid import paths for the package.
+That is a problem: one may inadvertently import the package through the two
+distinct paths in a single program, which is wasteful;
+miss an update to a package because the path being used is not recognized to be
+out of date;
+or break clients using the old path by moving the package to a different hosting service.
+
+Go 1.4 introduces an annotation for package clauses in Go source that identify a canonical
+import path for the package.
+If an import is attempted using a path that is not canonical,
+the go
command
+will refuse to compile the importing package.
+
+The syntax is simple: put an identifying comment on the package line. +For our example, the package clause would read: +
+ ++package pdf // import "rsc.io/pdf" ++ +
+With this in place,
+the go
command will
+refuse to compile a package that imports github.com/rsc/pdf
,
+ensuring that the code can be moved without breaking users.
+
+The check is at build time, not download time, so if go
get
+fails because of this check, the mis-imported package has been copied to the local machine
+and should be removed manually.
+
+To complement this new feature, a check has been added at update time to verify
+that the local package's remote repository matches that of its custom import.
+The go
get
-u
command will fail to
+update a package if its remote repository has changed since it was first
+downloaded.
+The new -f
flag overrides this check.
+
+Further information is in +the design document. +
+ +
+The Go project subrepositories (code.google.com/p/go.tools
and so on)
+are now available under custom import paths replacing code.google.com/p/go.
with golang.org/x/
,
+as in golang.org/x/tools
.
+We will add canonical import comments to the code around June 1, 2015,
+at which point Go 1.4 and later will stop accepting the old code.google.com
paths.
+
+Updating: All code that imports from subrepositories should change
+to use the new golang.org
paths.
+Go 1.0 and later can resolve and import the new paths, so updating will not break
+compatibility with older releases.
+Code that has not updated will stop compiling with Go 1.4 around June 1, 2015.
+
+The go
command has a new subcommand,
+go generate
,
+to automate the running of tools to generate source code before compilation.
+For example, it can be used to run the yacc
+compiler-compiler on a .y
file to produce the Go source file implementing the grammar,
+or to automate the generation of String
methods for typed constants using the new
+stringer
+tool in the golang.org/x/tools
subrepository.
+
+For more information, see the +design document. +
+ +
+Build constraints, also known as build tags, control compilation by including or excluding files
+(see the documentation /go/build
).
+Compilation can also be controlled by the name of the file itself by "tagging" the file with
+a suffix (before the .go
or .s
extension) with an underscore
+and the name of the architecture or operating system.
+For instance, the file gopher_arm.go
will only be compiled if the target
+processor is an ARM.
+
+Before Go 1.4, a file called just arm.go
was similarly tagged, but this behavior
+can break sources when new architectures are added, causing files to suddenly become tagged.
+In 1.4, therefore, a file will be tagged in this manner only if the tag (architecture or operating
+system name) is preceded by an underscore.
+
+Updating: Packages that depend on the old behavior will no longer compile correctly.
+Files with names like windows.go
or amd64.go
should either
+have explicit build tags added to the source or be renamed to something like
+os_windows.go
or support_amd64.go
.
+
+There were a number of minor changes to the
+cmd/go
+command worth noting.
+
cgo
is being used to build the package,
+the go
command now refuses to compile C source files,
+since the relevant C compilers
+(6c
etc.)
+are intended to be removed from the installation in some future release.
+(They are used today only to build part of the runtime.)
+It is difficult to use them correctly in any case, so any extant uses are likely incorrect,
+so we have disabled them.
+go
test
+subcommand has a new flag, -o
, to set the name of the resulting binary,
+corresponding to the same flag in other subcommands.
+The non-functional -file
flag has been removed.
+go
test
+subcommand will compile and link all *_test.go
files in the package,
+even when there are no Test
functions in them.
+It previously ignored such files.
+go
build
+subcommand's
+-a
flag has been changed for non-development installations.
+For installations running a released distribution, the -a
flag will no longer
+rebuild the standard library and commands, to avoid overwriting the installation's files.
+
+In the main Go source repository, the source code for the packages was kept in
+the directory src/pkg
, which made sense but differed from
+other repositories, including the Go subrepositories.
+In Go 1.4, the pkg
level of the source tree is now gone, so for example
+the fmt
package's source, once kept in
+directory src/pkg/fmt
, now lives one level higher in src/fmt
.
+
+Updating: Tools like godoc
that discover source code
+need to know about the new location. All tools and services maintained by the Go team
+have been updated.
+
+Due to runtime changes in this release, Go 1.4 requires SWIG 3.0.3. +
+ +
+The standard repository's top-level misc
directory used to contain
+Go support for editors and IDEs: plugins, initialization scripts and so on.
+Maintaining these was becoming time-consuming
+and needed external help because many of the editors listed were not used by
+members of the core team.
+It also required us to make decisions about which plugin was best for a given
+editor, even for editors we do not use.
+
+The Go community at large is much better suited to managing this information. +In Go 1.4, therefore, this support has been removed from the repository. +Instead, there is a curated, informative list of what's available on +a wiki page. +
+ ++Most programs will run about the same speed or slightly faster in 1.4 than in 1.3; +some will be slightly slower. +There are many changes, making it hard to be precise about what to expect. +
+ ++As mentioned above, much of the runtime was translated to Go from C, +which led to some reduction in heap sizes. +It also improved performance slightly because the Go compiler is better +at optimization, due to things like inlining, than the C compiler used to build +the runtime. +
+ ++The garbage collector was sped up, leading to measurable improvements for +garbage-heavy programs. +On the other hand, the new write barriers slow things down again, typically +by about the same amount but, depending on their behavior, some programs +may be somewhat slower or faster. +
+ ++Library changes that affect performance are documented below. +
+ ++There are no new packages in this release. +
+ +
+The Scanner
type in the
+bufio
package
+has had a bug fixed that may require changes to custom
+split functions
.
+The bug made it impossible to generate an empty token at EOF; the fix
+changes the end conditions seen by the split function.
+Previously, scanning stopped at EOF if there was no more data.
+As of 1.4, the split function will be called once at EOF after input is exhausted,
+so the split function can generate a final empty token
+as the documentation already promised.
+
+Updating: Custom split functions may need to be modified to +handle empty tokens at EOF as desired. +
+ +
+The syscall
package is now frozen except
+for changes needed to maintain the core repository.
+In particular, it will no longer be extended to support new or different system calls
+that are not used by the core.
+The reasons are described at length in a
+separate document.
+
+A new subrepository, golang.org/x/sys, +has been created to serve as the location for new developments to support system +calls on all kernels. +It has a nicer structure, with three packages that each hold the implementation of +system calls for one of +Unix, +Windows and +Plan 9. +These packages will be curated more generously, accepting all reasonable changes +that reflect kernel interfaces in those operating systems. +See the documentation and the article mentioned above for more information. +
+ +
+Updating: Existing programs are not affected as the syscall
+package is largely unchanged from the 1.3 release.
+Future development that requires system calls not in the syscall
package
+should build on golang.org/x/sys
instead.
+
+The following list summarizes a number of minor changes to the library, mostly additions. +See the relevant package documentation for more information about each change. +
+ +archive/zip
package's
+Writer
now supports a
+Flush
method.
+compress/flate
,
+compress/gzip
,
+and compress/zlib
+packages now support a Reset
method
+for the decompressors, allowing them to reuse buffers and improve performance.
+The compress/gzip
package also has a
+Multistream
method to control support
+for multistream files.
+crypto
package now has a
+Signer
interface, implemented by the
+PrivateKey
types in
+crypto/ecdsa
and
+crypto/rsa
.
+crypto/tls
package
+now supports ALPN as defined in RFC 7301.
+crypto/tls
package
+now supports programmatic selection of server certificates
+through the new CertificateForName
function
+of the Config
struct.
+database/sql
package can now list all registered
+Drivers
.
+debug/dwarf
package now supports
+UnspecifiedType
s.
+encoding/asn1
package,
+optional elements with a default value will now only be omitted if they have that value.
+encoding/csv
package no longer
+quotes empty strings but does quote the end-of-data marker \.
(backslash dot).
+This is permitted by the definition of CSV and allows it to work better with Postgres.
+encoding/gob
package has been rewritten to eliminate
+the use of unsafe operations, allowing it to be used in environments that do not permit use of the
+unsafe
package.
+For typical uses it will be 10-30% slower, but the delta is dependent on the type of the data and
+in some cases, especially involving arrays, it can be faster.
+There is no functional change.
+encoding/xml
package's
+Decoder
can now report its input offset.
+fmt
package,
+formatting of pointers to maps has changed to be consistent with that of pointers
+to structs, arrays, and so on.
+For instance, &map[string]int{"one":
1}
now prints by default as
+&map[one:
1]
rather than as a hexadecimal pointer value.
+image
package's
+Image
+implementations like
+RGBA
and
+Gray
have specialized
+RGBAAt
and
+GrayAt
methods alongside the general
+At
method.
+image/png
package now has an
+Encoder
+type to control the compression level used for encoding.
+math
package now has a
+Nextafter32
function.
+net/http
package's
+Request
type
+has a new BasicAuth
method
+that returns the username and password from authenticated requests using the
+HTTP Basic Authentication
+Scheme.
+net/http
package's
+Transport
type
+has a new DialTLS
hook
+that allows customizing the behavior of outbound TLS connections.
+net/http/httputil
package's
+ReverseProxy
type
+has a new field,
+ErrorLog
, that
+provides user control of logging.
+os
package
+now implements symbolic links on the Windows operating system
+through the Symlink
function.
+Other operating systems already have this functionality.
+There is also a new Unsetenv
function.
+reflect
package's
+Type
interface
+has a new method, Comparable
,
+that reports whether the type implements general comparisons.
+reflect
package, the
+Value
interface is now three instead of four words
+because of changes to the implementation of interfaces in the runtime.
+This saves memory but has no semantic effect.
+runtime
package
+now implements monotonic clocks on Windows,
+as it already did for the other systems.
+runtime
package's
+Mallocs
counter
+now counts very small allocations that were missed in Go 1.3.
+This may break tests using ReadMemStats
+or AllocsPerRun
+due to the more accurate answer.
+runtime
package,
+an array PauseEnd
+has been added to the
+MemStats
+and GCStats
structs.
+This array is a circular buffer of times when garbage collection pauses ended.
+The corresponding pause durations are already recorded in
+PauseNs
+runtime/race
package
+now supports FreeBSD, which means the
+go
command's -race
+flag now works on FreeBSD.
+sync/atomic
package
+has a new type, Value
.
+Value
provides an efficient mechanism for atomic loads and
+stores of values of arbitrary type.
+syscall
package's
+implementation on Linux, the
+Setuid
+and Setgid
have been disabled
+because those system calls operate on the calling thread, not the whole process, which is
+different from other platforms and not the expected result.
+testing
package
+has a new facility to provide more control over running a set of tests.
+If the test code contains a function
+
+func TestMain(m *testing.M
)
+
+
+that function will be called instead of running the tests directly.
+The M
struct contains methods to access and run the tests.
+testing
package,
+a new Coverage
+function reports the current test coverage fraction,
+enabling individual tests to report how much they are contributing to the
+overall coverage.
+text/scanner
package's
+Scanner
type
+has a new function,
+IsIdentRune
,
+allowing one to control the definition of an identifier when scanning.
+text/template
package's boolean
+functions eq
, lt
, and so on have been generalized to allow comparison
+of signed and unsigned integers, simplifying their use in practice.
+(Previously one could only compare values of the same signedness.)
+All negative values compare less than all unsigned values.
+time
package now uses the standard symbol for the micro prefix,
+the micro symbol (U+00B5 'µ'), to print microsecond durations.
+ParseDuration
still accepts us
+but the package no longer prints microseconds as us
.
+unsafe
. Packages that import
+unsafe
+may depend on internal properties of the Go implementation.
+We reserve the right to make changes to the implementation
+that may break such programs.
+@@ -145,13 +153,28 @@ developed software based on Go 1.
Code in sub-repositories of the main go tree, such as -code.google.com/p/go.net, +golang.org/x/net, 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.
+
+It is impossible to guarantee long-term compatibility with operating
+system interfaces, which are changed by outside parties.
+The syscall
package
+is therefore outside the purview of the guarantees made here.
+As of Go version 1.4, the syscall
package is frozen.
+Any evolution of the system call interface must be supported elsewhere,
+such as in the
+go.sys subrepository.
+For details and background, see
+this document.
+
diff --git a/doc/go_faq.html b/doc/go_faq.html index f2082ef5b..6b77f1c1e 100644 --- a/doc/go_faq.html +++ b/doc/go_faq.html @@ -228,7 +228,7 @@ document server running in a production configuration on
-Other examples include the Vitess
+Other examples include the Vitess
system for large-scale SQL installations and Google's download server, dl.google.com
,
which delivers Chrome binaries and other large installables such as apt-get
packages.
@@ -889,6 +889,11 @@ type is generic; if you care about how many bits an integer holds, Go
encourages you to be explicit.
+A blog post, title Constants, +explores this topic in more detail. +
+@@ -971,7 +976,7 @@ It is a handy reference for people doing code reviews for Go projects. How do I submit patches to the Go libraries?
-The library sources are in go/src/pkg
.
+The library sources are in the src
directory of the repository.
If you want to make a significant change, please discuss on the mailing list before embarking.
-The Go project, hosted by Google Code at -code.google.com/p/go, -uses Mercurial as its version control system. -When the project launched, -Google Code supported only Subversion and Mercurial. -Mercurial was a better choice because of its plugin mechanism -that allowed us to create the "codereview" plugin to connect -the project to the excellent code review tools at -codereview.appspot.com. -
- --Programmers who work -with the Go project's source rather than release downloads sometimes -ask for the project to switch to git. -That would be possible, but it would be a lot of work and -would also require reimplementing the codereview plugin. -Given that Mercurial works today, with code review support, -combined with the Go project's mostly linear, non-branching use of -version control, a switch to git doesn't seem worthwhile. -
-@@ -1351,7 +1330,7 @@ to speed it up.
-Go's goroutine scheduler is not as good as it needs to be. In future, it
+Go's goroutine scheduler is not as good as it needs to be. In the future, it
should recognize such cases and optimize its use of OS threads. For now,
GOMAXPROCS
should be set on a per-application basis.
fmt
package.
+the formatting tests for the fmt
package.
@@ -1590,30 +1569,40 @@ and uses a variant of the Plan 9 loader to generate ELF/Mach-O/PE binaries.
-We considered writing gc
, the original Go compiler, in Go itself but
+We considered using LLVM for gc
but we felt it was too large and
+slow to meet our performance goals.
+
+We also considered writing gc
, 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. Gccgo
, 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 the go
package
-and a type checker is in the works.)
+consider writing a compiler in Go.
+A plan to do that by machine translation of the existing compiler is under development.
+A separate document
+explains the reason for this approach.
-We also considered using LLVM for gc
but we felt it was too large and
-slow to meet our performance goals.
+That plan aside,
+Go is a
+fine language in which to implement a self-hosting compiler: a native lexer and
+parser are already available in the go
package
+and a separate type checking
+package
+has also been written.
-Again due to bootstrapping issues, the run-time code is mostly in C (with a
-tiny bit of assembler) although Go is capable of implementing most of
-it now. Gccgo
's run-time support uses glibc
.
-Gc
uses a custom library to keep the footprint under
+Again due to bootstrapping issues, the run-time code was originally written mostly in C (with a
+tiny bit of assembler) although much of it has been translated to Go since then
+and one day all of it might be (except for the assembler bits).
+Gccgo
's run-time support uses glibc
.
+Gc
uses a custom C library to keep the footprint under
control; it is
compiled with a version of the Plan 9 C compiler that supports
resizable stacks for goroutines.
@@ -1637,8 +1626,8 @@ A simple C "hello, world" program compiled and linked statically using gcc
on Linux is around 750 kB,
including an implementation of printf
.
An equivalent Go program using fmt.Printf
-is around 1.2 MB, but
-that includes more powerful run-time support.
+is around 1.9 MB, but
+that includes more powerful run-time support and type information.
The presence of an unused variable may indicate a bug, while -unused imports just slow down compilation. -Accumulate enough unused imports in your code tree and -things can get very slow. -For these reasons, Go allows neither. +unused imports just slow down compilation, +an effect that can become substantial as a program accumulates +code and programmers over time. +For these reasons, Go refuses to compile programs with unused +variables or imports, +trading short-term convenience for long-term build speed and +program clarity.
-When developing code, it's common to create these situations +Still, when developing code, it's common to create these situations temporarily and it can be annoying to have to edit them out before the program will compile.
@@ -1695,6 +1687,14 @@ func main() { } ++Nowadays, most Go programmers use a tool, +goimports, +which automatically rewrites a Go source file to have the correct imports, +eliminating the unused imports issue in practice. +This program is easily connected to most editors to run automatically when a Go source file is written. +
++Programs that modify data being simultaneously accessed by multiple goroutines +must serialize such access. +
+ +
+To serialize access, protect the data with channel operations or other synchronization primitives
+such as those in the sync
+and sync/atomic
packages.
+
+If you must read the rest of this document to understand the behavior of your program, +you are being too clever. +
+ ++Don't be clever. +
+
diff --git a/doc/go_spec.html b/doc/go_spec.html
index 660c8535e..ca0deb56a 100644
--- a/doc/go_spec.html
+++ b/doc/go_spec.html
@@ -1,6 +1,6 @@
@@ -479,7 +479,7 @@ Interpreted string literals are character sequences between double
quotes ""
. The text between the quotes,
which may not contain newlines, forms the
value of the literal, with backslash escapes interpreted as they
-are in rune literals (except that \'
is illegal and
+are in rune literals (except that \'
is illegal and
\"
is legal), with the same restrictions.
The three-digit octal (\
nnn)
and two-digit hexadecimal (\x
nn) escapes represent individual
@@ -577,7 +577,7 @@ Numeric constants represent values of arbitrary precision and do not overflow.
-Constants may be typed or untyped.
+Constants may be typed or untyped.
Literal constants, true
, false
, iota
,
and certain constant expressions
containing only untyped constant operands are untyped.
@@ -597,6 +597,17 @@ can be given the types float32
, float64
, or uint
not
int32
or string
.
+An untyped constant has a default type which is the type to which the
+constant is implicitly converted in contexts where a typed value is required,
+for instance, in a short variable declaration
+such as i := 0
where there is no explicit type.
+The default type of an untyped constant is bool
, rune
,
+int
, float64
, complex128
or string
+respectively, depending on whether it is a boolean, rune, integer, floating-point,
+complex, or string constant.
+
There are no constants denoting the IEEE-754 infinity and not-a-number values,
but the math
package's
@@ -636,6 +647,65 @@ of evaluating constant
expressions.
+A variable is a storage location for holding a value. +The set of permissible values is determined by the +variable's type. +
+ +
+A variable declaration
+or, for function parameters and results, the signature
+of a function declaration
+or function literal reserves
+storage for a named variable.
+
+Calling the built-in function new
+or taking the address of a composite literal
+allocates storage for a variable at run time.
+Such an anonymous variable is referred to via a (possibly implicit)
+pointer indirection.
+
+Structured variables of array, slice, +and struct types have elements and fields that may +be addressed individually. Each such element +acts like a variable. +
+ +
+The static type (or just type) of a variable is the
+type given in its declaration, the type provided in the
+new
call or composite literal, or the type of
+an element of a structured variable.
+Variables of interface type also have a distinct dynamic type,
+which is the concrete type of the value assigned to the variable at run time
+(unless the value is the predeclared identifier nil
,
+which has no type).
+The dynamic type may vary during execution but values stored in interface
+variables are always assignable
+to the static type of the variable.
+
+var x interface{} // x is nil and has static type interface{} +var v *T // v has value nil, static type *T +x = 42 // x has value 42 and dynamic type int +x = v // x has value (*T)(nil) and dynamic type *T ++ +
+A variable's value is retrieved by referring to the variable in an +expression; it is the most recent value +assigned to the variable. +If a variable has not yet been assigned a value, its value is the +zero value for its type. +
+ +@@ -661,17 +731,6 @@ interface, slice, map, and channel types—may be constructed using type literals.
--The static type (or just type) of a variable is the -type defined by its declaration. Variables of interface type -also have a distinct dynamic type, which -is the actual type of the value stored in the variable at run time. -The dynamic type may vary during execution but is always -assignable -to the static type of the interface variable. For non-interface -types, the dynamic type is always the static type. -
-
Each type T
has an underlying type: If T
is one of the predeclared boolean, numeric, or string types, or a type literal,
@@ -1027,14 +1086,14 @@ struct {
-A pointer type denotes the set of all pointers to variables of a given
+A pointer type denotes the set of all pointers to variables of a given
type, called the base type of the pointer.
The value of an uninitialized pointer is nil
.
PointerType = "*" BaseType . -BaseType = Type . +BaseType = Type .
@@ -1154,11 +1213,11 @@ interface{}Similarly, consider this interface specification, which appears within a type declaration -to define an interface called
Lock
: +to define an interface calledLocker
:-type Lock interface { +type Locker interface { Lock() Unlock() } @@ -1174,28 +1233,35 @@ func (p T) Unlock() { … }-they implement the
+Lock
interface as well +they implement theLocker
interface as well as theFile
interface.-An interface may use an interface type name
T
-in place of a method specification. -The effect, called embedding an interface, -is equivalent to enumerating the methods ofT
explicitly -in the interface. +An interfaceT
may use a (possibly qualified) interface type +nameE
in place of a method specification. This is called +embedding interfaceE
inT
; it adds +all (exported and non-exported) methods ofE
to the interface +T
.-type ReadWrite interface { +type ReadWriter interface { Read(b Buffer) bool Write(b Buffer) bool } type File interface { - ReadWrite // same as enumerating the methods in ReadWrite - Lock // same as enumerating the methods in Lock + ReadWriter // same as adding the methods of ReadWriter + Locker // same as adding the methods of Locker Close() } + +type LockedFile interface { + Locker + File // illegal: Lock, Unlock not unique + Lock() // illegal: Lock not unique +}@@ -1443,7 +1509,7 @@ is different from
[]string
.Assignability
-A value
@@ -1875,9 +1941,10 @@ func (tz TimeZone) String() string {x
is assignable to a variable of typeT
+A valuex
is assignable to a variable of typeT
("x
is assignable toT
") in any of these cases:Variable declarations
-A variable declaration creates a variable, binds an identifier to it and -gives it a type and optionally an initial value. +A variable declaration creates one or more variables, binds corresponding +identifiers to them, and gives each a type and an initial value.
+VarDecl = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) . VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) . @@ -1898,22 +1965,27 @@ var _, found = entries[name] // map lookup; only interested in "found"If a list of expressions is given, the variables are initialized -by assigning the expressions to the variables -in order; all expressions must be consumed and all variables initialized from them. +with the expressions following the rules for assignments. Otherwise, each variable is initialized to its zero value.
-If the type is present, each variable is given that type. -Otherwise, the types are deduced from the assignment -of the expression list. +If a type is present, each variable is given that type. +Otherwise, each variable is given the type of the corresponding +initialization value in the assignment. +If that value is an untyped constant, it is first +converted to its default type; +if it is an untyped boolean value, it is first converted to type
-bool
. +The predeclared valuenil
cannot be used to initialize a variable +with no explicit type.-If the type is absent and the corresponding expression evaluates to an -untyped constant, the type of the declared variable -is as described in §Assignments. -
++var d = math.Sin(0.5) // d is int64 +var i = 42 // i is int +var t, ok = x.(T) // t is T, ok is bool +var n = nil // illegal +Implementation restriction: A compiler may make it illegal to declare a variable @@ -2029,13 +2101,14 @@ and associates the method with the receiver's base type.
MethodDecl = "func" Receiver MethodName ( Function | Signature ) . -Receiver = "(" [ identifier ] [ "*" ] BaseTypeName ")" . -BaseTypeName = identifier . +Receiver = Parameters .-The receiver type must be of the form
T
or*T
where -T
is a type name. The type denoted byT
is called +The receiver is specified via an extra parameter section preceeding the method +name. That parameter section must declare a single parameter, the receiver. +Its type must be of the formT
or*T
(possibly using +parentheses) whereT
is a type name. The type denoted byT
is called the receiver base type; 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 bound to the base type and the method name @@ -2117,9 +2190,9 @@ operand only on the left-hand side of an assignment.-Operand = Literal | OperandName | MethodExpr | "(" Expression ")" . -Literal = BasicLit | CompositeLit | FunctionLit . -BasicLit = int_lit | float_lit | imaginary_lit | rune_lit | string_lit . +Operand = Literal | OperandName | MethodExpr | "(" Expression ")" . +Literal = BasicLit | CompositeLit | FunctionLit . +BasicLit = int_lit | float_lit | imaginary_lit | rune_lit | string_lit . OperandName = identifier | QualifiedIdent.@@ -2241,7 +2314,8 @@ For array and slice literals the following rules apply:Taking the address of a composite literal -generates a pointer to a unique instance of the literal's value. +generates a pointer to a unique variable initialized +with the literal's value.
var pointer *Point3D = &Point3D{y: 1000} @@ -2375,12 +2449,11 @@ Primary expressions are the operands for unary and binary expressions. PrimaryExpr = Operand | Conversion | - BuiltinCall | PrimaryExpr Selector | PrimaryExpr Index | PrimaryExpr Slice | PrimaryExpr TypeAssertion | - PrimaryExpr Call . + PrimaryExpr Arguments . Selector = "." identifier . Index = "[" Expression "]" . @@ -2388,8 +2461,7 @@ Slice = "[" ( [ Expression ] ":" [ Expression ] ) | ( [ Expression ] ":" Expression ":" Expression ) "]" . TypeAssertion = "." "(" Type ")" . -Call = "(" [ ArgumentList [ "," ] ] ")" . -ArgumentList = ExpressionList [ "..." ] . +Arguments = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" .@@ -2449,30 +2521,40 @@ The following rules apply to selectors:-
- For a value
+x
of typeT
or*T
-whereT
is not an interface type, +whereT
is not a pointer or interface type,x.f
denotes the field or method at the shallowest depth inT
where there is such anf
. If there is not exactly onef
with shallowest depth, the selector expression is illegal.- -For a variable
+ +x
of typeI
whereI
+For a valuex
of typeI
whereI
is an interface type,x.f
denotes the actual method with name -f
of the value assigned tox
. +f
of the dynamic value ofx
. If there is no method with namef
in the method set ofI
, the selector expression is illegal.- +As an exception, if the type of
+x
is a named pointer type +and(*x).f
is a valid selector expression denoting a field +(but not a method),x.f
is shorthand for(*x).f
. +- In all other cases,
+x.f
is illegal.- If
+x
is of pointer type and has the valuenil
andx.f
denotes a struct field, assigning to or evaluatingx.f
causes a run-time panic.- If
x
is of interface type and has the valuenil
, calling or @@ -2481,18 +2563,6 @@ causes a run-time panic.-Selectors automatically dereference -pointers to structs. -If
-x
is a pointer to a struct,x.y
-is shorthand for(*x).y
; if the fieldy
-is also a pointer to a struct,x.y.z
is shorthand -for(*(*x).y).z
, and so on. -Ifx
contains an anonymous field of type*A
, -whereA
is also a struct type, -x.f
is shorthand for(*x.A).f
. -For example, given the declarations:
@@ -2502,13 +2572,13 @@ type T0 struct { x int } -func (recv *T0) M0() +func (*T0) M0() type T1 struct { y int } -func (recv T1) M1() +func (T1) M1() type T2 struct { z int @@ -2516,9 +2586,13 @@ type T2 struct { *T0 } -func (recv *T2) M2() +func (*T2) M2() -var p *T2 // with p != nil and p.T0 != nil +type Q *T2 + +var t T2 // with t.T0 != nil +var p *T2 // with p != nil and (*p).T0 != nil +var q Q = p@@ -2526,13 +2600,254 @@ one may write:
-p.z // (*p).z -p.y // ((*p).T1).y -p.x // (*(*p).T0).x +t.z // t.z +t.y // t.T1.y +t.x // (*t.TO).x + +p.z // (*p).z +p.y // (*p).T1.y +p.x // (*(*p).T0).x + +q.x // (*(*q).T0).x (*q).x is a valid field selector + +p.M2() // p.M2() M2 expects *T2 receiver +p.M1() // ((*p).T1).M1() M1 expects T1 receiver +p.M0() // ((&(*p).T0)).M0() M0 expects *T0 receiver, see section on Calls ++ ++but the following is invalid: +
+ ++q.M0() // (*q).M0 is valid but not a field selector ++ + +Method expressions
+ ++If
+ +M
is in the method set of typeT
, +T.M
is a function that is callable as a regular function +with the same arguments asM
prefixed by an additional +argument that is the receiver of the method. ++MethodExpr = ReceiverType "." MethodName . +ReceiverType = TypeName | "(" "*" TypeName ")" | "(" ReceiverType ")" . ++ ++Consider a struct type
+ +T
with two methods, +Mv
, whose receiver is of typeT
, and +Mp
, whose receiver is of type*T
. ++type T struct { + a int +} +func (tv T) Mv(a int) int { return 0 } // value receiver +func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver + +var t T ++ ++The expression +
+ ++T.Mv ++ ++yields a function equivalent to
+ +Mv
but +with an explicit receiver as its first argument; it has signature ++func(tv T, a int) int ++ ++That function may be called normally with an explicit receiver, so +these five invocations are equivalent: +
+ ++t.Mv(7) +T.Mv(t, 7) +(T).Mv(t, 7) +f1 := T.Mv; f1(t, 7) +f2 := (T).Mv; f2(t, 7) ++ ++Similarly, the expression +
+ ++(*T).Mp ++ ++yields a function value representing
+ +Mp
with signature ++func(tp *T, f float32) float32 ++ ++For a method with a value receiver, one can derive a function +with an explicit pointer receiver, so +
+ ++(*T).Mv ++ ++yields a function value representing
+ +Mv
with signature ++func(tv *T, a int) int ++ ++Such a function indirects through the receiver to create a value +to pass as the receiver to the underlying method; +the method does not overwrite the value whose address is passed in +the function call. +
+ ++The final case, a value-receiver function for a pointer-receiver method, +is illegal because pointer-receiver methods are not in the method set +of the value type. +
+ ++Function values derived from methods are called with function call syntax; +the receiver is provided as the first argument to the call. +That is, given
+ +f := T.Mv
,f
is invoked +asf(t, 7)
nott.f(7)
. +To construct a function that binds the receiver, use a +function literal or +method value. ++It is legal to derive a function value from a method of an interface type. +The resulting function takes an explicit receiver of that interface type. +
+ +Method values
+ ++If the expression
+ +x
has static typeT
and +M
is in the method set of typeT
, +x.M
is called a method value. +The method valuex.M
is a function value that is callable +with the same arguments as a method call ofx.M
. +The expressionx
is evaluated and saved during the evaluation of the +method value; the saved copy is then used as the receiver in any calls, +which may be executed later. ++The type
+ +T
may be an interface or non-interface type. ++As in the discussion of method expressions above, +consider a struct type
+ +T
with two methods, +Mv
, whose receiver is of typeT
, and +Mp
, whose receiver is of type*T
. ++type T struct { + a int +} +func (tv T) Mv(a int) int { return 0 } // value receiver +func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver + +var t T +var pt *T +func makeT() T ++ ++The expression +
+ ++t.Mv ++ ++yields a function value of type +
+ ++func(int) int ++ ++These two invocations are equivalent: +
+ ++t.Mv(7) +f := t.Mv; f(7) ++ ++Similarly, the expression +
+ ++pt.Mp ++ ++yields a function value of type +
+ ++func(float32) float32 +-p.M2() // (*p).M2() -p.M1() // ((*p).T1).M1() -p.M0() // ((*p).T0).M0() ++As with selectors, a reference to a non-interface method with a value receiver +using a pointer will automatically dereference that pointer:
+ +pt.Mv
is equivalent to(*pt).Mv
. ++As with method calls, a reference to a non-interface method with a pointer receiver +using an addressable value will automatically take the address of that value:
+ +t.Mp
is equivalent to(&t).Mp
. ++f := t.Mv; f(7) // like t.Mv(7) +f := pt.Mp; f(7) // like pt.Mp(7) +f := pt.Mv; f(7) // like (*pt).Mv(7) +f := t.Mp; f(7) // like (&t).Mp(7) +f := makeT().Mp // invalid: result of makeT() is not addressable ++ ++Although the examples above use non-interface types, it is also legal to create a method value +from a value of interface type. +
+ ++var i interface { M(int) } = myVal +f := i.M; f(7) // like i.M(7)@@ -2625,7 +2940,7 @@ Otherwisea[x]
is illegal.An index expression on a map
a
of typemap[K]V
-may be used in an assignment or initialization of the special form +used in an assignment or initialization of the special form@@ -2635,11 +2950,9 @@ var v, ok = a[x]-where the result of the index expression is a pair of values with types -
(V, bool)
. In this form, the value ofok
is +yields an additional untyped boolean value. The value ofok
istrue
if the keyx
is present in the map, and -false
otherwise. The value ofv
is the value -a[x]
as in the single-result form. +false
otherwise.@@ -2824,7 +3137,7 @@ r := y.(io.Reader) // r has type io.Reader and y must implement both I and i
-If a type assertion is used in an assignment or initialization of the form +A type assertion used in an assignment or initialization of the special form
@@ -2834,13 +3147,10 @@ var v, ok = x.(T)
-the result of the assertion is a pair of values with types (T, bool)
.
-If the assertion holds, the expression returns the pair (x.(T), true)
;
-otherwise, the expression returns (Z, false)
where Z
-is the zero value for type T
.
+yields an additional untyped boolean value. The value of ok
is true
+if the assertion holds. Otherwise it is false
and the value of v
is
+the zero value for type T
.
No run-time panic occurs in this case.
-The type assertion in this construct thus acts like a function call
-returning a value and a boolean indicating success.
math.Atan2(x, y) // function call var pt *Point -pt.Scale(3.5) // method call with receiver pt +pt.Scale(3.5) // method call with receiver pt
@@ -3375,13 +3685,13 @@ or an array indexing operation of an addressable array.
As an exception to the addressability requirement, x
may also be a
(possibly parenthesized)
composite literal.
-If the evaluation of x
would cause a run-time panic,
+If the evaluation of x
would cause a run-time panic,
then the evaluation of &x
does too.
For an operand x
of pointer type *T
, the pointer
-indirection *x
denotes the value of type T
pointed
+indirection *x
denotes the variable of type T
pointed
to by x
.
If x
is nil
, an attempt to evaluate *x
will cause a run-time panic.
@@ -3422,7 +3732,7 @@ f(<-ch)
-A receive expression used in an assignment or initialization of the form +A receive expression used in an assignment or initialization of the special form
@@ -3432,7 +3742,7 @@ var x, ok = <-ch
-yields an additional result of type bool
reporting whether the
+yields an additional untyped boolean result reporting whether the
communication succeeded. The value of ok
is true
if the value received was delivered by a successful send operation to the
channel, or false
if it is a zero value generated because the
@@ -3440,232 +3750,6 @@ channel is closed and empty.
-If M
is in the method set of type T
,
-T.M
is a function that is callable as a regular function
-with the same arguments as M
prefixed by an additional
-argument that is the receiver of the method.
-
-MethodExpr = ReceiverType "." MethodName . -ReceiverType = TypeName | "(" "*" TypeName ")" | "(" ReceiverType ")" . -- -
-Consider a struct type T
with two methods,
-Mv
, whose receiver is of type T
, and
-Mp
, whose receiver is of type *T
.
-
-type T struct { - a int -} -func (tv T) Mv(a int) int { return 0 } // value receiver -func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver - -var t T -- -
-The expression -
- --T.Mv -- -
-yields a function equivalent to Mv
but
-with an explicit receiver as its first argument; it has signature
-
-func(tv T, a int) int -- -
-That function may be called normally with an explicit receiver, so -these five invocations are equivalent: -
- --t.Mv(7) -T.Mv(t, 7) -(T).Mv(t, 7) -f1 := T.Mv; f1(t, 7) -f2 := (T).Mv; f2(t, 7) -- -
-Similarly, the expression -
- --(*T).Mp -- -
-yields a function value representing Mp
with signature
-
-func(tp *T, f float32) float32 -- -
-For a method with a value receiver, one can derive a function -with an explicit pointer receiver, so -
- --(*T).Mv -- -
-yields a function value representing Mv
with signature
-
-func(tv *T, a int) int -- -
-Such a function indirects through the receiver to create a value -to pass as the receiver to the underlying method; -the method does not overwrite the value whose address is passed in -the function call. -
- --The final case, a value-receiver function for a pointer-receiver method, -is illegal because pointer-receiver methods are not in the method set -of the value type. -
- -
-Function values derived from methods are called with function call syntax;
-the receiver is provided as the first argument to the call.
-That is, given f := T.Mv
, f
is invoked
-as f(t, 7)
not t.f(7)
.
-To construct a function that binds the receiver, use a
-function literal or
-method value.
-
-It is legal to derive a function value from a method of an interface type. -The resulting function takes an explicit receiver of that interface type. -
- -
-If the expression x
has static type T
and
-M
is in the method set of type T
,
-x.M
is called a method value.
-The method value x.M
is a function value that is callable
-with the same arguments as a method call of x.M
.
-The expression x
is evaluated and saved during the evaluation of the
-method value; the saved copy is then used as the receiver in any calls,
-which may be executed later.
-
-The type T
may be an interface or non-interface type.
-
-As in the discussion of method expressions above,
-consider a struct type T
with two methods,
-Mv
, whose receiver is of type T
, and
-Mp
, whose receiver is of type *T
.
-
-type T struct { - a int -} -func (tv T) Mv(a int) int { return 0 } // value receiver -func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver - -var t T -var pt *T -func makeT() T -- -
-The expression -
- --t.Mv -- -
-yields a function value of type -
- --func(int) int -- -
-These two invocations are equivalent: -
- --t.Mv(7) -f := t.Mv; f(7) -- -
-Similarly, the expression -
- --pt.Mp -- -
-yields a function value of type -
- --func(float32) float32 -- -
-As with selectors, a reference to a non-interface method with a value receiver
-using a pointer will automatically dereference that pointer: pt.Mv
is equivalent to (*pt).Mv
.
-
-As with method calls, a reference to a non-interface method with a pointer receiver
-using an addressable value will automatically take the address of that value: t.Mp
is equivalent to (&t).Mp
.
-
-f := t.Mv; f(7) // like t.Mv(7) -f := pt.Mp; f(7) // like pt.Mp(7) -f := pt.Mv; f(7) // like (*pt).Mv(7) -f := t.Mp; f(7) // like (&t).Mp(7) -f := makeT().Mp // invalid: result of makeT() is not addressable -- -
-Although the examples above use non-interface types, it is also legal to create a method value -from a value of interface type. -
- --var i interface { M(int) } = myVal -f := i.M; f(7) // like i.M(7) --
@@ -4055,7 +4139,7 @@ n := map[int]int{a: f()} // n may be {2: 3} or {3: 3}: evaluation order bet
At package level, initialization dependencies override the left-to-right rule for individual initialization expressions, but not for operands within each -expression: +expression:
@@ -4314,7 +4398,7 @@ a[i] = 23An assignment operation
x
op=
-y
where op is a binary arithmetic operation equivalent +y
where op is a binary arithmetic operation is equivalent tox
=
x
opy
but evaluatesx
only once. The op=
construct is a single token. @@ -4332,8 +4416,8 @@ i &^= 1<<n A tuple assignment assigns the individual elements of a multi-valued operation to a list of variables. There are two forms. In the first, the right hand operand is a single multi-valued expression -such as a function evaluation or channel or -map operation or a type assertion. +such as a function call, a channel or +map operation, or a type assertion. The number of operands on the left hand side must match the number of values. For instance, iff
is a function returning two values, @@ -4407,23 +4491,21 @@ to the type of the operand to which it is assigned, with the following special c-
- If an untyped constant +
- + Any typed value may be assigned to the blank identifier. +
+ +- + If an untyped constant is assigned to a variable of interface type or the blank identifier, - the constant is first converted to type -
- -bool
,rune
,int
,float64
, -complex128
orstring
respectively, depending on - whether the value is a boolean, rune, integer, floating-point, complex, or - string constant. -- + the constant is first converted to its + default type. + + +
- - If a left-hand side is the blank identifier, any typed or non-constant - value except for the predeclared identifier -
nil
- may be assigned to it. -- + If an untyped boolean value is assigned to a variable of interface type or + the blank identifier, it is first converted to type
bool
. +If statements
@@ -4678,6 +4760,7 @@ additionally it may specify an init and a post statement, such as an assignment, an increment or decrement statement. The init statement may be a short variable declaration, but the post statement must not. +Variables declared by the init statement are re-used in each iteration.@@ -4713,41 +4796,42 @@ for { S() } is the same as for true { S() } A "for" statement with a "range" clause iterates through all entries of an array, slice, string or map, or values received on a channel. For each entry it assigns iteration values -to corresponding iteration variables and then executes the block. +to corresponding iteration variables if present and then executes the block.-RangeClause = ( ExpressionList "=" | IdentifierList ":=" ) "range" Expression . +RangeClause = [ ExpressionList "=" | IdentifierList ":=" ] "range" Expression .The expression on the right in the "range" clause is called the range expression, which may be an array, pointer to an array, slice, string, map, or channel permitting receive operations. -As with an assignment, the operands on the left must be +As with an assignment, if present 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. In the latter case, -if the second iteration variable is the blank identifier, -the range clause is equivalent to the same clause with only the first variable present. +denote the iteration variables. If the range expression is a channel, at most +one iteration variable is permitted, otherwise there may be up to two. +If the last iteration variable is the blank identifier, +the range clause is equivalent to the same clause without that identifier.
The range expression is evaluated once before beginning the loop, -with one exception. If the range expression is an array or a pointer to an array -and only the first iteration value is present, only the range expression's -length is evaluated; if that length is constant -by definition, +with one exception: if the range expression is an array or a pointer to an array +and at most one iteration variable is present, only the range expression's +length is evaluated; if that length is constant, +by definition the range expression itself will not be evaluated.
Function calls on the left are evaluated once per iteration. -For each iteration, iteration values are produced as follows: +For each iteration, iteration values are produced as follows +if the respective iteration variables are present:
-Range expression 1st value 2nd value (if 2nd variable is present) +Range expression 1st value 2nd value array or slice a [n]E, *[n]E, or []E index i int a[i] E string s string type index i int see below rune @@ -4759,7 +4843,7 @@ channel c chan E, <-chan E element e E
a
, the index iteration
values are produced in increasing order, starting at element index 0.
-If only the first iteration variable is present, the range loop produces
+If at most one iteration variable is present, the range loop produces
iteration values from 0 up to len(a)-1
and does not index into the array
or slice itself. For a nil
slice, the number of iterations is 0.
:=
).
In this case their types are set to the types of the respective iteration values
-and their scope ends at the end of the "for"
+and their scope is the block of the "for"
statement; they are re-used in each iteration.
If the iteration variables are declared outside the "for" statement,
after execution their values will be those of the last iteration.
@@ -4840,6 +4924,9 @@ var ch chan Work = producer()
for w := range ch {
doWork(w)
}
+
+// empty a channel
+for range ch {}
@@ -5242,13 +5329,16 @@ Calls of built-in functions are restricted as for
-Each time the "defer" statement
+Each time a "defer" statement
executes, the function value and parameters to the call are
evaluated as usual
-and saved anew but the actual function body is not executed.
-Instead, deferred functions are executed immediately before
+and saved anew but the actual function is not invoked.
+Instead, deferred functions are invoked immediately before
the surrounding function returns, in the reverse order
they were deferred.
+If a deferred function value evaluates
+to nil
, execution panics
+when the function is invoked, not when the "defer" statement is executed.
@@ -5295,11 +5385,6 @@ so they can only appear in call expressions; they cannot be used as function values.
--BuiltinCall = identifier "(" [ BuiltinArgs [ "," ] ] ")" . -BuiltinArgs = Type [ "," ArgumentList ] | ArgumentList . --
@@ -5378,9 +5463,11 @@ var z complex128
-The built-in function new
takes a type T
and
-returns a value of type *T
.
-The memory is initialized as described in the section on
+The built-in function new
takes a type T
,
+allocates storage for a variable of that type
+at run time, and returns a value of type *T
+pointing to it.
+The variable is initialized as described in the section on
initial values.
-dynamically allocates memory for a variable of type S
,
+allocates storage for a variable of type S
,
initializes it (a=0
, b=0.0
),
and returns a value of type *S
containing the address
-of the memory.
+of the location.
-When memory is allocated to store a value, either through a declaration
-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
+When storage is allocated for a variable,
+either through a declaration or a call of new
, or when
+a new value is created, either through a composite literal or a call
+of make
,
+and no explicit initialization is provided, the variable or value is
+given a default value. Each element of such a variable or value is
set to the zero value for its type: false
for booleans,
0
for integers, 0.0
for floats, ""
for strings, and nil
for pointers, functions, interfaces, slices, channels, and maps.
@@ -5915,20 +6004,42 @@ var t T
-Within a package, package-level variables are initialized according
-to their dependencies: if a variable x
depends on
-a variable y
, x
will be initialized after
-y
.
+Within a package, package-level variables are initialized in
+declaration order but after any of the variables
+they depend on.
+
+More precisely, a package-level variable is considered ready for +initialization if it is not yet initialized and either has +no initialization expression or +its initialization expression has no dependencies on uninitialized variables. +Initialization proceeds by repeatedly initializing the next package-level +variable that is earliest in declaration order and ready for initialization, +until there are no variables ready for initialization. +
+ ++If any variables are still uninitialized when this +process ends, those variables are part of one or more initialization cycles, +and the program is not valid. +
+ ++The declaration order of variables declared in multiple files is determined +by the order in which the files are presented to the compiler: Variables +declared in the first file are declared before any of the variables declared +in the second file, and so on.
Dependency analysis does not rely on the actual values of the
variables, only on lexical references to them in the source,
-analyzed transitively. For instance, a variable x
's
-initialization expression
-may refer to a function whose body refers to variable y
;
-if so, x
depends on y
.
+analyzed transitively. For instance, if a variable x
's
+initialization expression refers to a function whose body refers to
+variable y
then x
depends on y
.
Specifically:
m
is a
method value or
-method expression of the form
+method expression of the form
t.m
, where the (static) type of t
is
not an interface type, and the method m
is in the
method set of t
.
@@ -5950,7 +6061,7 @@ It is immaterial whether the resulting function value
x
depends on a variable
+A variable, function, or method x
depends on a variable
y
if x
's initialization expression or body
(for functions and methods) contains a reference to y
or to a function or method that depends on y
.
@@ -5961,11 +6072,6 @@ or to a function or method that depends on y
.
Dependency analysis is performed per package; only references referring
to variables, functions, and methods declared in the current package
are considered.
-It is an error if variable dependencies form a cycle
-(but dependency cycles containing no variables are permitted).
-If two variables are independent of each other,
-they are initialized in the order they are declared
-in the source, possibly in multiple files, as presented to the compiler.
@@ -5988,8 +6094,6 @@ func f() int {
the initialization order is d
, b
, c
, a
.
-Since b
and c
are independent of each other, they are
-initialized in declaration order (b
before c
).
@@ -6002,7 +6106,7 @@ func init() { … }
-Multiple such functions may be defined, even within a single
+Multiple such functions may be defined, even within a single
source file. The init
identifier is not
declared and thus
init
functions cannot be referred to from anywhere
@@ -6032,6 +6136,12 @@ the init
functions: it will not invoke the next one
until the previous one has returned.
+To ensure reproducible initialization behavior, build systems are encouraged +to present multiple files belonging to the same package in lexical file name +order to a compiler. +
+
@@ -6106,8 +6216,8 @@ type Error interface {
The built-in package unsafe
, known to the compiler,
provides facilities for low-level programming including operations
that violate the type system. A package using unsafe
-must be vetted manually for type safety. The package provides the
-following interface:
+must be vetted manually for type safety and may not be portable.
+The package provides the following interface:
@@ -6122,10 +6232,11 @@ func Sizeof(variable ArbitraryType) uintptr
-Any pointer or value of underlying type uintptr
can be converted to
-a Pointer
type and vice versa.
A Pointer
is a pointer type but a Pointer
value may not be dereferenced.
+Any pointer or value of underlying type uintptr
can be converted to
+a Pointer
type and vice versa.
+The effect of converting between Pointer
and uintptr
is implementation-defined.
diff --git a/doc/gopher/biplane.jpg b/doc/gopher/biplane.jpg new file mode 100644 index 000000000..d5e666f96 Binary files /dev/null and b/doc/gopher/biplane.jpg differ diff --git a/doc/gopher/fiveyears.jpg b/doc/gopher/fiveyears.jpg new file mode 100644 index 000000000..df1064868 Binary files /dev/null and b/doc/gopher/fiveyears.jpg differ diff --git a/doc/help.html b/doc/help.html index a307b2aad..2cc47806c 100644 --- a/doc/help.html +++ b/doc/help.html @@ -24,7 +24,7 @@ Need help with Go? Try these resources.Search the golang-nuts archives and consult the FAQ and -wiki before posting. +wiki before posting.
Go IRC Channel
diff --git a/doc/install-source.html b/doc/install-source.html index 82859b50f..f53deb404 100644 --- a/doc/install-source.html +++ b/doc/install-source.html @@ -241,12 +241,12 @@ provides essential setup instructions for using the Go tools.The source code for several Go tools (including godoc) -is kept in the go.tools repository. +is kept in the go.tools repository. To install all of them, run the
go
get
command:-$ go get code.google.com/p/go.tools/cmd/... +$ go get golang.org/x/tools/cmd/...@@ -254,7 +254,7 @@ Or if you just want to install a specific command (
godoc
in this ca-$ go get code.google.com/p/go.tools/cmd/godoc +$ go get golang.org/x/tools/cmd/godocdiff --git a/doc/install.html b/doc/install.html index 2de04471c..9561fdde2 100644 --- a/doc/install.html +++ b/doc/install.html @@ -6,14 +6,14 @@
Download the Go distribution
- + Download Go Click here to visit the downloads page
-Official binary +Official binary distributions are available for the FreeBSD (release 8 and above), Linux, Mac OS X (Snow Leopard and above), and Windows operating systems and the 32-bit (
386
) and 64-bit (amd64
) x86 processor architectures. @@ -47,7 +47,7 @@ proceeding. If your OS or architecture is not on the list, it's possible thatFreeBSD 8 or later amd64, 386, arm Debian GNU/kFreeBSD not supported; FreeBSD/ARM needs FreeBSD 10 or later Linux 2.6.23 or later with glibc amd64, 386, arm CentOS/RHEL 5.x not supported; no binary distribution for ARM yet - Mac OS X 10.6 or later amd64, 386 use the gcc† that comes with Xcode‡ + Windows XP or later amd64, 386 use MinGW gcc†. No need for cgywin or msys. Windows XP or later amd64, 386 use MinGW gcc†. No need for cygwin or msys. @@ -70,7 +70,7 @@ first remove the existing version.
Linux, Mac OS X, and FreeBSD tarballs
-Download the archive +Download the archive and extract it into
@@ -127,7 +127,7 @@ location./usr/local
, creating a Go tree in/usr/local/go
. For example:Mac OS X package installer
-Download the package file, +Download the package file, open it, and follow the prompts to install the Go tools. The package installs the Go distribution to
@@ -150,7 +150,7 @@ MSI installer that configures your installation automatically./usr/local/go
.MSI installer
-Open the MSI file +Open the MSI file and follow the prompts to install the Go tools. By default, the installer puts the Go distribution in
@@ -164,7 +164,7 @@ command prompts for the change to take effect.c:\Go
.Zip archive
-Download the zip file and extract it into the directory of your choice (we suggest
c:\Go
). +Download the zip file and extract it into the directory of your choice (we suggestc:\Go
).@@ -224,19 +224,12 @@ If you see the "hello, world" message then your Go installation is working.
You're almost done. -You just need to do a little more setup. +You just need to set up your environment.
- -How to Write Go Code -Learn how to set up and use the Go tools - -
- --The How to Write Go Code document -provides essential setup instructions for using the Go tools. +Read the How to Write Go Code document, +which provides essential setup instructions for using the Go tools.
@@ -277,5 +270,3 @@ The official mailing list for discussion of the Go language is Report bugs using the Go issue tracker. - - -- cgit v1.2.3