From d8ebd27297fa7c71a81f38716cc35c565263fa0d Mon Sep 17 00:00:00 2001
From: Channing Kimble-Brown The Go distribution includes a command, named
-" You might have seen early Go talks in which Rob Pike jokes that the idea
-for Go arose while waiting for a large Google server to compile. That
-really was the motivation for Go: to build a language that worked well
-for building the large software that Google writes and runs. It was
-clear from the start that such a language must provide a way to
-express dependencies between code libraries clearly, hence the package
-grouping and the explicit import blocks. It was also clear from the
-start that you might want arbitrary syntax for describing the code
-being imported; this is why import paths are string literals. An explicit goal for Go from the beginning was to be able to build Go
-code using only the information found in the source itself, not
-needing to write a makefile or one of the many modern replacements for
-makefiles. If Go needed a configuration file to explain how to build
-your program, then Go would have failed. At first, there was no Go compiler, and the initial development
-focused on building one and then building libraries for it. For
-expedience, we postponed the automation of building Go code by using
-make and writing makefiles. When compiling a single package involved
-multiple invocations of the Go compiler, we even used a program to
-write the makefiles for us. You can find it if you dig through the
-repository history. The purpose of the new go command is our return to this ideal, that Go
-programs should compile without configuration or additional effort on
-the part of the developer beyond writing the necessary import
-statements. The way to achieve the simplicity of a configuration-free system is to
-establish conventions. The system works only to the extent that those conventions
-are followed. When we first launched Go, many people published packages that
-had to be installed in certain places, under certain names, using certain build
-tools, in order to be used. That's understandable: that's the way it works in
-most other languages. Over the last few years we consistently reminded people
-about the We received many requests to allow a makefile in a package directory to
-provide just a little extra configuration beyond what's in the source code.
-But that would have introduced new rules. Because we did not accede to such
-requests, we were able to write the go command and eliminate our use of make
-or any other build system. It is important to understand that the go command is not a general
-build tool. It cannot be configured and it does not attempt to build
-anything but Go packages. These are important simplifying
-assumptions: they simplify not only the implementation but also, more
-important, the use of the tool itself. The First, the import path is derived in an known way from the URL of the
-source code. For Bitbucket, GitHub, Google Code, and Launchpad, the
-root directory of the repository is identified by the repository's
-main URL, without the and thus the import path for the root directory of that repository is
-" These paths are on the long side, but in exchange we get an
-automatically managed name space for import paths and the ability for
-a tool like the go command to look at an unfamiliar import path and
-deduce where to obtain the source code. Second, the place to store sources in the local file system is derived
-in a known way from the import path, specifically
- Each of those trees contains, by convention, a top-level directory named
-" These naming conventions also let us work in the reverse direction,
-from a directory name to its import path. This mapping is important
-for many of the go command's subcommands, as we'll see below. Third, each directory in a source tree corresponds to a single
-package. By restricting a directory to a single package, we don't have
-to create hybrid import paths that specify first the directory and
-then the package within that directory. Also, most file management
-tools and UIs work on directories as fundamental units. Tying the
-fundamental Go unit—the package—to file system structure means
-that file system tools become Go package tools. Copying, moving, or
-deleting a package corresponds to copying, moving, or deleting a
-directory. Fourth, each package is built using only the information present in
-the source files. This makes it much more likely that the tool will
-be able to adapt to changing build environments and conditions. For
-example, if we allowed extra configuration such as compiler flags or
-command line recipes, then that configuration would need to be updated
-each time the build tools changed; it would also be inherently tied
-to the use of a specific toolchain. Finally, a quick tour of how to use the go command.
-As mentioned above, the default We first add some source code. Suppose we want to use
-the indexing library from the codesearch project along with a left-leaning
-red-black tree. We can install both with the " Both of these projects are now downloaded and installed into Because we used version control systems (Mercurial and Git) to check
-out the sources, the source tree also contains the other files in the
-corresponding repositories, such as related packages. The " We can also test those packages: If a go subcommand is invoked with no paths listed, it operates on the
-current directory: That " Notice that " As mentioned above, the go command is not a general-purpose build
-tool.
-In particular, it does not have any facility for generating Go
-source files during a build, although it does provide
- For more information, read How to Write Go Code
-and see the go command documentation.
-See the Documents page and the
-Blog index for a complete list of Go articles.
-
-Data races are among the most common and hardest to debug types of bugs in concurrent systems.
-A data race occurs when two goroutines access the same variable concurrently and at least one of the accesses is a write.
-See the The Go Memory Model for details.
-
-Here is an example of a data race that can lead to crashes and memory corruption:
-
-To help diagnose such bugs, Go includes a built-in data race detector.
-To use it, add the
-When the race detector finds a data race in the program, it prints a report.
-The report contains stack traces for conflicting accesses, as well as stacks where the involved goroutines were created.
-Here is an example:
-
-The
-The options are:
-
-Example:
-
-When you build with
-To start, run your tests using the race detector (
-Here are some typical data races. All of them can be detected with the race detector.
-
-The variable
-The fix is to introduce new variables in the goroutines (note the use of
-If the following code is called from several goroutines, it leads to races on the
-To make the code safe, protect the accesses with a mutex:
-
-Data races can happen on variables of primitive types as well (
-Even such "innocent" data races can lead to hard-to-debug problems caused by
-non-atomicity of the memory accesses,
-interference with compiler optimizations,
-or reordering issues accessing processor memory .
-
-A typical fix for this race is to use a channel or a mutex.
-To preserve the lock-free behavior, one can also use the
-
-The race detector runs on
-The cost of race detection varies by program, but for a typical program, memory
-usage may increase by 5-10x and execution time by 2-20x.
-
-Covered in this tutorial:
-
-Assumed knowledge:
-
-At present, you need to have a FreeBSD, Linux, OS X, or Windows machine to run Go.
-We will use
-Install Go (see the Installation Instructions).
-
-Make a new directory for this tutorial inside your
-Create a file named
-We import the
-Let's start by defining the data structures. A wiki consists of a series of
-interconnected pages, each of which has a title and a body (the page content).
-Here, we define
-The type
-The
-This method's signature reads: "This is a method named
-This method will save the
-The
-The octal integer literal
-In addition to saving pages, we will want to load pages, too:
-
-The function
-Functions can return multiple values. The standard library function
-
-But what happens if
-Callers of this function can now check the second parameter; if it is
-
-At this point we have a simple data structure and the ability to save to and
-load from a file. Let's write a
-After compiling and executing this code, a file named
-You can compile and run the program like this:
-
-(If you're using Windows you must type "
-Click here to view the code we've written so far.
-
-Here's a full working example of a simple web server:
-
-The
-It then calls
-
-The function
-An
-An
-If you run this program and access the URL:
-
-the program would present a page containing:
-
-To use the
-Let's create a handler,
-Again, note the use of
-First, this function extracts the page title from
-The function then loads the page data, formats the page with a string of simple
-HTML, and writes it to
-To use this handler, we rewrite our
-Click here to view the code we've written so far.
-
-Let's create some page data (as
-Open
-(If you're using Windows you must type "
-With this web server running, a visit to
-A wiki is not a wiki without the ability to edit pages. Let's create two new
-handlers: one named
-First, we add them to
-The function
-This function will work fine, but all that hard-coded HTML is ugly.
-Of course, there is a better way.
-
-The
-First, we must add
-Let's create a template file containing the HTML form.
-Open a new file named
-Modify
-The function
-The method
-Template directives are enclosed in double curly braces.
-The
-Since we're working with templates now, let's create a template for our
-
-Modify
-Notice that we've used almost exactly the same templating code in both
-handlers. Let's remove this duplication by moving the templating code
-to its own function:
-
-And modify the handlers to use that function:
-
-If we comment out the registration of our unimplemented save handler in
-
-What if you visit
-
-The
-The function
-The page title (provided in the URL) and the form's only field,
-
-The value returned by
-There are several places in our program where errors are being ignored. This
-is bad practice, not least because when an error does occur the program will
-have unintended behavior. A better solution is to handle the errors and return
-an error message to the user. That way if something does go wrong, the server
-will function exactly how we want and the user can be notified.
-
-First, let's handle the errors in
-The
-Now let's fix up
-Any errors that occur during
-There is an inefficiency in this code:
-First we create a global variable named
-The function
-The
-We then modify the
-Note that the template name is the template file name, so we must
-append
-As you may have observed, this program has a serious security flaw: a user
-can supply an arbitrary path to be read/written on the server. To mitigate
-this, we can write a function to validate the title with a regular expression.
-
-First, add
-The function
-Now, let's write a function that uses the
-If the title is valid, it will be returned along with a
-Let's put a call to
-Catching the error condition in each handler introduces a lot of repeated code.
-What if we could wrap each of the handlers in a function that does this
-validation and error checking? Go's
-function
-literals provide a powerful means of abstracting functionality
-that can help us here.
-
-First, we re-write the function definition of each of the handlers to accept
-a title string:
-
-Now let's define a wrapper function that takes a function of the above
-type, and returns a function of type
-The returned function is called a closure because it encloses values defined
-outside of it. In this case, the variable
-Now we can take the code from
-The closure returned by
-Now we can wrap the handler functions with
-Finally we remove the calls to
-Click here to view the final code listing.
-
-Recompile the code, and run the app:
-
-Visiting http://localhost:8080/view/ANewPage
-should present you with the page edit form. You should then be able to
-enter some text, click 'Save', and be redirected to the newly created page.
-
-Here are some simple tasks you might want to tackle on your own:
- [edit] [edit]
-This document is a quick outline of the unusual form of assembly language used by the
-The assembler is based on the input style of the Plan 9 assemblers, which is documented in detail
-elsewhere.
-If you plan to write assembly language, you should read that document although much of it is Plan 9-specific.
-The current document provides a summary of the syntax and the differences with
-what is explained in that document, and
-describes the peculiarities that apply when writing assembly code to interact with Go.
-
-The most important thing to know about Go's assembler is that it is not a direct representation of the underlying machine.
-Some of the details map precisely to the machine, but some do not.
-This is because the compiler suite (see
-this description)
-needs no assembler pass in the usual pipeline.
-Instead, the compiler operates on a kind of semi-abstract instruction set,
-and instruction selection occurs partly after code generation.
-The assembler works on the semi-abstract form, so
-when you see an instruction like
-The assembler program is a way to parse a description of that
-semi-abstract instruction set and turn it into instructions to be
-input to the linker.
-If you want to see what the instructions look like in assembly for a given architecture, say amd64, there
-are many examples in the sources of the standard library, in packages such as
-
-The
-Although the assembler takes its guidance from the Plan 9 assemblers,
-it is a distinct program, so there are some differences.
-One is in constant evaluation.
-Constant expressions in the assembler are parsed using Go's operator
-precedence, not the C-like precedence of the original.
-Thus
-Some symbols, such as
-There are four predeclared symbols that refer to pseudo-registers.
-These are not real registers, but rather virtual registers maintained by
-the toolchain, such as a frame pointer.
-The set of pseudo-registers is the same for all architectures:
-
-All user-defined symbols are written as offsets to the pseudo-registers
-
-The
-The
-For assembly functions with Go prototypes,
-The
-On architectures with a hardware register named
-On machines where
-Branches and direct jumps are always written as offsets to the PC, or as
-jumps to labels:
-
-Each label is visible only within the function in which it is defined.
-It is therefore permitted for multiple functions in a file to define
-and use the same label names.
-Direct jumps and call instructions can target text symbols,
-such as
-Instructions, registers, and assembler directives are always in UPPER CASE to remind you
-that assembly programming is a fraught endeavor.
-(Exception: the
-In Go object files and binaries, the full name of a symbol is the
-package path followed by a period and the symbol name:
-
-Most hand-written assembly files do not include the full package path
-in symbol names, because the linker inserts the package path of the current
-object file at the beginning of any name starting with a period:
-in an assembly source file within the math/rand package implementation,
-the package's Int function can be referred to as
-The assembler uses various directives to bind text and data to symbol names.
-For example, here is a simple complete function definition. The
-In the general case, the frame size is followed by an argument size, separated by a minus sign.
-(It's not a subtraction, just idiosyncratic syntax.)
-The frame size
-Note that the symbol name uses a middle dot to separate the components and is specified as an offset from the
-static base pseudo-register
-Global data symbols are defined by a sequence of initializing
-
-which initializes the symbol memory at the given offset and width with the given value.
-The
-The
-For example,
-
-declares and initializes
-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 standard
-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
-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. The name of the assembly
-function must not contain the package name component (for example,
-function
-If a function has no arguments and no results,
-the pointer information can be omitted.
-This is indicated by an argument size annotation of
-If a function has no local stack frame,
-the pointer information can be omitted.
-This is indicated by a local frame size annotation of
-Assembly functions should always be given Go prototypes,
-both to provide pointer information for the arguments and results
-and to let
-It is impractical to list all the instructions and other details for each machine.
-To see what instructions are defined for a given machine, say ARM,
-look in the source for the
-This is the list of instructions and their spellings as known to the assembler and linker for that architecture.
-Each instruction begins with an initial capital
-The instructions for both the 386 and AMD64 architectures are listed in
-
-The architectures share syntax for common addressing modes such as
-
-One detail evident in the examples from the previous sections is that data in the instructions flows from left to right:
-
-Here follow some descriptions of key Go-specific details for the supported architectures.
-
-The runtime pointer to the
-Within the runtime, the
-Addressing modes:
-
-When using the compiler and assembler's
-
-The two architectures behave largely the same at the assembler level.
-Assembly code to access the
-The registers
-
-To make it easier for people and compilers to write assembly, the ARM linker
-allows general addressing forms and pseudo-operations like
-When defining a
-The name
-Condition code syntax is to append a period and the one- or two-letter code to the instruction,
-as in
-Addressing modes:
-
-The ARM64 port is in an experimental state.
-
-
-Instruction modifiers are appended to the instruction following a period.
-The only modifiers are
-Addressing modes:
-
-Reference: Go ARM64 Assembly Instructions Reference Manual
-
-The 64-bit PowerPC port is in an experimental state.
-
-Addressing modes:
-
-The registers
-
-
-Load- and store-multiple instructions operate on a range of registers.
-The range of registers is specified by a start register and an end register.
-For example,
-Storage-and-storage instructions such as
-If a vector instruction takes a length or an index as an argument then it will be the
-first argument.
-For example,
-Addressing modes:
-
-General purpose registers are named
-
-In a
-
-Addressing modes:
-
-The value of
-The value of
-The assemblers are designed to support the compiler so not all hardware instructions
-are defined for all architectures: if the compiler doesn't generate it, it might not be there.
-If you need to use a missing instruction, there are two ways to proceed.
-One is to update the assembler to support that instruction, which is straightforward
-but only worthwhile if it's likely the instruction will be used again.
-Instead, for simple one-off cases, it's possible to use the
-There is a suite of programs to build and process Go source code.
-Instead of being run directly, programs in the suite are usually invoked
-by the go program.
-
-The most common way to run these programs is as a subcommand of the go program,
-for instance as
-The programs can also be run as stand-alone binaries, with unmodified arguments,
-using the go
-Finally the
-Click on the links for more documentation, invocation methods, and usage details.
-
-This is an abridged list. See the full command reference
-for documentation of the compilers and more.
-
-This document demonstrates the development of a simple Go package and
-introduces the go tool, the standard way to fetch,
-build, and install Go packages and commands.
-
-The
-A similar explanation is available as a
-screencast.
-
-Note that this differs from other programming environments in which every
-project has a separate workspace and workspaces are closely tied to version
-control repositories.
-
-A workspace is a directory hierarchy with two directories at its root:
-
-The
-The
-To give you an idea of how a workspace looks in practice, here's an example:
-
-The tree above shows a workspace containing two repositories
-(
-A typical workspace contains many source repositories containing many
-packages and commands. Most Go programmers keep all their Go source code
-and dependencies in a single workspace.
-
-Note that symbolic links should not be used to link files or directories into your workspace.
-
-Commands and libraries are built from different kinds of source packages.
-We will discuss the distinction later.
-
-The
-If you would like to work in a different location, you will need to
-set
-The command
-For convenience, add the workspace's
-The scripts in the rest of this document use
-To learn more about the
-To use a custom workspace location,
-set the
-An import path is a string that uniquely identifies a package.
-A package's import path corresponds to its location inside a workspace
-or in a remote repository (explained below).
-
-The packages from the standard library are given short import paths such as
-
-If you keep your code in a source repository somewhere, then you should use the
-root of that source repository as your base path.
-For instance, if you have a GitHub account at
-
-Note that you don't need to publish your code to a remote repository before you
-can build it. It's just a good habit to organize your code as if you will
-publish it someday. In practice you can choose any arbitrary path name,
-as long as it is unique to the standard library and greater Go ecosystem.
-
-We'll use
-To compile and run a simple program, first choose a package path (we'll use
-
-Next, create a file named
-Now you can build and install that program with the
-Note that you can run this command from anywhere on your system. The
-
-You can also omit the package path if you run
-This command builds the
-The
-You can now run the program by typing its full path at the command line:
-
-Or, as you have added
-If you're using a source control system, now would be a good time to initialize
-a repository, add the files, and commit your first change. Again, this step is
-optional: you do not need to use source control to write Go code.
-
-Pushing the code to a remote repository is left as an exercise for the reader.
-
-Let's write a library and use it from the
-Again, the first step is to choose a package path (we'll use
-
-Next, create a file named
-Now, test that the package compiles with
-Or, if you are working in the package's source directory, just:
-
-This won't produce an output file.
-Instead it saves the compiled package in the local build cache.
-
-After confirming that the
-Install the
-Running the new version of the program, you should see a new, reversed message:
-
-After the steps above, your workspace should look like this:
-
-The first statement in a Go source file must be
-
-where
-Go's convention is that the package name is the last element of the
-import path: the package imported as "
-Executable commands must always use
-There is no requirement that package names be unique
-across all packages linked into a single binary,
-only that the import paths (their full file names) be unique.
-
-See Effective Go to learn more about
-Go's naming conventions.
-
-Go has a lightweight test framework composed of the
-You write a test by creating a file with a name ending in
-Add a test to the
-Then run the test with
-As always, if you are running the
-Run
-An import path can describe how to obtain the package source code using a
-revision control system such as Git or Mercurial. The
-If the specified package is not present in a workspace,
-After issuing the above
-The
-This convention is the easiest way to make your Go packages available for
-others to use.
-The Go Wiki
-and godoc.org
-provide lists of external Go projects.
-
-For more information on using remote repositories with the
-Subscribe to the
-golang-announce
-mailing list to be notified when a new stable version of Go is released.
-
-See Effective Go for tips on writing
-clear, idiomatic Go code.
-
-Take A Tour of Go to learn the language
-proper.
-
-Visit the documentation page for a set of in-depth
-articles about the Go language and its libraries and tools.
-
-For real-time help, ask the helpful gophers in
-The official mailing list for discussion of the Go language is
-Go Nuts.
-
-Report bugs using the
-Go issue tracker.
-
-Online communities include people from many different backgrounds.
-The Go contributors are committed to providing a friendly, safe and welcoming
-environment for all, regardless of gender identity and expression, sexual orientation,
-disabilities, neurodiversity, physical appearance, body size, ethnicity, nationality,
-race, age, religion, or similar personal characteristics.
-
-The first goal of the Code of Conduct is to specify a baseline standard
-of behavior so that people with different social values and communication
-styles can talk about Go effectively, productively, and respectfully.
-
-The second goal is to provide a mechanism for resolving conflicts in the
-community when they arise.
-
-The third goal of the Code of Conduct is to make our community welcoming to
-people from different backgrounds.
-Diversity is critical to the project; for Go to be successful, it needs
-contributors and users from all backgrounds.
-(See Go, Open Source, Community.)
-
-We believe that healthy debate and disagreement are essential to a healthy project and community.
-However, it is never ok to be disrespectful.
-We value diverse opinions, but we value respectful behavior more.
-
-These are the values to which people in the Go community (“Gophers”) should aspire.
-
-People are complicated.
-You should expect to be misunderstood and to misunderstand others;
-when this inevitably occurs, resist the urge to be defensive or assign blame.
-Try not to take offense where no offense was intended.
-Give people the benefit of the doubt.
-Even if the intent was to provoke, do not rise to it.
-It is the responsibility of all parties to de-escalate conflict when it arises.
- In the interest of fostering an open and welcoming environment, we as
-contributors and maintainers pledge to making participation in our project and
-our community a harassment-free experience for everyone, regardless of age, body
-size, disability, ethnicity, gender identity and expression, level of
-experience, education, socio-economic status, nationality, personal appearance,
-race, religion, or sexual identity and orientation. Examples of behavior that contributes to creating a positive environment
-include: Examples of unacceptable behavior by participants include: Project maintainers are responsible for clarifying the standards of acceptable
-behavior and are expected to take appropriate and fair corrective action in
-response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject
-comments, commits, code, wiki edits, issues, and other contributions that are
-not aligned to this Code of Conduct, or to ban temporarily or permanently any
-contributor for other behaviors that they deem inappropriate, threatening,
-offensive, or harmful. This Code of Conduct applies both within project spaces and in public spaces
-when an individual is representing the project or its community. Examples of
-representing a project or community include using an official project e-mail
-address, posting via an official social media account, or acting as an appointed
-representative at an online or offline event. Representation of a project may be
-further defined and clarified by project maintainers. This Code of Conduct also applies outside the project spaces when the Project
-Steward has a reasonable belief that an individual’s behavior may have a
-negative impact on the project or its community. We do not believe that all conflict is bad; healthy debate and disagreement
-often yield positive results. However, it is never okay to be disrespectful or
-to engage in behavior that violates the project’s code of conduct. If you see someone violating the code of conduct, you are encouraged to address
-the behavior directly with those involved. Many issues can be resolved quickly
-and easily, and this gives people more control over the outcome of their
-dispute. If you are unable to resolve the matter for any reason, or if the
-behavior is threatening or harassing, report it. We are dedicated to providing
-an environment where participants feel welcome and safe. Reports should be directed to Cassandra Salisbury, the
-Go Project Steward, at conduct@golang.org.
-It is the Project Steward’s duty to
-receive and address reported violations of the code of conduct. They will then
-work with a committee consisting of representatives from the Open Source
-Programs Office and the Google Open Source Strategy team. If for any reason you
-are uncomfortable reaching out the Project Steward, please email
-the Google Open Source Programs Office at opensource@google.com. We will investigate every complaint, but you may not receive a direct response.
-We will use our discretion in determining when and how to follow up on reported
-incidents, which may range from not taking action to permanent expulsion from
-the project and project-sponsored spaces. We will notify the accused of the
-report and provide them an opportunity to discuss it before any action is taken.
-The identity of the reporter will be omitted from the details of the report
-supplied to the accused. In potentially harmful situations, such as ongoing
-harassment or threats to anyone’s safety, we may take action without notice. This Code of Conduct is adapted from the Contributor Covenant, version 1.4,
-available at
-https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
-Go is an open source project developed by a team at
-Google and many
-contributors from the open source community.
-
-Go is distributed under a BSD-style license.
-
-A low traffic mailing list for important announcements, such as new releases.
-
-We encourage all Go users to subscribe to
-golang-announce.
- A summary of the changes between Go releases. Notes for the major releases:
-What Go 1 defines and the backwards-compatibility guarantees one can expect as
-Go 1 matures.
- Check out the Go source code.
-A mailing list for general discussion of Go programming.
-
-Questions about using Go or announcements relevant to other Go users should be sent to
-golang-nuts.
- The golang-dev
-mailing list is for discussing code changes to the Go project.
-The golang-codereviews
-mailing list is for actual reviewing of the code changes (CLs). A mailing list that receives a message summarizing each checkin to the Go repository. View the status of Go builds across the supported operating
-systems and architectures.
-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.
-(Of course, you should check it's not an existing issue before creating
-a new one.)
-
-We pride ourselves on being meticulous; no issue is too small.
-
-Security-related issues should be reported to
-security@golang.org.
-Community-related issues should be reported to
-conduct@golang.org.
-Go is an open source project and we welcome contributions from the community.
-
-To get started, read these contribution
-guidelines for information on design, testing, and our code review process.
-
-Check the tracker for
-open issues that interest you. Those labeled
-help wanted
-are particularly in need of outside help.
-
-The Go project welcomes all contributors.
-
-This document is a guide to help you through the process
-of contributing to the Go project, which is a little different
-from that used by other open source projects.
-We assume you have a basic understanding of Git and Go.
-
-In addition to the information here, the Go community maintains a
-CodeReview wiki page.
-Feel free to contribute to the wiki as you learn the review process.
-
-Note that the
-The first step is registering as a Go contributor and configuring your environment.
-Here is a checklist of the required steps to follow:
-
-If you prefer, there is an automated tool that walks through these steps.
-Just run:
-
-The rest of this chapter elaborates on these instructions.
-If you have completed the steps above (either manually or through the tool), jump to
-Before contributing code.
-
-A contribution to Go is made through a Google account with a specific
-e-mail address.
-Make sure to use the same account throughout the process and
-for all your subsequent contributions.
-You may need to decide whether to use a personal address or a corporate address.
-The choice will depend on who
-will own the copyright for the code that you will be writing
-and submitting.
-You might want to discuss this topic with your employer before deciding which
-account to use.
-
-Google accounts can either be Gmail e-mail accounts, G Suite organization accounts, or
-accounts associated with an external e-mail address.
-For instance, if you need to use
-an existing corporate e-mail that is not managed through G Suite, you can create
-an account associated
-with your existing
-e-mail address.
-
-You also need to make sure that your Git tool is configured to create commits
-using your chosen e-mail address.
-You can either configure Git globally
-(as a default for all projects), or locally (for a single specific project).
-You can check the current configuration with this command:
-
-To change the configured address:
-
-Before sending your first change to the Go project
-you must have completed one of the following two CLAs.
-Which CLA you should sign depends on who owns the copyright to your work.
-
-You can check your currently signed agreements and sign new ones at
-the Google Developers
-Contributor License Agreements website.
-If the copyright holder for your contribution has already completed the
-agreement in connection with another Google open source project,
-it does not need to be completed again.
-
-If the copyright holder for the code you are submitting changes—for example,
-if you start contributing code on behalf of a new company—please send mail
-to the
-The main Go repository is located at
-go.googlesource.com,
-a Git server hosted by Google.
-Authentication on the web server is made through your Google account, but
-you also need to configure
-Gerrit is an open-source tool used by Go maintainers to discuss and review
-code submissions.
-
-To register your account, visit
-go-review.googlesource.com/login/ and sign in once using the same Google Account you used above.
-
-Changes to Go must be reviewed before they are accepted, no matter who makes the change.
-A custom
-Install the
-Make sure
-prints help text, not an error.
-
-On Windows, when using git-bash you must make sure that
-
-The project welcomes code patches, but to make sure things are well
-coordinated you should discuss any significant change before starting
-the work.
-It's recommended that you signal your intention to contribute in the
-issue tracker, either by filing
-a new issue or by claiming
-an existing one.
-
-Whether you already know what contribution to make, or you are searching for
-an idea, the issue tracker is
-always the first place to go.
-Issues are triaged to categorize them and manage the workflow.
-
-Most issues will be marked with one of the following workflow labels:
-
-You can use GitHub's search functionality to find issues to help out with. Examples:
-
-Excluding very trivial changes, all contributions should be connected
-to an existing issue.
-Feel free to open one and discuss your plans.
-This process gives everyone a chance to validate the design,
-helps prevent duplication of effort,
-and ensures that the idea fits inside the goals for the language and tools.
-It also checks that the design is sound before code is written;
-the code review tool is not the place for high-level discussions.
-
-When planning work, please note that the Go project follows a six-month development cycle.
-The latter half of each cycle is a three-month feature freeze during
-which only bug fixes and documentation updates are accepted.
-New contributions can be sent during a feature freeze, but they will
-not be merged until the freeze is over.
-
-Significant changes to the language, libraries, or tools must go
-through the
-change proposal process
-before they can be accepted.
-
-Sensitive security-related issues (only!) should be reported to security@golang.org.
-
-First-time contributors that are already familiar with the
-GitHub flow
-are encouraged to use the same process for Go contributions.
-Even though Go
-maintainers use Gerrit for code review, a bot called Gopherbot has been created to sync
-GitHub pull requests to Gerrit.
-
-Open a pull request as you normally would.
-Gopherbot will create a corresponding Gerrit change and post a link to
-it on your GitHub pull request; updates to the pull request will also
-get reflected in the Gerrit change.
-When somebody comments on the change, their comment will be also
-posted in your pull request, so you will get a notification.
-
-Some things to keep in mind:
-
-It is not possible to fully sync Gerrit and GitHub, at least at the moment,
-so we recommend learning Gerrit.
-It's different but powerful and familiarity with it will help you understand
-the flow.
-
-This is an overview of the overall process:
-
-The rest of this section describes these steps in more detail.
-
-In addition to a recent Go installation, you need to have a local copy of the source
-checked out from the correct repository.
-You can check out the Go source repo onto your local file system anywhere
-you want as long as it's outside your
-Each Go change must be made in a separate branch, created from the master branch.
-You can use
-the normal
-To commit changes, instead of
-You can edit the commit description in your favorite editor as usual.
-The
-The tool also checks that you've
-run
-If you need to edit the files again, you can stage the new changes and
-re-run
-Make sure that you always keep a single commit in each branch.
-If you add more
-commits by mistake, you can use
-You've written and tested your code, but
-before sending code out for review, run all the tests for the whole
-tree to make sure the changes don't break other packages or programs:
-
-(To build under Windows use
-After running for a while and printing a lot of testing output, the command should finish
-by printing,
-
-You can use
-Once the change is ready and tested over the whole tree, send it for review.
-This is done with the
-Gerrit assigns your change a number and URL, which
-If you get an error instead, check the
-Troubleshooting mail errors section.
-
-If your change relates to an open GitHub issue and you have followed the
-suggested commit message format, the issue will be updated in a few minutes by a bot,
-linking your Gerrit change to it in the comments.
-
-Go maintainers will review your code on Gerrit, and you will get notifications via e-mail.
-You can see the review on Gerrit and comment on them there.
-You can also reply
-using e-mail
-if you prefer.
-
-If you need to revise your change after the review, edit the files in
-the same branch you previously created, add them to the Git staging
-area, and then amend the commit with
-
-If you don't need to change the commit description, just save and exit from the editor.
-Remember not to touch the special Change-Id line.
-
-Again, make sure that you always keep a single commit in each branch.
-If you add more
-commits by mistake, you can use
-Commit messages in Go follow a specific set of conventions,
-which we discuss in this section.
-
-Here is an example of a good one:
-
-The first line of the change description is conventionally a short one-line
-summary of the change, prefixed by the primary affected package.
-
-A rule of thumb is that it should be written so to complete the sentence
-"This change modifies Go to _____."
-That means it does not start with a capital letter, is not a complete sentence,
-and actually summarizes the result of the change.
-
-Follow the first line by a blank line.
-
-The rest of the description elaborates and should provide context for the
-change and explain what it does.
-Write in complete sentences with correct punctuation, just like
-for your comments in Go.
-Don't use HTML, Markdown, or any other markup language.
-
-Add any relevant information, such as benchmark data if the change
-affects performance.
-The benchstat
-tool is conventionally used to format
-benchmark data for change descriptions.
-
-The special notation "Fixes #12345" associates the change with issue 12345 in the
-Go issue tracker.
-When this change is eventually applied, the issue
-tracker will automatically mark the issue as fixed.
-
-If the change is a partial step towards the resolution of the issue,
-uses the notation "Updates #12345".
-This will leave a comment in the issue
-linking back to the change in Gerrit, but it will not close the issue
-when the change is applied.
-
-If you are sending a change against a subrepository, you must use
-the fully-qualified syntax supported by GitHub to make sure the change is
-linked to the issue in the main repository, not the subrepository.
-All issues are tracked in the main repository's issue tracker.
-The correct form is "Fixes golang/go#159".
-
-This section explains the review process in detail and how to approach
-reviews after a change has been mailed.
-
-When a change is sent to Gerrit, it is usually triaged within a few days.
-A maintainer will have a look and provide some initial review that for first-time
-contributors usually focuses on basic cosmetics and common mistakes.
-These include things like:
-
-After an initial reading of your change, maintainers will trigger trybots,
-a cluster of servers that will run the full test suite on several different
-architectures.
-Most trybots complete in a few minutes, at which point a link will
-be posted in Gerrit where you can see the results.
-
-If the trybot run fails, follow the link and check the full logs of the
-platforms on which the tests failed.
-Try to understand what broke, update your patch to fix it, and upload again.
-Maintainers will trigger a new trybot run to see
-if the problem was fixed.
-
-Sometimes, the tree can be broken on some platforms for a few hours; if
-the failure reported by the trybot doesn't seem related to your patch, go to the
-Build Dashboard and check if the same
-failure appears in other recent commits on the same platform.
-In this case,
-feel free to write a comment in Gerrit to mention that the failure is
-unrelated to your change, to help maintainers understand the situation.
-
-The Go community values very thorough reviews.
-Think of each review comment like a ticket: you are expected to somehow "close" it
-by acting on it, either by implementing the suggestion or convincing the
-reviewer otherwise.
-
-After you update the change, go through the review comments and make sure
-to reply to every one.
-You can click the "Done" button to reply
-indicating that you've implemented the reviewer's suggestion; otherwise,
-click on "Reply" and explain why you have not, or what you have done instead.
-
-It is perfectly normal for changes to go through several round of reviews,
-with one or more reviewers making new comments every time
-and then waiting for an updated change before reviewing again.
-This cycle happens even for experienced contributors, so
-don't be discouraged by it.
-
-As they near a decision, reviewers will make a "vote" on your change.
-The Gerrit voting system involves an integer in the range -2 to +2:
-
-After the code has been +2'ed, an approver will
-apply it to the master branch using the Gerrit user interface.
-This is called "submitting the change".
-
-The two steps (approving and submitting) are separate because in some cases maintainers
-may want to approve it but not to submit it right away (for instance,
-the tree could be temporarily frozen).
-
-Submitting a change checks it into the repository.
-The change description will include a link to the code review,
-which will be updated with a link to the change
-in the repository.
-Since the method used to integrate the changes is Git's "Cherry Pick",
-the commit hashes in the repository will be changed by
-the submit operation.
-
-If your change has been approved for a few days without being
-submitted, feel free to write a comment in Gerrit requesting
-submission.
-
-In addition to the information here, the Go community maintains a CodeReview wiki page.
-Feel free to contribute to this page as you learn more about the review process.
-
-This section collects a number of other comments that are
-outside the issue/edit/code review/submit process itself.
-
-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
-change log and in the
-New files that you contribute should use the standard copyright header:
-
-(Use the current year if you're reading this in 2020 or beyond.)
-Files in the repository are copyrighted the year they are added.
-Do not update the copyright year on files that you change.
-
-The most common way that the
-you need to configure Git for this repository to use the
-e-mail address that you registered with.
-To change the e-mail address to ensure this doesn't happen again, run:
-
-Then change the commit to use this alternative e-mail address with this command:
-
-Then retry by running:
-
-Running
-If you are contributing a change to a subrepository, obtain the
-Go package using
-Then, change your directory to the package's source directory
-(
-Unless explicitly told otherwise, such as in the discussion leading
-up to sending in the change, it's better not to specify a reviewer.
-All changes are automatically CC'ed to the
-golang-codereviews@googlegroups.com
-mailing list.
-If this is your first ever change, there may be a moderation
-delay before it appears on the mailing list, to prevent spam.
-
-You can specify a reviewer or CC interested parties
-using the
-While you were working, others might have submitted changes to the repository.
-To update your local branch, run
-
-(Under the covers this runs
-
-As part of the review process reviewers can propose changes directly (in the
-GitHub workflow this would be someone else attaching commits to a pull request).
-
-You can import these changes 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 will look something like this:
-
-To revert, change back to the branch you were working in.
-
-The
-but it is more convenient to set up aliases for
-The
-Advanced users may want to stack up related commits in a single branch.
-Gerrit allows for changes to be dependent on each other, forming such a dependency chain.
-Each change will need to be approved and submitted separately but the dependency
-will be visible to reviewers.
-
-To send out a group of dependent changes, keep each change as a different commit under
-the same branch, and then run:
-
-Make sure to explicitly specify
-The following instructions apply to the standard toolchain
-(the
-Note that
-Delve is a better
-alternative to GDB when debugging Go programs built with the standard
-toolchain. It understands the Go runtime, data structures, and
-expressions better than GDB. Delve currently supports Linux, OSX,
-and Windows on
-GDB does not understand Go programs well.
-The stack management, threading, and runtime contain aspects that differ
-enough from the execution model GDB expects that they can confuse
-the debugger and cause incorrect results even when the program is
-compiled with gccgo.
-As a consequence, although GDB can be useful in some situations (e.g.,
-debugging Cgo code, or debugging the runtime itself), it is not
-a reliable debugger for Go programs, particularly heavily concurrent
-ones. Moreover, it is not a priority for the Go project to address
-these issues, which are difficult.
-
-In short, the instructions below should be taken only as a guide to how
-to use GDB when it works, not as a guarantee of success.
-
-Besides this overview you might want to consult the
-GDB manual.
-
-
-When you compile and link your Go programs with the
-Pass the
-The code generated by the
-If you want to use gdb to inspect a core dump, you can trigger a dump
-on a program crash, on systems that permit it, by setting
-
-A recent extension mechanism to GDB allows it to load extension scripts for a
-given binary. The toolchain uses this to extend GDB with a handful of
-commands to inspect internals of the runtime code (such as goroutines) and to
-pretty print the built-in map, slice and channel types.
- Known issue: GDB can’t automatically find the dynamic
-type of an interface value if its long name differs from its short name
-(annoying when printing stacktraces, the pretty printer falls back to printing
-the short type name and a pointer).
-If you'd like to see how this works, or want to extend it, take a look at src/runtime/runtime-gdb.py in
-the Go source distribution. It depends on some special magic types
-(
-If you're interested in what the debugging information looks like, run
-
-In this tutorial we will inspect the binary of the
-regexp package's unit tests. To build the binary,
-change to
-Launch GDB, debugging
-The message "Loading Go Runtime support" means that GDB loaded the
-extension from
-To help GDB find the Go runtime sources and the accompanying support script,
-pass your
-If for some reason GDB still can't find that directory or that script, you can load
-it by hand by telling gdb (assuming you have the go sources in
-
-Use the
-List a specific part of the source parametrizing
-List a specific file and line number:
-
-Variable and function names must be qualified with the name of the packages
-they belong to. The
-Methods must be qualified with the name of their receiver types. For example,
-the
-Variables that shadow other variables are magically suffixed with a number in the debug info.
-Variables referenced by closures will appear as pointers magically prefixed with '&'.
-
-Set a breakpoint at the
-Run the program:
-
-Execution has paused at the breakpoint.
-See which goroutines are running, and what they're doing:
-
-the one marked with the
-Look at the stack trace for where we’ve paused the program:
-
-The other goroutine, number 1, is stuck in
-The stack frame shows we’re currently executing the
-The command
-The function’s arguments:
-
-When printing the argument, notice that it’s a pointer to a
-
-That
-Stepping forward:
-
-We can step into the
-Get a stack trace to see where we are:
-
-Look at the source code:
-
-GDB's pretty printing mechanism is triggered by regexp matches on type names. An example for slices:
-
-Since slices, arrays and strings are not C pointers, GDB can't interpret the subscripting operation for you, but
-you can look inside the runtime representation to do that (tab completion helps here):
-
-The extension functions $len and $cap work on strings, arrays and slices:
-
-Channels and maps are 'reference' types, which gdb shows as pointers to C++-like types
-Interfaces are represented in the runtime as a pointer to a type descriptor and a pointer to a value. The Go GDB runtime extension decodes this and automatically triggers pretty printing for the runtime type. The extension function
-This page summarizes the changes between stable releases of Go prior to Go 1.
-See the Release History page for notes on recent releases.
-
-The r60 release corresponds to
-
-An "else" block is now required to have braces except if the body of the "else"
-is another "if". Since gofmt always puts those braces in anyway,
-gofmt-formatted programs will not be affected.
-To fix other programs, run gofmt.
-
-Package http's URL parsing and query escaping code
-(such as
-Package image has had significant changes made to the
-
-Package template has been replaced with a new
-templating package (formerly
-Goinstall now uses a new tag selection scheme.
-When downloading or updating, goinstall looks for a tag or branch with the
-
-r60.1 includes a
-linker
-fix, a pair of
-goplay
-fixes,
-and a
-r60.2
-fixes
-a memory leak involving maps.
-
-r60.3 fixes a
-reflect bug.
-
-The r59 release corresponds to
-
-This release includes a language change that restricts the use of
-
-As usual, gofix will handle the bulk of the rewrites
-necessary for these changes to package APIs.
-
-Package http has a new
-FileSystem interface that provides access
-to files. The FileServer helper now takes a
-
-Package os's
-Package reflect supports a new struct tag scheme
-that enables sharing of struct tags between multiple packages.
-In this scheme, the tags must be of the form:
-
-The StructField type's Tag field now
-has type StructTag, which has a
-
-should become
-
-Use govet to identify struct tags that need to be
-changed to use the new syntax.
-
-Package sort's
-Package strings's go
", that
-automates the downloading, building, installation, and testing of Go packages
-and commands. This document talks about why we wrote a new command, what it
-is, what it's not, and how to use it.Motivation
-
-Configuration versus convention
-
-goinstall
command
-(now replaced by go get
)
-and its conventions: first, that the import path is derived in a known way from
-the URL of the source code; second, that the place to store the sources in
-the local file system is derived in a known way from the import path; third,
-that each directory in a source tree corresponds to a single package; and
-fourth, that the package is built using only information in the source code.
-Today, the vast majority of packages follow these conventions.
-The Go ecosystem is simpler and more powerful as a result.Go's conventions
-
-go
command requires that code adheres to a few key,
-well-established conventions.http://
prefix. Subdirectories are named by
-adding to that path.
-For example, the Go example programs are obtained by running
-git clone https://github.com/golang/example
-
-
-github.com/golang/example
".
-The stringutil
-package is stored in a subdirectory, so its import path is
-"github.com/golang/example/stringutil
".$GOPATH/src/<import-path>
.
-If unset, $GOPATH
defaults to a subdirectory
-named go
in the user's home directory.
-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.
-bin
", for holding compiled executables, and a top-level directory
-named "pkg
", for holding compiled packages that can be imported,
-and the "src
" directory, for holding package source files.
-Imposing this structure lets us keep each of these directory trees
-self-contained: the compiled form and the sources are always near each
-other.Getting started with the go command
-
-$GOPATH
on Unix is $HOME/go
.
-We'll store our programs there.
-To use a different location, you can set $GOPATH
;
-see How to Write Go Code for details.
-
-go get
"
-subcommand:
-$ go get github.com/google/codesearch/index
-$ go get github.com/petar/GoLLRB/llrb
-$
-
-
-$HOME/go
,
-which contains the two directories
-src/github.com/google/codesearch/index/
and
-src/github.com/petar/GoLLRB/llrb/
, along with the compiled
-packages (in pkg/
) for those libraries and their dependencies.go list
"
-subcommand lists the import paths corresponding to its arguments, and
-the pattern "./...
" means start in the current directory
-("./
") and find all packages below that directory
-("...
"):
-$ cd $HOME/go/src
-$ go list ./...
-github.com/google/codesearch/cmd/cgrep
-github.com/google/codesearch/cmd/cindex
-github.com/google/codesearch/cmd/csearch
-github.com/google/codesearch/index
-github.com/google/codesearch/regexp
-github.com/google/codesearch/sparse
-github.com/petar/GoLLRB/example
-github.com/petar/GoLLRB/llrb
-$
-
-
-
-$ go test ./...
-? github.com/google/codesearch/cmd/cgrep [no test files]
-? github.com/google/codesearch/cmd/cindex [no test files]
-? github.com/google/codesearch/cmd/csearch [no test files]
-ok github.com/google/codesearch/index 0.203s
-ok github.com/google/codesearch/regexp 0.017s
-? github.com/google/codesearch/sparse [no test files]
-? github.com/petar/GoLLRB/example [no test files]
-ok github.com/petar/GoLLRB/llrb 0.231s
-$
-
-
-
-$ cd github.com/google/codesearch/regexp
-$ go list
-github.com/google/codesearch/regexp
-$ go test -v
-=== RUN TestNstateEnc
---- PASS: TestNstateEnc (0.00s)
-=== RUN TestMatch
---- PASS: TestMatch (0.00s)
-=== RUN TestGrep
---- PASS: TestGrep (0.00s)
-PASS
-ok github.com/google/codesearch/regexp 0.018s
-$ go install
-$
-
-
-go install
" subcommand installs the latest copy of the
-package into the pkg directory. Because the go command can analyze the
-dependency graph, "go install
" also installs any packages that
-this package imports but that are out of date, recursively.go install
" was able to determine the name of the
-import path for the package in the current directory, because of the convention
-for directory naming. It would be a little more convenient if we could pick
-the name of the directory where we kept source code, and we probably wouldn't
-pick such a long name, but that ability would require additional configuration
-and complexity in the tool. Typing an extra directory name or two is a small
-price to pay for the increased simplicity and power.Limitations
-
-go
-generate
,
-which can automate the creation of Go files before the build.
-For more advanced build setups, you may need to write a
-makefile (or a configuration file for the build tool of your choice)
-to run whatever tool creates the Go files and then check those generated source files
-into your repository. This is more work for you, the package author,
-but it is significantly less work for your users, who can use
-"go get
" without needing to obtain and build
-any additional tools.More information
-
-Introduction
-
-
-func main() {
- c := make(chan bool)
- m := make(map[string]string)
- go func() {
- m["1"] = "a" // First conflicting access.
- c <- true
- }()
- m["2"] = "b" // Second conflicting access.
- <-c
- for k, v := range m {
- fmt.Println(k, v)
- }
-}
-
-
-Usage
-
--race
flag to the go command:
-
-$ go test -race mypkg // to test the package
-$ go run -race mysrc.go // to run the source file
-$ go build -race mycmd // to build the command
-$ go install -race mypkg // to install the package
-
-
-Report Format
-
-
-WARNING: DATA RACE
-Read by goroutine 185:
- net.(*pollServer).AddFD()
- src/net/fd_unix.go:89 +0x398
- net.(*pollServer).WaitWrite()
- src/net/fd_unix.go:247 +0x45
- net.(*netFD).Write()
- src/net/fd_unix.go:540 +0x4d4
- net.(*conn).Write()
- src/net/net.go:129 +0x101
- net.func·060()
- src/net/timeout_test.go:603 +0xaf
-
-Previous write by goroutine 184:
- net.setWriteDeadline()
- src/net/sockopt_posix.go:135 +0xdf
- net.setDeadline()
- src/net/sockopt_posix.go:144 +0x9c
- net.(*conn).SetDeadline()
- src/net/net.go:161 +0xe3
- net.func·061()
- src/net/timeout_test.go:616 +0x3ed
-
-Goroutine 185 (running) created at:
- net.func·061()
- src/net/timeout_test.go:609 +0x288
-
-Goroutine 184 (running) created at:
- net.TestProlongTimeout()
- src/net/timeout_test.go:618 +0x298
- testing.tRunner()
- src/testing/testing.go:301 +0xe8
-
-
-Options
-
-GORACE
environment variable sets race detector options.
-The format is:
-
-GORACE="option1=val1 option2=val2"
-
-
-
-
-
-log_path
(default stderr
): The race detector writes
-its report to a file named log_path.pid
.
-The special names stdout
-and stderr
cause reports to be written to standard output and
-standard error, respectively.
-exitcode
(default 66
): The exit status to use when
-exiting after a detected race.
-strip_path_prefix
(default ""
): Strip this prefix
-from all reported file paths, to make reports more concise.
-history_size
(default 1
): The per-goroutine memory
-access history is 32K * 2**history_size elements
.
-Increasing this value can avoid a "failed to restore the stack" error in reports, at the
-cost of increased memory usage.
-halt_on_error
(default 0
): Controls whether the program
-exits after reporting first data race.
-
-$ GORACE="log_path=/tmp/race/report strip_path_prefix=/my/go/sources/" go test -race
-
-
-Excluding Tests
-
--race
flag, the go
command defines additional
-build tag race
.
-You can use the tag to exclude some code and tests when running the race detector.
-Some examples:
-
-// +build !race
-
-package foo
-
-// The test contains a data race. See issue 123.
-func TestFoo(t *testing.T) {
- // ...
-}
-
-// The test fails under the race detector due to timeouts.
-func TestBar(t *testing.T) {
- // ...
-}
-
-// The test takes too long under the race detector.
-func TestBaz(t *testing.T) {
- // ...
-}
-
-
-How To Use
-
-go test -race
).
-The race detector only finds races that happen at runtime, so it can't find
-races in code paths that are not executed.
-If your tests have incomplete coverage,
-you may find more races by running a binary built with -race
under a realistic
-workload.
-Typical Data Races
-
-Race on loop counter
-
-
-func main() {
- var wg sync.WaitGroup
- wg.Add(5)
- for i := 0; i < 5; i++ {
- go func() {
- fmt.Println(i) // Not the 'i' you are looking for.
- wg.Done()
- }()
- }
- wg.Wait()
-}
-
-
-i
in the function literal is the same variable used by the loop, so
-the read in the goroutine races with the loop increment.
-(This program typically prints 55555, not 01234.)
-The program can be fixed by making a copy of the variable:
-
-func main() {
- var wg sync.WaitGroup
- wg.Add(5)
- for i := 0; i < 5; i++ {
- go func(j int) {
- fmt.Println(j) // Good. Read local copy of the loop counter.
- wg.Done()
- }(i)
- }
- wg.Wait()
-}
-
-
-Accidentally shared variable
-
-
-// ParallelWrite writes data to file1 and file2, returns the errors.
-func ParallelWrite(data []byte) chan error {
- res := make(chan error, 2)
- f1, err := os.Create("file1")
- if err != nil {
- res <- err
- } else {
- go func() {
- // This err is shared with the main goroutine,
- // so the write races with the write below.
- _, err = f1.Write(data)
- res <- err
- f1.Close()
- }()
- }
- f2, err := os.Create("file2") // The second conflicting write to err.
- if err != nil {
- res <- err
- } else {
- go func() {
- _, err = f2.Write(data)
- res <- err
- f2.Close()
- }()
- }
- return res
-}
-
-
-:=
):
-
- ...
- _, err := f1.Write(data)
- ...
- _, err := f2.Write(data)
- ...
-
-
-Unprotected global variable
-
-service
map.
-Concurrent reads and writes of the same map are not safe:
-
-var service map[string]net.Addr
-
-func RegisterService(name string, addr net.Addr) {
- service[name] = addr
-}
-
-func LookupService(name string) net.Addr {
- return service[name]
-}
-
-
-
-var (
- service map[string]net.Addr
- serviceMu sync.Mutex
-)
-
-func RegisterService(name string, addr net.Addr) {
- serviceMu.Lock()
- defer serviceMu.Unlock()
- service[name] = addr
-}
-
-func LookupService(name string) net.Addr {
- serviceMu.Lock()
- defer serviceMu.Unlock()
- return service[name]
-}
-
-
-Primitive unprotected variable
-
-bool
, int
, int64
, etc.),
-as in this example:
-
-type Watchdog struct{ last int64 }
-
-func (w *Watchdog) KeepAlive() {
- w.last = time.Now().UnixNano() // First conflicting access.
-}
-
-func (w *Watchdog) Start() {
- go func() {
- for {
- time.Sleep(time.Second)
- // Second conflicting access.
- if w.last < time.Now().Add(-10*time.Second).UnixNano() {
- fmt.Println("No keepalives for 10 seconds. Dying.")
- os.Exit(1)
- }
- }
- }()
-}
-
-
-sync/atomic
package.
-
-type Watchdog struct{ last int64 }
-
-func (w *Watchdog) KeepAlive() {
- atomic.StoreInt64(&w.last, time.Now().UnixNano())
-}
-
-func (w *Watchdog) Start() {
- go func() {
- for {
- time.Sleep(time.Second)
- if atomic.LoadInt64(&w.last) < time.Now().Add(-10*time.Second).UnixNano() {
- fmt.Println("No keepalives for 10 seconds. Dying.")
- os.Exit(1)
- }
- }
- }()
-}
-
-
-Supported Systems
-
-darwin/amd64
, freebsd/amd64
,
-linux/amd64
, and windows/amd64
.
-Runtime Overhead
-
-Editing {{.Title}}
-
-
diff --git a/content/doc/articles/wiki/final-noclosure.go b/content/doc/articles/wiki/final-noclosure.go
deleted file mode 100644
index b4ce2557..00000000
--- a/content/doc/articles/wiki/final-noclosure.go
+++ /dev/null
@@ -1,103 +0,0 @@
-// Copyright 2010 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package main
-
-import (
- "errors"
- "html/template"
- "io/ioutil"
- "log"
- "net/http"
- "regexp"
-)
-
-type Page struct {
- Title string
- Body []byte
-}
-
-func (p *Page) save() error {
- filename := p.Title + ".txt"
- return ioutil.WriteFile(filename, p.Body, 0600)
-}
-
-func loadPage(title string) (*Page, error) {
- filename := title + ".txt"
- body, err := ioutil.ReadFile(filename)
- if err != nil {
- return nil, err
- }
- return &Page{Title: title, Body: body}, nil
-}
-
-func viewHandler(w http.ResponseWriter, r *http.Request) {
- title, err := getTitle(w, r)
- if err != nil {
- return
- }
- p, err := loadPage(title)
- if err != nil {
- http.Redirect(w, r, "/edit/"+title, http.StatusFound)
- return
- }
- renderTemplate(w, "view", p)
-}
-
-func editHandler(w http.ResponseWriter, r *http.Request) {
- title, err := getTitle(w, r)
- if err != nil {
- return
- }
- p, err := loadPage(title)
- if err != nil {
- p = &Page{Title: title}
- }
- renderTemplate(w, "edit", p)
-}
-
-func saveHandler(w http.ResponseWriter, r *http.Request) {
- title, err := getTitle(w, r)
- if err != nil {
- return
- }
- body := r.FormValue("body")
- p := &Page{Title: title, Body: []byte(body)}
- err = p.save()
- if err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- return
- }
- http.Redirect(w, r, "/view/"+title, http.StatusFound)
-}
-
-func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
- t, err := template.ParseFiles(tmpl + ".html")
- if err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- return
- }
- err = t.Execute(w, p)
- if err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- }
-}
-
-var validPath = regexp.MustCompile("^/(edit|save|view)/([a-zA-Z0-9]+)$")
-
-func getTitle(w http.ResponseWriter, r *http.Request) (string, error) {
- m := validPath.FindStringSubmatch(r.URL.Path)
- if m == nil {
- http.NotFound(w, r)
- return "", errors.New("Invalid Page Title")
- }
- return m[2], nil // The title is the second subexpression.
-}
-
-func main() {
- http.HandleFunc("/view/", viewHandler)
- http.HandleFunc("/edit/", editHandler)
- http.HandleFunc("/save/", saveHandler)
- log.Fatal(http.ListenAndServe(":8080", nil))
-}
diff --git a/content/doc/articles/wiki/final-noerror.go b/content/doc/articles/wiki/final-noerror.go
deleted file mode 100644
index 42a22da9..00000000
--- a/content/doc/articles/wiki/final-noerror.go
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright 2010 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package main
-
-import (
- "html/template"
- "io/ioutil"
- "log"
- "net/http"
-)
-
-type Page struct {
- Title string
- Body []byte
-}
-
-func (p *Page) save() error {
- filename := p.Title + ".txt"
- return ioutil.WriteFile(filename, p.Body, 0600)
-}
-
-func loadPage(title string) (*Page, error) {
- filename := title + ".txt"
- body, err := ioutil.ReadFile(filename)
- if err != nil {
- return nil, err
- }
- return &Page{Title: title, Body: body}, nil
-}
-
-func editHandler(w http.ResponseWriter, r *http.Request) {
- title := r.URL.Path[len("/edit/"):]
- p, err := loadPage(title)
- if err != nil {
- p = &Page{Title: title}
- }
- t, _ := template.ParseFiles("edit.html")
- t.Execute(w, p)
-}
-
-func viewHandler(w http.ResponseWriter, r *http.Request) {
- title := r.URL.Path[len("/view/"):]
- p, _ := loadPage(title)
- t, _ := template.ParseFiles("view.html")
- t.Execute(w, p)
-}
-
-func main() {
- http.HandleFunc("/view/", viewHandler)
- http.HandleFunc("/edit/", editHandler)
- log.Fatal(http.ListenAndServe(":8080", nil))
-}
diff --git a/content/doc/articles/wiki/final-parsetemplate.go b/content/doc/articles/wiki/final-parsetemplate.go
deleted file mode 100644
index a9aa7f28..00000000
--- a/content/doc/articles/wiki/final-parsetemplate.go
+++ /dev/null
@@ -1,92 +0,0 @@
-// Copyright 2010 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package main
-
-import (
- "html/template"
- "io/ioutil"
- "log"
- "net/http"
- "regexp"
-)
-
-type Page struct {
- Title string
- Body []byte
-}
-
-func (p *Page) save() error {
- filename := p.Title + ".txt"
- return ioutil.WriteFile(filename, p.Body, 0600)
-}
-
-func loadPage(title string) (*Page, error) {
- filename := title + ".txt"
- body, err := ioutil.ReadFile(filename)
- if err != nil {
- return nil, err
- }
- return &Page{Title: title, Body: body}, nil
-}
-
-func viewHandler(w http.ResponseWriter, r *http.Request, title string) {
- p, err := loadPage(title)
- if err != nil {
- http.Redirect(w, r, "/edit/"+title, http.StatusFound)
- return
- }
- renderTemplate(w, "view", p)
-}
-
-func editHandler(w http.ResponseWriter, r *http.Request, title string) {
- p, err := loadPage(title)
- if err != nil {
- p = &Page{Title: title}
- }
- renderTemplate(w, "edit", p)
-}
-
-func saveHandler(w http.ResponseWriter, r *http.Request, title string) {
- body := r.FormValue("body")
- p := &Page{Title: title, Body: []byte(body)}
- err := p.save()
- if err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- return
- }
- http.Redirect(w, r, "/view/"+title, http.StatusFound)
-}
-
-func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
- t, err := template.ParseFiles(tmpl + ".html")
- if err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- return
- }
- err = t.Execute(w, p)
- if err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- }
-}
-
-var validPath = regexp.MustCompile("^/(edit|save|view)/([a-zA-Z0-9]+)$")
-
-func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- m := validPath.FindStringSubmatch(r.URL.Path)
- if m == nil {
- http.NotFound(w, r)
- return
- }
- fn(w, r, m[2])
- }
-}
-
-func main() {
- http.HandleFunc("/view/", makeHandler(viewHandler))
- http.HandleFunc("/edit/", makeHandler(editHandler))
- http.HandleFunc("/save/", makeHandler(saveHandler))
- log.Fatal(http.ListenAndServe(":8080", nil))
-}
diff --git a/content/doc/articles/wiki/final-template.go b/content/doc/articles/wiki/final-template.go
deleted file mode 100644
index 7ea480e5..00000000
--- a/content/doc/articles/wiki/final-template.go
+++ /dev/null
@@ -1,66 +0,0 @@
-// Copyright 2010 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package main
-
-import (
- "html/template"
- "io/ioutil"
- "log"
- "net/http"
-)
-
-type Page struct {
- Title string
- Body []byte
-}
-
-func (p *Page) save() error {
- filename := p.Title + ".txt"
- return ioutil.WriteFile(filename, p.Body, 0600)
-}
-
-func loadPage(title string) (*Page, error) {
- filename := title + ".txt"
- body, err := ioutil.ReadFile(filename)
- if err != nil {
- return nil, err
- }
- return &Page{Title: title, Body: body}, nil
-}
-
-func editHandler(w http.ResponseWriter, r *http.Request) {
- title := r.URL.Path[len("/edit/"):]
- p, err := loadPage(title)
- if err != nil {
- p = &Page{Title: title}
- }
- renderTemplate(w, "edit", p)
-}
-
-func viewHandler(w http.ResponseWriter, r *http.Request) {
- title := r.URL.Path[len("/view/"):]
- p, _ := loadPage(title)
- renderTemplate(w, "view", p)
-}
-
-func saveHandler(w http.ResponseWriter, r *http.Request) {
- title := r.URL.Path[len("/save/"):]
- body := r.FormValue("body")
- p := &Page{Title: title, Body: []byte(body)}
- p.save()
- http.Redirect(w, r, "/view/"+title, http.StatusFound)
-}
-
-func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
- t, _ := template.ParseFiles(tmpl + ".html")
- t.Execute(w, p)
-}
-
-func main() {
- http.HandleFunc("/view/", viewHandler)
- http.HandleFunc("/edit/", editHandler)
- http.HandleFunc("/save/", saveHandler)
- log.Fatal(http.ListenAndServe(":8080", nil))
-}
diff --git a/content/doc/articles/wiki/final-test.patch b/content/doc/articles/wiki/final-test.patch
deleted file mode 100644
index fd7d6253..00000000
--- a/content/doc/articles/wiki/final-test.patch
+++ /dev/null
@@ -1,27 +0,0 @@
---- final.go 2017-08-31 13:19:00.422925489 -0700
-+++ final-test.go 2017-08-31 13:23:43.381391659 -0700
-@@ -8,6 +8,7 @@
- "html/template"
- "io/ioutil"
- "log"
-+ "net"
- "net/http"
- "regexp"
- )
-@@ -86,5 +87,15 @@
- http.HandleFunc("/edit/", makeHandler(editHandler))
- http.HandleFunc("/save/", makeHandler(saveHandler))
-
-- log.Fatal(http.ListenAndServe(":8080", nil))
-+ l, err := net.Listen("tcp", "127.0.0.1:0")
-+ if err != nil {
-+ log.Fatal(err)
-+ }
-+ err = ioutil.WriteFile("final-test-port.txt", []byte(l.Addr().String()), 0644)
-+ if err != nil {
-+ log.Fatal(err)
-+ }
-+ s := &http.Server{}
-+ s.Serve(l)
-+ return
- }
diff --git a/content/doc/articles/wiki/final.go b/content/doc/articles/wiki/final.go
deleted file mode 100644
index 0f6646ba..00000000
--- a/content/doc/articles/wiki/final.go
+++ /dev/null
@@ -1,90 +0,0 @@
-// Copyright 2010 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package main
-
-import (
- "html/template"
- "io/ioutil"
- "log"
- "net/http"
- "regexp"
-)
-
-type Page struct {
- Title string
- Body []byte
-}
-
-func (p *Page) save() error {
- filename := p.Title + ".txt"
- return ioutil.WriteFile(filename, p.Body, 0600)
-}
-
-func loadPage(title string) (*Page, error) {
- filename := title + ".txt"
- body, err := ioutil.ReadFile(filename)
- if err != nil {
- return nil, err
- }
- return &Page{Title: title, Body: body}, nil
-}
-
-func viewHandler(w http.ResponseWriter, r *http.Request, title string) {
- p, err := loadPage(title)
- if err != nil {
- http.Redirect(w, r, "/edit/"+title, http.StatusFound)
- return
- }
- renderTemplate(w, "view", p)
-}
-
-func editHandler(w http.ResponseWriter, r *http.Request, title string) {
- p, err := loadPage(title)
- if err != nil {
- p = &Page{Title: title}
- }
- renderTemplate(w, "edit", p)
-}
-
-func saveHandler(w http.ResponseWriter, r *http.Request, title string) {
- body := r.FormValue("body")
- p := &Page{Title: title, Body: []byte(body)}
- err := p.save()
- if err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- return
- }
- http.Redirect(w, r, "/view/"+title, http.StatusFound)
-}
-
-var templates = template.Must(template.ParseFiles("edit.html", "view.html"))
-
-func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
- err := templates.ExecuteTemplate(w, tmpl+".html", p)
- if err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- }
-}
-
-var validPath = regexp.MustCompile("^/(edit|save|view)/([a-zA-Z0-9]+)$")
-
-func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- m := validPath.FindStringSubmatch(r.URL.Path)
- if m == nil {
- http.NotFound(w, r)
- return
- }
- fn(w, r, m[2])
- }
-}
-
-func main() {
- http.HandleFunc("/view/", makeHandler(viewHandler))
- http.HandleFunc("/edit/", makeHandler(editHandler))
- http.HandleFunc("/save/", makeHandler(saveHandler))
-
- log.Fatal(http.ListenAndServe(":8080", nil))
-}
diff --git a/content/doc/articles/wiki/get.go b/content/doc/articles/wiki/get.go
deleted file mode 100644
index b3e464b3..00000000
--- a/content/doc/articles/wiki/get.go
+++ /dev/null
@@ -1,63 +0,0 @@
-// Copyright 2011 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package main
-
-import (
- "flag"
- "fmt"
- "io"
- "log"
- "net"
- "net/http"
- "os"
- "strings"
- "time"
-)
-
-var (
- post = flag.String("post", "", "urlencoded form data to POST")
- addr = flag.Bool("addr", false, "find open address and print to stdout")
- wait = flag.Duration("wait_for_port", 0, "if non-zero, the amount of time to wait for the address to become available")
-)
-
-func main() {
- flag.Parse()
- if *addr {
- l, err := net.Listen("tcp", "127.0.0.1:0")
- if err != nil {
- log.Fatal(err)
- }
- defer l.Close()
- fmt.Print(l.Addr())
- return
- }
- url := flag.Arg(0)
- if url == "" {
- log.Fatal("no url supplied")
- }
- var r *http.Response
- var err error
- loopUntil := time.Now().Add(*wait)
- for {
- if *post != "" {
- b := strings.NewReader(*post)
- r, err = http.Post(url, "application/x-www-form-urlencoded", b)
- } else {
- r, err = http.Get(url)
- }
- if err == nil || *wait == 0 || time.Now().After(loopUntil) {
- break
- }
- time.Sleep(100 * time.Millisecond)
- }
- if err != nil {
- log.Fatal(err)
- }
- defer r.Body.Close()
- _, err = io.Copy(os.Stdout, r.Body)
- if err != nil {
- log.Fatal(err)
- }
-}
diff --git a/content/doc/articles/wiki/http-sample.go b/content/doc/articles/wiki/http-sample.go
deleted file mode 100644
index 9bc2084c..00000000
--- a/content/doc/articles/wiki/http-sample.go
+++ /dev/null
@@ -1,16 +0,0 @@
-package main
-
-import (
- "fmt"
- "log"
- "net/http"
-)
-
-func handler(w http.ResponseWriter, r *http.Request) {
- fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
-}
-
-func main() {
- http.HandleFunc("/", handler)
- log.Fatal(http.ListenAndServe(":8080", nil))
-}
diff --git a/content/doc/articles/wiki/index.html b/content/doc/articles/wiki/index.html
deleted file mode 100644
index b7ab2cc6..00000000
--- a/content/doc/articles/wiki/index.html
+++ /dev/null
@@ -1,740 +0,0 @@
-
-
-Introduction
-
-
-
-
-net/http
package to build web applications
-html/template
package to process HTML templatesregexp
package to validate user input
-
-
-Getting Started
-
-$
to represent the command prompt.
-GOPATH
and cd to it:
-
-$ mkdir gowiki
-$ cd gowiki
-
-
-wiki.go
, open it in your favorite editor, and
-add the following lines:
-
-package main
-
-import (
- "fmt"
- "io/ioutil"
-)
-
-
-fmt
and ioutil
packages from the Go
-standard library. Later, as we implement additional functionality, we will
-add more packages to this import
declaration.
-Data Structures
-
-Page
as a struct with two fields representing
-the title and body.
-[]byte
means "a byte
slice".
-(See Slices: usage and
-internals for more on slices.)
-The Body
element is a []byte
rather than
-string
because that is the type expected by the io
-libraries we will use, as you'll see below.
-Page
struct describes how page data will be stored in memory.
-But what about persistent storage? We can address that by creating a
-save
method on Page
:
-save
that
-takes as its receiver p
, a pointer to Page
. It takes
-no parameters, and returns a value of type error
."
-Page
's Body
to a text
-file. For simplicity, we will use the Title
as the file name.
-save
method returns an error
value because
-that is the return type of WriteFile
(a standard library function
-that writes a byte slice to a file). The save
method returns the
-error value, to let the application handle it should anything go wrong while
-writing the file. If all goes well, Page.save()
will return
-nil
(the zero-value for pointers, interfaces, and some other
-types).
-0600
, passed as the third parameter to
-WriteFile
, indicates that the file should be created with
-read-write permissions for the current user only. (See the Unix man page
-open(2)
for details.)
-loadPage
constructs the file name from the title
-parameter, reads the file's contents into a new variable body
, and
-returns a pointer to a Page
literal constructed with the proper
-title and body values.
-io.ReadFile
returns []byte
and error
.
-In loadPage
, error isn't being handled yet; the "blank identifier"
-represented by the underscore (_
) symbol is used to throw away the
-error return value (in essence, assigning the value to nothing).
-ReadFile
encounters an error? For example,
-the file might not exist. We should not ignore such errors. Let's modify the
-function to return *Page
and error
.
-nil
then it has successfully loaded a Page. If not, it will be an
-error
that can be handled by the caller (see the
-language specification for details).
-main
function to test what we've
-written:
-TestPage.txt
-would be created, containing the contents of p1
. The file would
-then be read into the struct p2
, and its Body
element
-printed to the screen.
-
-$ go build wiki.go
-$ ./wiki
-This is a sample Page.
-
-
-wiki
" without the
-"./
" to run the program.)
-Introducing the
-
-net/http
package (an interlude)main
function begins with a call to
-http.HandleFunc
, which tells the http
package to
-handle all requests to the web root ("/"
) with
-handler
.
-http.ListenAndServe
, specifying that it should
-listen on port 8080 on any interface (":8080"
). (Don't
-worry about its second parameter, nil
, for now.)
-This function will block until the program is terminated.
-ListenAndServe
always returns an error, since it only returns when an
-unexpected error occurs.
-In order to log that error we wrap the function call with log.Fatal
.
-handler
is of the type http.HandlerFunc
.
-It takes an http.ResponseWriter
and an http.Request
as
-its arguments.
-http.ResponseWriter
value assembles the HTTP server's response; by writing
-to it, we send data to the HTTP client.
-http.Request
is a data structure that represents the client
-HTTP request. r.URL.Path
is the path component
-of the request URL. The trailing [1:]
means
-"create a sub-slice of Path
from the 1st character to the end."
-This drops the leading "/" from the path name.
-http://localhost:8080/monkeys
-Hi there, I love monkeys!
-
-Using
-
-net/http
to serve wiki pagesnet/http
package, it must be imported:
-
-import (
- "fmt"
- "io/ioutil"
- "net/http"
-)
-
-
-viewHandler
that will allow users to
-view a wiki page. It will handle URLs prefixed with "/view/".
-_
to ignore the error
-return value from loadPage
. This is done here for simplicity
-and generally considered bad practice. We will attend to this later.
-r.URL.Path
,
-the path component of the request URL.
-The Path
is re-sliced with [len("/view/"):]
to drop
-the leading "/view/"
component of the request path.
-This is because the path will invariably begin with "/view/"
,
-which is not part of the page's title.
-w
, the http.ResponseWriter
.
-main
function to
-initialize http
using the viewHandler
to handle
-any requests under the path /view/
.
-test.txt
), compile our code, and
-try serving a wiki page.
-test.txt
file in your editor, and save the string "Hello world" (without quotes)
-in it.
-
-$ go build wiki.go
-$ ./wiki
-
-
-wiki
" without the
-"./
" to run the program.)
-http://localhost:8080/view/test
-should show a page titled "test" containing the words "Hello world".
-Editing Pages
-
-editHandler
to display an 'edit page' form,
-and the other named saveHandler
to save the data entered via the
-form.
-main()
:
-editHandler
loads the page
-(or, if it doesn't exist, create an empty Page
struct),
-and displays an HTML form.
-The
-
-html/template
packagehtml/template
package is part of the Go standard library.
-We can use html/template
to keep the HTML in a separate file,
-allowing us to change the layout of our edit page without modifying the
-underlying Go code.
-html/template
to the list of imports. We
-also won't be using fmt
anymore, so we have to remove that.
-
-import (
- "html/template"
- "io/ioutil"
- "net/http"
-)
-
-
-edit.html
, and add the following lines:
-editHandler
to use the template, instead of the hard-coded
-HTML:
-template.ParseFiles
will read the contents of
-edit.html
and return a *template.Template
.
-t.Execute
executes the template, writing the
-generated HTML to the http.ResponseWriter
.
-The .Title
and .Body
dotted identifiers refer to
-p.Title
and p.Body
.
-printf "%s" .Body
instruction is a function call
-that outputs .Body
as a string instead of a stream of bytes,
-the same as a call to fmt.Printf
.
-The html/template
package helps guarantee that only safe and
-correct-looking HTML is generated by template actions. For instance, it
-automatically escapes any greater than sign (>
), replacing it
-with >
, to make sure user data does not corrupt the form
-HTML.
-viewHandler
called view.html
:
-viewHandler
accordingly:
-main
, we can once again build and test our program.
-Click here to view the code we've written so far.
-Handling non-existent pages
-
-/view/APageThatDoesntExist
? You'll see a page containing
-HTML. This is because it ignores the error return value from
-loadPage
and continues to try and fill out the template
-with no data. Instead, if the requested Page doesn't exist, it should
-redirect the client to the edit Page so the content may be created:
-http.Redirect
function adds an HTTP status code of
-http.StatusFound
(302) and a Location
-header to the HTTP response.
-Saving Pages
-
-saveHandler
will handle the submission of forms
-located on the edit pages. After uncommenting the related line in
-main
, let's implement the handler:
-Body
, are stored in a new Page
.
-The save()
method is then called to write the data to a file,
-and the client is redirected to the /view/
page.
-FormValue
is of type string
.
-We must convert that value to []byte
before it will fit into
-the Page
struct. We use []byte(body)
to perform
-the conversion.
-Error handling
-
-renderTemplate
:
-http.Error
function sends a specified HTTP response code
-(in this case "Internal Server Error") and error message.
-Already the decision to put this in a separate function is paying off.
-saveHandler
:
-p.save()
will be reported
-to the user.
-Template caching
-
-renderTemplate
calls
-ParseFiles
every time a page is rendered.
-A better approach would be to call ParseFiles
once at program
-initialization, parsing all templates into a single *Template
.
-Then we can use the
-ExecuteTemplate
-method to render a specific template.
-templates
, and initialize
-it with ParseFiles
.
-template.Must
is a convenience wrapper that panics
-when passed a non-nil error
value, and otherwise returns the
-*Template
unaltered. A panic is appropriate here; if the templates
-can't be loaded the only sensible thing to do is exit the program.
-ParseFiles
function takes any number of string arguments that
-identify our template files, and parses those files into templates that are
-named after the base file name. If we were to add more templates to our
-program, we would add their names to the ParseFiles
call's
-arguments.
-renderTemplate
function to call the
-templates.ExecuteTemplate
method with the name of the appropriate
-template:
-".html"
to the tmpl
argument.
-Validation
-
-"regexp"
to the import
list.
-Then we can create a global variable to store our validation
-expression:
-regexp.MustCompile
will parse and compile the
-regular expression, and return a regexp.Regexp
.
-MustCompile
is distinct from Compile
in that it will
-panic if the expression compilation fails, while Compile
returns
-an error
as a second parameter.
-validPath
-expression to validate path and extract the page title:
-nil
-error value. If the title is invalid, the function will write a
-"404 Not Found" error to the HTTP connection, and return an error to the
-handler. To create a new error, we have to import the errors
-package.
-getTitle
in each of the handlers:
-Introducing Function Literals and Closures
-
-
-func viewHandler(w http.ResponseWriter, r *http.Request, title string)
-func editHandler(w http.ResponseWriter, r *http.Request, title string)
-func saveHandler(w http.ResponseWriter, r *http.Request, title string)
-
-
-http.HandlerFunc
-(suitable to be passed to the function http.HandleFunc
):
-
-func makeHandler(fn func (http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- // Here we will extract the page title from the Request,
- // and call the provided handler 'fn'
- }
-}
-
-
-fn
(the single argument
-to makeHandler
) is enclosed by the closure. The variable
-fn
will be one of our save, edit, or view handlers.
-getTitle
and use it here
-(with some minor modifications):
-makeHandler
is a function that takes
-an http.ResponseWriter
and http.Request
(in other
-words, an http.HandlerFunc
).
-The closure extracts the title
from the request path, and
-validates it with the TitleValidator
regexp. If the
-title
is invalid, an error will be written to the
-ResponseWriter
using the http.NotFound
function.
-If the title
is valid, the enclosed handler function
-fn
will be called with the ResponseWriter
,
-Request
, and title
as arguments.
-makeHandler
in
-main
, before they are registered with the http
-package:
-getTitle
from the handler functions,
-making them much simpler:
-Try it out!
-
-
-$ go build wiki.go
-$ ./wiki
-
-
-Other tasks
-
-
-
diff --git a/content/doc/articles/wiki/notemplate.go b/content/doc/articles/wiki/notemplate.go
deleted file mode 100644
index 0fda7a98..00000000
--- a/content/doc/articles/wiki/notemplate.go
+++ /dev/null
@@ -1,57 +0,0 @@
-// Copyright 2010 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package main
-
-import (
- "fmt"
- "io/ioutil"
- "log"
- "net/http"
-)
-
-type Page struct {
- Title string
- Body []byte
-}
-
-func (p *Page) save() error {
- filename := p.Title + ".txt"
- return ioutil.WriteFile(filename, p.Body, 0600)
-}
-
-func loadPage(title string) (*Page, error) {
- filename := title + ".txt"
- body, err := ioutil.ReadFile(filename)
- if err != nil {
- return nil, err
- }
- return &Page{Title: title, Body: body}, nil
-}
-
-func viewHandler(w http.ResponseWriter, r *http.Request) {
- title := r.URL.Path[len("/view/"):]
- p, _ := loadPage(title)
- fmt.Fprintf(w, "tmpl/
and page data in data/
.
-/view/FrontPage
.[PageName]
to
- <a href="/view/PageName">PageName</a>
.
- (hint: you could use regexp.ReplaceAllFunc
to do this)
- %s
Editing %s
"+
- "",
- p.Title, p.Title, p.Body)
-}
-
-func main() {
- http.HandleFunc("/view/", viewHandler)
- http.HandleFunc("/edit/", editHandler)
- log.Fatal(http.ListenAndServe(":8080", nil))
-}
diff --git a/content/doc/articles/wiki/part1-noerror.go b/content/doc/articles/wiki/part1-noerror.go
deleted file mode 100644
index 7577b7b4..00000000
--- a/content/doc/articles/wiki/part1-noerror.go
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright 2010 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package main
-
-import (
- "fmt"
- "io/ioutil"
-)
-
-type Page struct {
- Title string
- Body []byte
-}
-
-func (p *Page) save() error {
- filename := p.Title + ".txt"
- return ioutil.WriteFile(filename, p.Body, 0600)
-}
-
-func loadPage(title string) *Page {
- filename := title + ".txt"
- body, _ := ioutil.ReadFile(filename)
- return &Page{Title: title, Body: body}
-}
-
-func main() {
- p1 := &Page{Title: "TestPage", Body: []byte("This is a sample page.")}
- p1.save()
- p2 := loadPage("TestPage")
- fmt.Println(string(p2.Body))
-}
diff --git a/content/doc/articles/wiki/part1.go b/content/doc/articles/wiki/part1.go
deleted file mode 100644
index d7bf1be9..00000000
--- a/content/doc/articles/wiki/part1.go
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright 2010 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package main
-
-import (
- "fmt"
- "io/ioutil"
-)
-
-type Page struct {
- Title string
- Body []byte
-}
-
-func (p *Page) save() error {
- filename := p.Title + ".txt"
- return ioutil.WriteFile(filename, p.Body, 0600)
-}
-
-func loadPage(title string) (*Page, error) {
- filename := title + ".txt"
- body, err := ioutil.ReadFile(filename)
- if err != nil {
- return nil, err
- }
- return &Page{Title: title, Body: body}, nil
-}
-
-func main() {
- p1 := &Page{Title: "TestPage", Body: []byte("This is a sample Page.")}
- p1.save()
- p2, _ := loadPage("TestPage")
- fmt.Println(string(p2.Body))
-}
diff --git a/content/doc/articles/wiki/part2.go b/content/doc/articles/wiki/part2.go
deleted file mode 100644
index 30f9dcf1..00000000
--- a/content/doc/articles/wiki/part2.go
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright 2010 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package main
-
-import (
- "fmt"
- "io/ioutil"
- "log"
- "net/http"
-)
-
-type Page struct {
- Title string
- Body []byte
-}
-
-func (p *Page) save() error {
- filename := p.Title + ".txt"
- return ioutil.WriteFile(filename, p.Body, 0600)
-}
-
-func loadPage(title string) (*Page, error) {
- filename := title + ".txt"
- body, err := ioutil.ReadFile(filename)
- if err != nil {
- return nil, err
- }
- return &Page{Title: title, Body: body}, nil
-}
-
-func viewHandler(w http.ResponseWriter, r *http.Request) {
- title := r.URL.Path[len("/view/"):]
- p, _ := loadPage(title)
- fmt.Fprintf(w, "%s
Editing Test
-
-
diff --git a/content/doc/articles/wiki/test_view.good b/content/doc/articles/wiki/test_view.good
deleted file mode 100644
index 07e8edb2..00000000
--- a/content/doc/articles/wiki/test_view.good
+++ /dev/null
@@ -1,5 +0,0 @@
-Test
-
-{{.Title}}
-
-A Quick Guide to Go's Assembler
-
-gc
Go compiler.
-The document is not comprehensive.
-MOV
-what the toolchain actually generates for that operation might
-not be a move instruction at all, perhaps a clear or load.
-Or it might correspond exactly to the machine instruction with that name.
-In general, machine-specific operations tend to appear as themselves, while more general concepts like
-memory move and subroutine call and return are more abstract.
-The details vary with architecture, and we apologize for the imprecision; the situation is not well-defined.
-runtime
and
-math/big
.
-You can also examine what the compiler emits as assembly code
-(the actual output may differ from what you see here):
-
-$ cat x.go
-package main
-
-func main() {
- println(3)
-}
-$ GOOS=linux GOARCH=amd64 go tool compile -S x.go # or: go build -gcflags -S x.go
-
---- prog list "main" ---
-0000 (x.go:3) TEXT main+0(SB),$8-0
-0001 (x.go:3) FUNCDATA $0,gcargs·0+0(SB)
-0002 (x.go:3) FUNCDATA $1,gclocals·0+0(SB)
-0003 (x.go:4) MOVQ $3,(SP)
-0004 (x.go:4) PCDATA $0,$8
-0005 (x.go:4) CALL ,runtime.printint+0(SB)
-0006 (x.go:4) PCDATA $0,$-1
-0007 (x.go:4) PCDATA $0,$0
-0008 (x.go:4) CALL ,runtime.printnl+0(SB)
-0009 (x.go:4) PCDATA $0,$-1
-0010 (x.go:5) RET ,
-...
-
-
-FUNCDATA
and PCDATA
directives contain information
-for use by the garbage collector; they are introduced by the compiler.
-Constants
-
-3&1<<2
is 4, not 0—it parses as (3&1)<<2
-not 3&(1<<2)
.
-Also, constants are always evaluated as 64-bit unsigned integers.
-Thus -2
is not the integer value minus two,
-but the unsigned 64-bit integer with the same bit pattern.
-The distinction rarely matters but
-to avoid ambiguity, division or right shift where the right operand's
-high bit is set is rejected.
-Symbols
-
-R1
or LR
,
-are predefined and refer to registers.
-The exact set depends on the architecture.
-
-
-
-
-FP
: Frame pointer: arguments and locals.
-PC
: Program counter:
-jumps and branches.
-SB
: Static base pointer: global symbols.
-SP
: Stack pointer: top of stack.
-FP
(arguments and locals) and SB
(globals).
-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.
-Adding an offset to the name refers to that offset from the symbol's address, so
-foo+4(SB)
is four bytes past the start of foo
.
-FP
pseudo-register is a virtual frame pointer
-used to refer to function arguments.
-The compilers maintain a virtual frame pointer and refer to the arguments on the stack as offsets from that pseudo-register.
-Thus 0(FP)
is the first argument to the function,
-8(FP)
is the second (on a 64-bit machine), and so on.
-However, when referring to a function argument this way, it is necessary to place a name
-at the beginning, as in first_arg+0(FP)
and second_arg+8(FP)
.
-(The meaning of the offset—offset from the frame pointer—distinct
-from its use with SB
, where it is an offset from the symbol.)
-The assembler enforces this convention, rejecting plain 0(FP)
and 8(FP)
.
-The actual name is semantically irrelevant but should be used to document
-the argument's name.
-It is worth stressing that FP
is always a
-pseudo-register, not a hardware
-register, even on architectures with a hardware frame pointer.
-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
.
-SP
pseudo-register is a virtual stack pointer
-used to refer to frame-local variables and the arguments being
-prepared for function calls.
-It points to the top of the local stack frame, so references should use negative offsets
-in the range [−framesize, 0):
-x-8(SP)
, y-4(SP)
, and so on.
-SP
,
-the name prefix distinguishes
-references to the virtual stack pointer from references to the architectural
-SP
register.
-That is, x-8(SP)
and -8(SP)
-are different memory locations:
-the first refers to the virtual stack pointer pseudo-register,
-while the second refers to the
-hardware's SP
register.
-SP
and PC
are
-traditionally aliases for a physical, numbered register,
-in the Go assembler the names SP
and PC
-are still treated specially;
-for instance, references to SP
require a symbol,
-much like FP
.
-To access the actual hardware register use the true R
name.
-For example, on the ARM architecture the hardware
-SP
and PC
are accessible as
-R13
and R15
.
-
-label:
- MOVW $0, R1
- JMP label
-
-
-name(SB)
, but not offsets from symbols,
-such as name+4(SB)
.
-g
register renaming on ARM.)
-fmt.Printf
or math/rand.Int
.
-Because the assembler's parser treats period and slash as punctuation,
-those strings cannot be used directly as identifier names.
-Instead, the assembler allows the middle dot character U+00B7
-and the division slash U+2215 in identifiers and rewrites them to
-plain period and slash.
-Within an assembler source file, the symbols above are written as
-fmt·Printf
and math∕rand·Int
.
-The assembly listings generated by the compilers when using the -S
flag
-show the period and slash directly instead of the Unicode replacements
-required by the assemblers.
-·Int
.
-This convention avoids the need to hard-code a package's import path in its
-own source code, making it easier to move the code from one location to another.
-Directives
-
-TEXT
-directive declares the symbol runtime·profileloop
and the instructions
-that follow form the body of the function.
-The last instruction in a TEXT
block must be some sort of jump, usually a RET
(pseudo-)instruction.
-(If it's not, the linker will append a jump-to-itself instruction; there is no fallthrough in TEXTs
.)
-After the symbol, the arguments are flags (see below)
-and the frame size, a constant (but see below):
-
-TEXT runtime·profileloop(SB),NOSPLIT,$8
- MOVQ $runtime·profileloop1(SB), CX
- MOVQ CX, 0(SP)
- CALL runtime·externalthreadhandler(SB)
- RET
-
-
-$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.
-SB
.
-This function would be called from Go source for package runtime
using the
-simple name profileloop
.
-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 symbol+offset(SB)/width, value
-
-
-DATA
directives for a given symbol must be written with increasing offsets.
-GLOBL
directive declares a symbol to be global.
-The arguments are optional flags and the size of the data being declared as a global,
-which will have initial value all zeros unless a DATA
directive
-has initialized it.
-The GLOBL
directive must follow any corresponding DATA
directives.
-
-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
-
-
-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.
-#include
file textflag.h
, are:
-
-
-
-NOPROF
= 1
-
-(For TEXT
items.)
-Don't profile the marked function. This flag is deprecated.
-DUPOK
= 2
-
-It is legal to have multiple instances of this symbol in a single binary.
-The linker will choose one of the duplicates to use.
-NOSPLIT
= 4
-
-(For TEXT
items.)
-Don't insert the preamble to check if the stack must be split.
-The frame for the routine, plus anything it calls, must fit in the
-spare space at the top of the stack segment.
-Used to protect routines such as the stack splitting code itself.
-RODATA
= 8
-
-(For DATA
and GLOBL
items.)
-Put this data in a read-only section.
-NOPTR
= 16
-
-(For DATA
and GLOBL
items.)
-This data contains no pointers and therefore does not need to be
-scanned by the garbage collector.
-WRAPPER
= 32
-
-(For TEXT
items.)
-This is a wrapper function and should not count as disabling recover
.
-NEEDCTXT
= 64
-
-(For TEXT
items.)
-This function is a closure so it uses its incoming context register.
-Runtime Coordination
-
-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.
-Syscall
in package syscall
should
-use the name ·Syscall
instead of the equivalent name
-syscall·Syscall
in its TEXT
directive).
-For more complex situations, explicit annotation is needed.
-These annotations use pseudo-instructions defined in the standard
-#include
file funcdata.h
.
-$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
.
-$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.
-go
vet
check that
-the offsets being used to access them are correct.
-Architecture-specific details
-
-obj
support library for
-that architecture, located in the directory src/cmd/internal/obj/arm
.
-In that directory is a file a.out.go
; it contains
-a long list of constants starting with A
, like this:
-
-const (
- AAND = obj.ABaseARM + obj.A_ARCHSPECIFIC + iota
- AEOR
- ASUB
- ARSB
- AADD
- ...
-
-
-A
in this list, so AAND
-represents the bitwise and instruction,
-AND
(without the leading A
),
-and is written in assembly source as AND
.
-The enumeration is mostly in alphabetical order.
-(The architecture-independent AXXX
, defined in the
-cmd/internal/obj
package,
-represents an invalid instruction).
-The sequence of the A
names has nothing to do with the actual
-encoding of the machine instructions.
-The cmd/internal/obj
package takes care of that detail.
-cmd/internal/obj/x86/a.out.go
.
-(R1)
(register indirect),
-4(R1)
(register indirect with offset), and
-$foo(SB)
(absolute address).
-The assembler also supports some (not necessarily all) addressing modes
-specific to each architecture.
-The sections below list these.
-MOVQ
$0,
CX
clears CX
.
-This rule applies even on architectures where the conventional notation uses the opposite direction.
-32-bit Intel 386
-
-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
-a special header, go_asm.h
:
-
-#include "go_asm.h"
-
-
-get_tls
macro loads its argument register
-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 g_m(AX), BX // Move g.m into BX.
-
-
-
-
-
-
-(DI)(BX*2)
: The location at address DI
plus BX*2
.
-64(DI)(BX*2)
: The location at address DI
plus BX*2
plus 64.
-These modes accept only 1, 2, 4, and 8 as scale factors.
--dynlink
or -shared
modes,
-any load or store of a fixed memory location such as a global variable
-must be assumed to overwrite CX
.
-Therefore, to be safe for use with these modes,
-assembly sources should typically avoid CX except between memory references.
-64-bit Intel 386 (a.k.a. amd64)
-
-m
and g
-pointers on the 64-bit version is the same as on the 32-bit 386,
-except it uses MOVQ
rather than MOVL
:
-
-get_tls(CX)
-MOVQ g(CX), AX // Move g into AX.
-MOVQ g_m(AX), BX // Move g.m into BX.
-
-
-ARM
-
-R10
and R11
-are reserved by the compiler and linker.
-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.
-DIV
or MOD
-that may not be expressible using a single hardware instruction.
-It implements these forms as multiple instructions, often using the R11
register
-to hold temporary values.
-Hand-written assembly can use R11
, but doing so requires
-being sure that the linker is not also using it to implement any of the other
-instructions in the function.
-TEXT
, specifying frame size $-4
-tells the linker that this is a leaf function that does not need to save LR
on entry.
-SP
always refers to the virtual stack pointer described earlier.
-For the hardware register, use R13
.
-MOVW.EQ
.
-Multiple codes may be appended: MOVM.IA.W
.
-The order of the code modifiers is irrelevant.
-
-
-
-
-R0->16
-
-R0>>16
-
-R0<<16
-
-R0@>16
:
-For <<
, left shift R0
by 16 bits.
-The other codes are ->
(arithmetic right shift),
->>
(logical right shift), and
-@>
(rotate right).
-R0->R1
-
-R0>>R1
-
-R0<<R1
-
-R0@>R1
:
-For <<
, left shift R0
by the count in R1
.
-The other codes are ->
(arithmetic right shift),
->>
(logical right shift), and
-@>
(rotate right).
-
-[R0,g,R12-R15]
: For multi-register instructions, the set comprising
-R0
, g
, and R12
through R15
inclusive.
-(R5, R6)
: Destination register pair.
-ARM64
-
-R18
is the "platform register", reserved on the Apple platform.
-To prevent accidental misuse, the register is named R18_PLATFORM
.
-R27
and R28
are reserved by the compiler and linker.
-R29
is the frame pointer.
-R30
is the link register.
-P
(postincrement) and W
-(preincrement):
-MOVW.P
, MOVW.W
-
-
-
-
-R0->16
-
-R0>>16
-
-R0<<16
-
-R0@>16
:
-These are the same as on the 32-bit ARM.
-$(8<<12)
:
-Left shift the immediate value 8
by 12
bits.
-8(R0)
:
-Add the value of R0
and 8
.
-(R2)(R0)
:
-The location at R0
plus R2
.
-R0.UXTB
-
-R0.UXTB<<imm
:
-UXTB
: extract an 8-bit value from the low-order bits of R0
and zero-extend it to the size of R0
.
-R0.UXTB<<imm
: left shift the result of R0.UXTB
by imm
bits.
-The imm
value can be 0, 1, 2, 3, or 4.
-The other extensions include UXTH
(16-bit), UXTW
(32-bit), and UXTX
(64-bit).
-R0.SXTB
-
-R0.SXTB<<imm
:
-SXTB
: extract an 8-bit value from the low-order bits of R0
and sign-extend it to the size of R0
.
-R0.SXTB<<imm
: left shift the result of R0.SXTB
by imm
bits.
-The imm
value can be 0, 1, 2, 3, or 4.
-The other extensions include SXTH
(16-bit), SXTW
(32-bit), and SXTX
(64-bit).
-(R5, R6)
: Register pair for LDAXP
/LDP
/LDXP
/STLXP
/STP
/STP
.
-64-bit PowerPC, a.k.a. ppc64
-
-
-
-
-
-(R5)(R6*1)
: The location at R5
plus R6
. It is a scaled
-mode as on the x86, but the only scale allowed is 1
.
-(R5+R6)
: Alias for (R5)(R6*1)
-IBM z/Architecture, a.k.a. s390x
-
-R10
and R11
are reserved.
-The assembler uses them to hold temporary values when assembling some instructions.
-R13
points to the g
(goroutine) structure.
-This register must be referred to as g
; the name R13
is not recognized.
-R15
points to the stack frame and should typically only be accessed using the
-virtual registers SP
and FP
.
-LMG
(R9),
R5,
R7
would load
-R5
, R6
and R7
with the 64-bit values at
-0(R9)
, 8(R9)
and 16(R9)
respectively.
-MVC
and XC
are written
-with the length as the first argument.
-For example, XC
$8,
(R9),
(R9)
would clear
-eight bytes at the address specified in R9
.
-VLEIF
$1,
$16,
V2
will load
-the value sixteen into index one of V2
.
-Care should be taken when using vector instructions to ensure that they are available at
-runtime.
-To use vector instructions a machine must have both the vector facility (bit 129 in the
-facility list) and kernel support.
-Without kernel support a vector instruction will have no effect (it will be equivalent
-to a NOP
instruction).
-
-
-
-
-(R5)(R6*1)
: The location at R5
plus R6
.
-It is a scaled mode as on the x86, but the only scale allowed is 1
.
-MIPS, MIPS64
-
-R0
through R31
,
-floating point registers are F0
through F31
.
-R30
is reserved to point to g
.
-R23
is used as a temporary register.
-TEXT
directive, the frame size $-4
for MIPS or
-$-8
for MIPS64 instructs the linker not to save LR
.
-SP
refers to the virtual stack pointer.
-For the hardware register, use R29
.
-
-
-
-
-16(R1)
: The location at R1
plus 16.
-(R1)
: Alias for 0(R1)
.
-GOMIPS
environment variable (hardfloat
or
-softfloat
) is made available to assembly code by predefining either
-GOMIPS_hardfloat
or GOMIPS_softfloat
.
-GOMIPS64
environment variable (hardfloat
or
-softfloat
) is made available to assembly code by predefining either
-GOMIPS64_hardfloat
or GOMIPS64_softfloat
.
-Unsupported opcodes
-
-BYTE
-and WORD
directives
-to lay down explicit data into the instruction stream within a TEXT
.
-Here's how the 386 runtime defines the 64-bit atomic load function.
-
-// uint64 atomicload64(uint64 volatile* addr);
-// so actually
-// void atomicload64(uint64 *res, uint64 volatile *addr);
-TEXT runtime·atomicload64(SB), NOSPLIT, $0-12
- MOVL ptr+0(FP), AX
- TESTL $7, AX
- JZ 2(PC)
- MOVL 0, AX // crash with nil ptr deref
- LEAL ret_lo+4(FP), BX
- // MOVQ (%EAX), %MM0
- BYTE $0x0f; BYTE $0x6f; BYTE $0x00
- // MOVQ %MM0, 0(%EBX)
- BYTE $0x0f; BYTE $0x7f; BYTE $0x03
- // EMMS
- BYTE $0x0F; BYTE $0x77
- RET
-
diff --git a/content/doc/cmd.html b/content/doc/cmd.html
deleted file mode 100644
index c590f4d3..00000000
--- a/content/doc/cmd.html
+++ /dev/null
@@ -1,103 +0,0 @@
-
-
-go fmt
. Run like this, the command operates on
-complete packages of Go source code, with the go program invoking the
-underlying binary with arguments appropriate to package-level processing.
-tool
subcommand, such as go tool vet
.
-This style of invocation allows, for instance, checking a single source file
-rather than an entire package: go tool vet myprogram.go
as
-compared to go vet mypackage
.
-Some of the commands, such as pprof
, are accessible only through
-the go tool
subcommand.
-fmt
and godoc
commands are installed
-as regular binaries called gofmt
and godoc
because
-they are so often referenced.
-
-
-
-
-
-
-Name
-
-Synopsis
-
-
-
-go
-
-
-The
-go
program manages Go source code and runs the other
-commands listed here.
-See the command docs for usage
-details.
-
-
-
-
-cgo
-
-Cgo enables the creation of Go packages that call C code.
-
-
-
-cover
-
-Cover is a program for creating and analyzing the coverage profiles
-generated by
-"go test -coverprofile"
.
-
-
-fix
-
-Fix finds Go programs that use old features of the language and libraries
-and rewrites them to use newer ones.
-
-
-
-fmt
-
-Fmt formats Go packages, it is also available as an independent
-gofmt command with more general options.
-
-
-
-godoc
-
-Godoc extracts and generates documentation for Go packages.
-
-
-
-vet
-
-Vet examines Go source code and reports suspicious constructs, such as Printf
-calls whose arguments do not align with the format string.
-Introduction
-
-go
tool requires you to organize your code in a specific
-way. Please read this document carefully.
-It explains the simplest way to get up and running with your Go installation.
-Code organization
-
-Overview
-
-
-
-
-Workspaces
-
-
-
-
-src
contains Go source files, and
-bin
contains executable commands.
-go
tool builds and installs binaries to the bin
directory.
-src
subdirectory typically contains multiple version control
-repositories (such as for Git or Mercurial) that track the development of one
-or more source packages.
-
-bin/
- hello # command executable
- outyet # command executable
-src/
- 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
- golang.org/x/image/
- .git/ # Git repository metadata
- bmp/
- reader.go # package source
- writer.go # package source
- ... (many more repositories and packages omitted) ...
-
-
-example
and image
).
-The example
repository contains two commands (hello
-and outyet
) and one library (stringutil
).
-The image
repository contains the bmp
package
-and several others.
-The
-
-GOPATH
environment variableGOPATH
environment variable specifies the location of your
-workspace. It defaults to a directory named go
inside your home directory,
-so $HOME/go
on Unix,
-$home/go
on Plan 9,
-and %USERPROFILE%\go
(usually C:\Users\YourName\go
) on Windows.
-GOPATH
-to the path to that directory.
-(Another common setup is to set GOPATH=$HOME
.)
-Note that GOPATH
must not be the
-same path as your Go installation.
-go
env
GOPATH
-prints the effective current GOPATH
;
-it prints the default location if the environment variable is unset.
-bin
subdirectory
-to your PATH
:
-
-$ export PATH=$PATH:$(go env GOPATH)/bin
-
-
-$GOPATH
-instead of $(go env GOPATH)
for brevity.
-To make the scripts run as written
-if you have not set GOPATH,
-you can substitute $HOME/go in those commands
-or else run:
-
-$ export GOPATH=$(go env GOPATH)
-
-
-GOPATH
environment variable, see
-'go help gopath'
.
-GOPATH
environment variable.
-Import paths
-
-"fmt"
and "net/http"
.
-For your own packages, you must choose a base path that is unlikely to
-collide with future additions to the standard library or other external
-libraries.
-github.com/user
, that should be your base path.
-github.com/user
as our base path. Create a directory
-inside your workspace in which to keep source code:
-
-$ mkdir -p $GOPATH/src/github.com/user
-
-
-
-Your first program
-
-github.com/user/hello
) and create a corresponding package directory
-inside your workspace:
-
-$ mkdir $GOPATH/src/github.com/user/hello
-
-
-hello.go
inside that directory,
-containing the following Go code.
-
-package main
-
-import "fmt"
-
-func main() {
- fmt.Println("Hello, world.")
-}
-
-
-go
tool:
-
-$ go install github.com/user/hello
-
-
-go
tool finds the source code by looking for the
-github.com/user/hello
package inside the workspace specified by
-GOPATH
.
-go install
from the
-package directory:
-
-$ cd $GOPATH/src/github.com/user/hello
-$ go install
-
-
-hello
command, producing an executable
-binary. It then installs that binary to the workspace's bin
-directory as hello
(or, under Windows, hello.exe
).
-In our example, that will be $GOPATH/bin/hello
, which is
-$HOME/go/bin/hello
.
-go
tool will only print output when an error occurs, so if
-these commands produce no output they have executed successfully.
-
-$ $GOPATH/bin/hello
-Hello, world.
-
-
-$GOPATH/bin
to your PATH
,
-just type the binary name:
-
-$ hello
-Hello, world.
-
-
-
-$ cd $GOPATH/src/github.com/user/hello
-$ git init
-Initialized empty Git repository in /home/user/work/src/github.com/user/hello/.git/
-$ git add hello.go
-$ git commit -m "initial commit"
-[master (root-commit) 0b4507d] initial commit
- 1 file changed, 1 insertion(+)
- create mode 100644 hello.go
-
-
-Your first library
-
-hello
program.
-github.com/user/stringutil
) and create the package directory:
-
-$ mkdir $GOPATH/src/github.com/user/stringutil
-
-
-reverse.go
in that directory with the
-following contents.
-
-// 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 string(r)
-}
-
-
-go build
:
-
-$ go build github.com/user/stringutil
-
-
-
-$ go build
-
-
-stringutil
package builds,
-modify your original hello.go
(which is in
-$GOPATH/src/github.com/user/hello
) to use it:
-
-package main
-
-import (
- "fmt"
-
- "github.com/user/stringutil"
-)
-
-func main() {
- fmt.Println(stringutil.Reverse("!oG ,olleH"))
-}
-
-
-hello
program:
-
-$ go install github.com/user/hello
-
-
-
-$ hello
-Hello, Go!
-
-
-
-bin/
- hello # command executable
-src/
- github.com/user/
- hello/
- hello.go # command source
- stringutil/
- reverse.go # package source
-
-
-Package names
-
-
-package name
-
-
-name
is the package's default name for imports.
-(All files in a package must use the same name
.)
-crypto/rot13
"
-should be named rot13
.
-package main
.
-Testing
-
-go test
-command and the testing
package.
-_test.go
-that contains functions named TestXXX
with signature
-func (t *testing.T)
.
-The test framework runs each such function;
-if the function calls a failure function such as t.Error
or
-t.Fail
, the test is considered to have failed.
-stringutil
package by creating the file
-$GOPATH/src/github.com/user/stringutil/reverse_test.go
containing
-the following Go code.
-
-package stringutil
-
-import "testing"
-
-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)
- }
- }
-}
-
-
-go test
:
-
-$ go test github.com/user/stringutil
-ok github.com/user/stringutil 0.165s
-
-
-go
tool from the package
-directory, you can omit the package path:
-
-$ go test
-ok github.com/user/stringutil 0.165s
-
-
-go help test
and see the
-testing package documentation for more detail.
-Remote packages
-
-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
-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 github.com/golang/example/hello
-$ $GOPATH/bin/hello
-Hello, Go examples!
-
-
-go get
-will place it inside the first workspace specified by GOPATH
.
-(If the package does already exist, go get
skips the remote
-fetch and behaves the same as go install
.)
-go get
command, the workspace directory
-tree should now look like this:
-
-bin/
- hello # command executable
-src/
- github.com/golang/example/
- .git/ # Git repository metadata
- hello/
- hello.go # command source
- stringutil/
- reverse.go # package source
- reverse_test.go # test source
- github.com/user/
- hello/
- hello.go # command source
- stringutil/
- reverse.go # package source
- reverse_test.go # test source
-
-
-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 "github.com/golang/example/stringutil"
-
-
-go
tool, see
-go help importpath
.
-What's next
-
-Getting help
-
-#go-nuts
on the
-Freenode IRC server.
-
-
- The godoc web server translates
- an XML file like the one in the main window pane into the HTML
- page that you're viewing now.
-
-
- The codewalk with URL path /doc/codewalk/
name
- is loaded from the input file $GOROOT/doc/codewalk/
name.xml
.
-
-
- This codewalk explains how to write a codewalk by examining
- its own source code,
- $GOROOT/doc/codewalk/codewalk.xml
,
- shown in the main window pane to the left.
-<codewalk>
element.
- That element's title
attribute gives the title
- that is used both on the codewalk page and in the codewalk list.
-<step>
element
- nested inside the main <codewalk>
.
- The step element's title
attribute gives the step's title,
- which is shown in a shaded bar above the main step text.
- The element's src
attribute specifies the source
- code to show in the main window pane and, optionally, a range of
- lines to highlight.
-
-
- The first step in this codewalk does not highlight any lines:
- its src
is just a file name.
-
-
- To specify a source line, use a src
attribute of the form
- filename:
address,
- where address is an address in the syntax used by the text editors sam and acme.
-
-
- The simplest address is a single regular expression.
- The highlighted line in the main window pane shows that the
- address for the “Title” step was /title=/
,
- which matches the first instance of that regular expression (title=
) in the file.
-/
regexp1/,/
regexp2/
.
- The highlight begins with the line containing the first match for regexp1
- and ends with the line containing the first match for regexp2
- after the end of the match for regexp1.
- Ignoring the HTML quoting,
- The line containing the first match for regexp1 will be the first one highlighted,
- and the line containing the first match for regexp2.
-
-
- The address /<step/,/step>/
looks for the first instance of
- <step
in the file, and then starting after that point,
- looks for the first instance of step>
.
- (Click on the “Steps” step above to see the highlight in action.)
- Note that the <
and >
had to be written
- using XML escapes in order to be valid XML.
-/
regexp/
- and /
regexp1/,/
regexp2/
- forms suffice for most highlighting.
-
-
- The full address syntax is summarized in this table
- (an excerpt of Table II from
- The text editor sam
):
-
-
-
-
-
- Simple addresses
-
- #
nThe empty string after character n
- n
- Line n
-
-
- /
regexp/
The first following match of the regular expression
-
-
- $
The null string at the end of the file
- Compound addresses
- a1
- +
a2The address a2 evaluated starting at the right of a1
- a1
- -
a2The address a2 evaluated in the reverse direction starting at the left of a1
- a1
- ,
a2From the left of a1 to the right of a2 (default 0,$
).
-
- This rich feature set supports a functional programming style in a strongly
- typed language.
-
-
- In this codewalk we will look at a simple program that simulates a dice game
- called Pig and evaluates
- basic strategies.
-
-
-
- The first person to reach 100 total points wins.
-
-
- The score
type stores the scores of the current and opposing
- players, in addition to the points accumulated during the current turn.
-
-
- The action
type is a function that takes a score
- and returns the resulting score
and whether the current turn is
- over.
-
-
- If the turn is over, the player
and opponent
fields
- in the resulting score
should be swapped, as it is now the other player's
- turn.
-
-
- The functions roll
and stay
each return a pair of
- values. They also match the action
type signature. These
- action
functions define the rules of Pig.
-
-
- A strategy
is a function that takes a score
as input
- and returns an action
to perform.
- (Remember, an action
is itself a function.)
-
-
- One basic strategy in Pig is to continue rolling until you have accumulated at
- least k points in a turn, and then stay. The argument k
is
- enclosed by this function literal, which matches the strategy
type
- signature.
-action
to update the
- score
until one player reaches 100 points. Each
- action
is selected by calling the strategy
function
- associated with the current player.
-roundRobin
function simulates a tournament and tallies wins.
- Each strategy plays each other strategy gamesPerSeries
times.
-ratioString
take a variable number of
- arguments. These arguments are available as a slice inside the function.
-main
function defines 100 basic strategies, simulates a round
- robin tournament, and then prints the win/loss record of each strategy.
-
-
- Among these strategies, staying at 25 is best, but the optimal strategy for
- Pig is much more complex.
-map[string][]string
.
- Each map key is a prefix (a string
) and its values are
- lists of suffixes (a slice of strings, []string
).
-
- Here is the example table from the package comment
- as modeled by this data structure:
-
-map[string][]string{
- " ": {"I"},
- " I": {"am"},
- "I am": {"a", "not"},
- "a free": {"man!"},
- "am a": {"free"},
- "am not": {"a"},
- "a number!": {"I"},
- "number! I": {"am"},
- "not a": {"number!"},
-}
- While each prefix consists of multiple words, we
- store prefixes in the map as a single string
.
- It would seem more natural to store the prefix as a
- []string
, but we can't do this with a map because the
- key type of a map must implement equality (and slices do not).
-
- Therefore, in most of our code we will model prefixes as a
- []string
and join the strings together with a space
- to generate the map key:
-
-Prefix Map key
-
-[]string{"", ""} " "
-[]string{"", "I"} " I"
-[]string{"I", "am"} "I am"
-
-Chain
struct stores
- this data.
-Chain
struct has two unexported fields (those that
- do not begin with an upper case character), and so we write a
- NewChain
constructor function that initializes the
- chain
map with make
and sets the
- prefixLen
field.
-
- This is constructor function is not strictly necessary as this entire
- program is within a single package (main
) and therefore
- there is little practical difference between exported and unexported
- fields. We could just as easily write out the contents of this function
- when we want to construct a new Chain.
- But using these unexported fields is good practice; it clearly denotes
- that only methods of Chain and its constructor function should access
- those fields. Also, structuring Chain
like this means we
- could easily move it into its own package at some later date.
-Prefix
type with the concrete type []string
.
- Defining a named type clearly allows us to be explicit when we are
- working with a prefix instead of just a []string
.
- Also, in Go we can define methods on any named type (not just structs),
- so we can add methods that operate on Prefix
if we need to.
-Prefix
is
- String
. It returns a string
representation
- of a Prefix
by joining the slice elements together with
- spaces. We will use this method to generate keys when working with
- the chain map.
-Build
method reads text from an io.Reader
- and parses it into prefixes and suffixes that are stored in the
- Chain
.
-
- The io.Reader
is an
- interface type that is widely used by the standard library and
- other Go code. Our code uses the
- fmt.Fscan
function, which
- reads space-separated values from an io.Reader
.
-
- The Build
method returns once the Reader
's
- Read
method returns io.EOF
(end of file)
- or some other read error occurs.
-Readers
. For efficiency we wrap the provided
- io.Reader
with
- bufio.NewReader
to create a
- new io.Reader
that provides buffering.
-Prefix
slice
- p
using the Chain
's prefixLen
- field as its length.
- We'll use this variable to hold the current prefix and mutate it with
- each new word we encounter.
-Reader
into a
- string
variable s
using
- fmt.Fscan
. Since Fscan
uses space to
- separate each input value, each call will yield just one word
- (including punctuation), which is exactly what we need.
-
- Fscan
returns an error if it encounters a read error
- (io.EOF
, for example) or if it can't scan the requested
- value (in our case, a single string). In either case we just want to
- stop scanning, so we break
out of the loop.
-s
is a new suffix. We add the new
- prefix/suffix combination to the chain
map by computing
- the map key with p.String
and appending the suffix
- to the slice stored under that key.
-
- The built-in append
function appends elements to a slice
- and allocates new storage when necessary. When the provided slice is
- nil
, append
allocates a new slice.
- This behavior conveniently ties in with the semantics of our map:
- retrieving an unset key returns the zero value of the value type and
- the zero value of []string
is nil
.
- When our program encounters a new prefix (yielding a nil
- value in the map) append
will allocate a new slice.
-
- For more information about the append
function and slices
- in general see the
- Slices: usage and internals article.
-
- When in this state
-
-p == Prefix{"I", "am"}
-s == "not"
- the new value for p
would be
-
-p == Prefix{"am", "not"}
- This operation is also required during text generation so we put
- the code to perform this mutation of the slice inside a method on
- Prefix
named Shift
.
-Shift
method uses the built-in copy
- function to copy the last len(p)-1 elements of p
to
- the start of the slice, effectively moving the elements
- one index to the left (if you consider zero as the leftmost index).
-
-p := Prefix{"I", "am"}
-copy(p, p[1:])
-// p == Prefix{"am", "am"}
- We then assign the provided word
to the last index
- of the slice:
-
-// suffix == "not"
-p[len(p)-1] = suffix
-// p == Prefix{"am", "not"}
-Generate
method is similar to Build
- except that instead of reading words from a Reader
- and storing them in a map, it reads words from the map and
- appends them to a slice (words
).
-
- Generate
uses a conditional for loop to generate
- up to n
words.
-chain
map at key
- p.String()
and assign its contents to choices
.
-
- If len(choices)
is zero we break out of the loop as there
- are no potential suffixes for that prefix.
- This test also works if the key isn't present in the map at all:
- in that case, choices
will be nil
and the
- length of a nil
slice is zero.
-rand.Intn
function.
- It returns a random integer up to (but not including) the provided
- value. Passing in len(choices)
gives us a random index
- into the full length of the list.
-
- We use that index to pick our new suffix, assign it to
- next
and append it to the words
slice.
-
- Next, we Shift
the new suffix onto the prefix just as
- we did in the Build
method.
-strings.Join
function to join the elements of
- the words
slice together, separated by spaces.
-flag
package to parse
- command-line flags.
-
- These calls to flag.Int
register new flags with the
- flag
package. The arguments to Int
are the
- flag name, its default value, and a description. The Int
- function returns a pointer to an integer that will contain the
- user-supplied value (or the default value if the flag was omitted on
- the command-line).
-main
function begins by parsing the command-line
- flags with flag.Parse
and seeding the rand
- package's random number generator with the current time.
-
- If the command-line flags provided by the user are invalid the
- flag.Parse
function will print an informative usage
- message and terminate the program.
-Chain
we call NewChain
- with the value of the prefix
flag.
-
- To build the chain we call Build
with
- os.Stdin
(which implements io.Reader
) so
- that it will read its input from standard input.
-Generate
with
- the value of the words
flag and assigning the result
- to the variable text
.
-
- Then we call fmt.Println
to write the text to standard
- output, followed by a carriage return.
-
-$ go build markov.go
- And then execute it while piping in some input text:
-
-$ echo "a man a plan a canal panama" \
- | ./markov -prefix=1
-a plan a man a plan a canal panama
- Here's a transcript of generating some text using the Go distribution's
- README file as source material:
-
-$ ./markov -words=10 < $GOROOT/README
-This is the source code repository for the Go source
-$ ./markov -prefix=1 -words=10 < $GOROOT/README
-This is the go directory (the one containing this README).
-$ ./markov -prefix=1 -words=10 < $GOROOT/README
-This is the variable if you have just untarred a
-Generate
function does a lot of allocations when it
- builds the words
slice. As an exercise, modify it to
- take an io.Writer
to which it incrementally writes the
- generated text with Fprint
.
- Aside from being more efficient this makes Generate
- more symmetrical to Build
.
-
-Don't communicate by sharing memory; share memory by communicating.
-
-Channels allow you to pass references to data structures between goroutines.
-If you consider this as passing around ownership of the data (the ability to
-read and write it), they become a powerful and expressive synchronization
-mechanism.
-
-In this codewalk we will look at a simple program that polls a list of
-URLs, checking their HTTP response codes and periodically printing their state.
-
-The Pollers send State values to the StateMonitor,
-which maintains a map of the current state of each URL.
-
-When the program starts, it allocates one Resource for each URL.
-The main goroutine and the Poller goroutines send the Resources to
-each other on channels.
-
-The Poller processes the Resource by calling its Poll method.
-
-It sends a State value to the status channel, to inform the StateMonitor
-of the result of the Poll.
-
-Finally, it sends the Resource pointer to the out channel. This can be
-interpreted as the Poller saying "I'm done with this Resource" and
-returning ownership of it to the main goroutine.
-
-Several goroutines run Pollers, processing Resources in parallel.
-
-Inside main, a new goroutine sends one Resource per URL to pending
-and the main goroutine receives completed Resources from complete.
-
-The pending and complete channels are passed to each of the Poller
-goroutines, within which they are known as in and out.
-
-For now, the important thing to note is that it returns a channel of State,
-which is saved as status and passed to the Poller goroutines.
-
-The new goroutine is necessary because unbuffered channel sends and
-receives are synchronous. That means these channel sends will block until
-the Pollers are ready to read from pending.
-
-Were these sends performed in the main goroutine with fewer Pollers than
-channel sends, the program would reach a deadlock situation, because
-main would not yet be receiving from complete.
-
-Exercise for the reader: modify this part of the program to read a list of
-URLs from a file. (You may want to move this goroutine into its own
-named function.)
-
-Note that any single Resource pointer may only be sent on either pending or
-complete at any one time. This ensures that a Resource is either being
-handled by a Poller goroutine or sleeping, but never both simultaneously.
-In this way, we share our Resource data by communicating.
-
-This is an example of a typical Go idiom: a function intended to run inside
-a goroutine takes a channel, upon which it sends its return value
-(or other indication of completed state).
-
-This channel is returned by the function.
-
-In this case, ticker triggers the printing of the current state to
-standard output every updateInterval nanoseconds.
-
-When StateMonitor receives a tick from ticker.C, it calls logState to
-print the current state. When it receives a State update from updates,
-it records the new status in the urlStatus map.
-
-Notice that this goroutine owns the urlStatus data structure,
-ensuring that it can only be accessed sequentially.
-This prevents memory corruption issues that might arise from parallel reads
-and/or writes to a shared map.
-
-This should provide a starting point from which to explore the ways in which
-goroutines and channels can be used to write expressive and concise concurrent
-programs.
-About
-
-Gopher values
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-Code of Conduct
-
-Our Pledge
-
-Our Standards
-
-
-
-
-
-
-
-Our Responsibilities
-
-Scope
-
-Conflict Resolution
-
-Attribution
-
-Summary
-
-
-
diff --git a/content/doc/contrib.html b/content/doc/contrib.html
deleted file mode 100644
index b4b19a6a..00000000
--- a/content/doc/contrib.html
+++ /dev/null
@@ -1,130 +0,0 @@
-
-
-
-
-
-
-Announcements Mailing List
-Version history
-
-Release History
-
-
-
-
-Go 1 and the Future of Go Programs
-Developer Resources
-
-Source Code
-Discussion Mailing List
-Developer and
-Code Review Mailing List
-Checkins Mailing List
-Build Status
-How you can help
-
-Reporting issues
-
-
-See the security policy for more details.
-
-See the Code of Conduct for more details.
-Contributing code
-
-gccgo
front end lives elsewhere;
-see Contributing to gccgo.
-Becoming a contributor
-
-Overview
-
-
-
-
-git
-is configured to create commits with that account's e-mail address.
-git-codereview
by running
-go get -u golang.org/x/review/git-codereview
-
-$ go get -u golang.org/x/tools/cmd/go-contrib-init
-$ cd /code/to/edit
-$ go-contrib-init
-
-
-Step 0: Select a Google Account
-
-
-$ git config --global user.email # check current global config
-$ git config user.email # check current local config
-
-
-
-$ git config --global user.email name@example.com # change global config
-$ git config user.email name@example.com # change local config
-
-
-
-Step 1: Contributor License Agreement
-
-
-
-
-
-golang-dev
-mailing list.
-This will let us know the situation so we can make sure an appropriate agreement is
-completed and update the AUTHORS
file.
-Step 2: Configure git authentication
-
-git
on your computer to access it.
-Follow this steps:
-
-
-
-.gitcookies
file.
-If you are using a Windows computer and running cmd
,
-you should instead follow the instructions in the yellow box to run the command;
-otherwise run the regular script.
-Step 3: Create a Gerrit account
-
-Step 4: Install the git-codereview command
-
-git
command called git-codereview
-simplifies sending changes to Gerrit.
-git-codereview
command by running,
-
-$ go get -u golang.org/x/review/git-codereview
-
-
-git-codereview
is installed in your shell path, so that the
-git
command can find it.
-Check that
-
-$ git codereview help
-
-
-git-codereview.exe
is in your git
exec-path.
-Run git --exec-path
to discover the right location then create a
-symbolic link or just copy the executable from $GOPATH/bin to this directory.
-Before contributing code
-
-Check the issue tracker
-
-
-
-
-
-
-
-is:issue is:open label:NeedsInvestigation
- is:issue is:open label:NeedsFix
- is:issue is:open label:NeedsFix "golang.org/cl"
- is:issue is:open label:NeedsFix NOT "golang.org/cl"
- Open an issue for any new problem
-
-Sending a change via GitHub
-
-
-
-
-Sending a change via Gerrit
-
-Overview
-
-
-
-
-go.googlesource.com
-and make sure it's stable by compiling and testing it once:
-
-$ git clone https://go.googlesource.com/go
-$ cd go/src
-$ ./all.bash # compile and test
-
-git
codereview
change
; that
-will create or amend a single commit in the branch.
-
-$ git checkout -b mybranch
-$ [edit files...]
-$ git add [files...]
-$ git codereview change # create commit in the branch
-$ [edit again...]
-$ git add [files...]
-$ git codereview change # amend the existing commit with new changes
-$ [etc.]
-
-all.bash
.
-
-$ ./all.bash # recompile and test
-
-git
-codereview
mail
(which doesn't use e-mail, despite the name).
-
-$ git codereview mail # send changes to Gerrit
-
-
-$ [edit files...]
-$ git add [files...]
-$ git codereview change # update same commit
-$ git codereview mail # send to Gerrit again
-
-Step 1: Clone the Go source code
-
-GOPATH
.
-Clone from go.googlesource.com
(not GitHub):
-
-$ git clone https://go.googlesource.com/go
-$ cd go
-
-
-Step 2: Prepare changes in a new branch
-
-git
commands to create a branch and add changes to the
-staging area:
-
-$ git checkout -b mybranch
-$ [edit files...]
-$ git add [files...]
-
-
-git commit
, use git codereview change
.
-
-$ git codereview change
-(open $EDITOR)
-
-
-git
codereview
change
command
-will automatically add a unique Change-Id line near the bottom.
-That line is used by Gerrit to match successive uploads of the same change.
-Do not edit or delete it.
-A Change-Id looks like this:
-
-Change-Id: I2fbdbffb3aab626c4b6f56348861b7909e3e8990
-
-
-go
fmt
over the source code, and that
-the commit message follows the suggested format.
-git
codereview
change
: each subsequent
-run will amend the existing commit while preserving the Change-Id.
-git
rebase
to
-squash them together
-into a single one.
-Step 3: Test your changes
-
-
-$ cd go/src
-$ ./all.bash
-
-
-all.bat
; this also requires
-setting the environment variable GOROOT_BOOTSTRAP
to the
-directory holding the Go tree for the bootstrap compiler.)
-
-ALL TESTS PASSED
-
-
-make.bash
instead of all.bash
-to just build the compiler and the standard library without running the test suite.
-Once the go
tool is built, it will be installed as bin/go
-under the directory in which you cloned the Go repository, and you can
-run it directly from there.
-See also
-the section on how to test your changes quickly.
-Step 4: Send changes for review
-
-mail
sub-command which, despite its name, doesn't
-directly mail anything; it just sends the change to Gerrit:
-
-$ git codereview mail
-
-
-git
codereview
mail
will print, something like:
-
-remote: New Changes:
-remote: https://go-review.googlesource.com/99999 math: improved Sin, Cos and Tan precision for very large arguments
-
-
-Step 5: Revise changes after a review
-
-git
codereview
change
:
-
-$ git codereview change # amend current commit
-(open $EDITOR)
-$ git codereview mail # send new changes to Gerrit
-
-
-git rebase
to
-squash them together
-into a single one.
-Good commit messages
-
-
-math: improve Sin, Cos and Tan precision for very large arguments
-
-The existing implementation has poor numerical properties for
-large arguments, so use the McGillicutty algorithm to improve
-accuracy above 1e10.
-
-The algorithm is described at https://wikipedia.org/wiki/McGillicutty_Algorithm
-
-Fixes #159
-
-
-First line
-
-Main content
-
-Referencing issues
-
-The review process
-
-Common beginner mistakes
-
-
-
-
-
-Only trivial or cosmetic changes will be accepted without an associated issue.
-R=go1.12
,
-which means that it will be reviewed later when the tree opens for a new
-development window.
-You can add R=go1.XX
as a comment yourself
-if you know that it's not the correct time frame for the change.
-Trybots
-
-Reviews
-
-Voting conventions
-
-
-
-
-Submitting an approved change
-
-More information
-
-Miscellaneous topics
-
-Copyright headers
-
-CONTRIBUTORS
file and perhaps the AUTHORS
file.
-These files are automatically generated from the commit logs periodically.
-The AUTHORS
file defines who “The Go
-Authors”—the copyright holders—are.
-
-// Copyright 2019 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-
-Troubleshooting mail errors
-
-git
codereview
mail
-command fails is because the e-mail address in the commit does not match the one
-that you used during the registration process.
-
-
-If you see something like...
-
-remote: Processing changes: refs: 1, done
-remote:
-remote: ERROR: In commit ab13517fa29487dcf8b0d48916c51639426c5ee9
-remote: ERROR: author email address XXXXXXXXXXXXXXXXXXX
-remote: ERROR: does not match your user account.
-
-
-
-$ git config user.email email@address.com
-
-
-
-$ git commit --amend --author="Author Name <email@address.com>"
-
-
-
-$ git codereview mail
-
-
-
-Quickly testing your changes
-
-all.bash
for every single change to the code tree
-is burdensome.
-Even though it is strongly suggested to run it before
-sending a change, during the normal development cycle you may want
-to compile and test only the package you are developing.
-
-
-
-make.bash
instead of all.bash
-to only rebuild the Go tool chain without running the whole test suite.
-Or you
-can run run.bash
to only run the whole test suite without rebuilding
-the tool chain.
-You can think of all.bash
as make.bash
-followed by run.bash
.
-$GODIR
.
-The go
tool built by $GODIR/make.bash
will be installed
-in $GODIR/bin/go
and you
-can invoke it to test your code.
-For instance, if you
-have modified the compiler and you want to test how it affects the
-test suite of your own project, just run go
test
-using it:
-
-
-$ cd <MYPROJECTDIR>
-$ $GODIR/bin/go test
-
-
-$ cd $GODIR/src/hash/sha1
-$ [make changes...]
-$ $GODIR/bin/go test .
-
-compile
tool (which is the internal binary invoked
-by go
build
to compile each single package).
-After that, you will want to test it by compiling or running something.
-
-
-$ cd $GODIR/src
-$ [make changes...]
-$ $GODIR/bin/go install cmd/compile
-$ $GODIR/bin/go build [something...] # test the new compiler
-$ $GODIR/bin/go run [something...] # test the new compiler
-$ $GODIR/bin/go test [something...] # test the new compiler
-
-
-The same applies to other internal tools of the Go tool chain,
-such as asm
, cover
, link
, and so on.
-Just recompile and install the tool using go
-install
cmd/<TOOL>
and then use
-the built Go binary to test it.
-$GODIR/test
that contains
-several black-box and regression tests.
-The test suite is run
-by all.bash
but you can also run it manually:
-
-
-$ cd $GODIR/test
-$ $GODIR/bin/go run run.go
-
-Contributing to subrepositories (golang.org/x/...)
-
-go get
.
-For example, to contribute
-to golang.org/x/oauth2
, check out the code by running:
-
-$ go get -d golang.org/x/oauth2/...
-
-
-$GOPATH/src/golang.org/x/oauth2
), and follow the
-normal contribution flow.
-Specifying a reviewer / CCing others
-
--r
or -cc
options.
-Both accept a comma-separated list of e-mail addresses:
-
-$ git codereview mail -r joe@golang.org -cc mabel@example.com,math-nuts@swtch.com
-
-
-
-Synchronize your client
-
-
-$ git codereview sync
-
-
-git
pull
-r
.)
-Reviewing code by others
-
-
-$ git fetch https://go.googlesource.com/review refs/changes/21/13245/1 && git checkout FETCH_HEAD
-
-
-Set up git aliases
-
-git-codereview
command can be run directly from the shell
-by typing, for instance,
-
-$ git codereview sync
-
-
-git-codereview
's own
-subcommands, so that the above becomes,
-
-$ git sync
-
-
-git-codereview
subcommands have been chosen to be distinct from
-Git's own, so it's safe to define these aliases.
-To install them, copy this text into your
-Git configuration file (usually .gitconfig
in your home directory):
-
-[alias]
- change = codereview change
- gofmt = codereview gofmt
- mail = codereview mail
- pending = codereview pending
- submit = codereview submit
- sync = codereview sync
-
-
-
-Sending multiple dependent changes
-
-
-$ git codereview mail HEAD
-
-
-HEAD
, which is usually not required when sending
-single changes.
-gc
Go compiler and tools).
-Gccgo has native gdb support.
-amd64
.
-For the most up-to-date list of supported platforms, please see
-
- the Delve documentation.
-Introduction
-
-gc
toolchain
-on Linux, macOS, FreeBSD or NetBSD, the resulting binaries contain DWARFv4
-debugging information that recent versions (≥7.5) of the GDB debugger can
-use to inspect a live process or a core dump.
-'-w'
flag to the linker to omit the debug information
-(for example, go
build
-ldflags=-w
prog.go
).
-gc
compiler includes inlining of
-function invocations and registerization of variables. These optimizations
-can sometimes make debugging with gdb
harder.
-If you find that you need to disable these optimizations,
-build your program using go
build
-gcflags=all="-N -l"
.
-GOTRACEBACK=crash
in the environment (see the
- runtime package
-documentation for more info).
-Common Operations
-
-
-
-
-
-(gdb) list
-(gdb) list line
-(gdb) list file.go:line
-(gdb) break line
-(gdb) break file.go:line
-(gdb) disas
-(gdb) bt
-(gdb) frame n
-(gdb) info locals
-(gdb) info args
-(gdb) p variable
-(gdb) whatis variable
-(gdb) info variables regexp
-Go Extensions
-
-
-
-
-(gdb) p var
-(gdb) p $len(var)
-(gdb) p $dtype(var)
-(gdb) iface var
-(gdb) info goroutines
-(gdb) goroutine n cmd
-(gdb) help goroutine
-For example:
-(gdb) goroutine 12 bt
-hash<T,U>
) and variables (runtime.m
and
-runtime.g
) that the linker
-(src/cmd/link/internal/ld/dwarf.go) ensures are described in
-the DWARF code.
-objdump
-W
a.out
and browse through the .debug_*
-sections.
-Known Issues
-
-
-
-
-"fmt.Print"
as an unstructured literal with a "."
-that needs to be quoted. It objects even more strongly to method names of
-the form pkg.(*MyType).Meth
.
-go
-build -ldflags=-compressdwarf=false
.
-(For convenience you can put the -ldflags
option in
-the GOFLAGS
-environment variable so that you don't have to specify it each time.)
-Tutorial
-
-$GOROOT/src/regexp
and run go
test
-c
.
-This should produce an executable file named regexp.test
.
-Getting Started
-
-regexp.test
:
-
-$ gdb regexp.test
-GNU gdb (GDB) 7.2-gg8
-Copyright (C) 2010 Free Software Foundation, Inc.
-License GPLv 3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
-Type "show copying" and "show warranty" for licensing/warranty details.
-This GDB was configured as "x86_64-linux".
-
-Reading symbols from /home/user/go/src/regexp/regexp.test...
-done.
-Loading Go Runtime support.
-(gdb)
-
-
-$GOROOT/src/runtime/runtime-gdb.py
.
-$GOROOT
with the '-d'
flag:
-
-$ gdb regexp.test -d $GOROOT
-
-
-~/go/
):
-
-(gdb) source ~/go/src/runtime/runtime-gdb.py
-Loading Go Runtime support.
-
-
-Inspecting the source
-
-"l"
or "list"
command to inspect source code.
-
-(gdb) l
-
-
-"list"
with a
-function name (it must be qualified with its package name).
-
-(gdb) l main.main
-
-
-
-(gdb) l regexp.go:1
-(gdb) # Hit enter to repeat last command. Here, this lists next 10 lines.
-
-
-
-Naming
-
-Compile
function from the regexp
-package is known to GDB as 'regexp.Compile'
.
-*Regexp
type’s String
method is known as
-'regexp.(*Regexp).String'
.
-Setting breakpoints
-
-TestFind
function:
-
-(gdb) b 'regexp.TestFind'
-Breakpoint 1 at 0x424908: file /home/user/go/src/regexp/find_test.go, line 148.
-
-
-
-(gdb) run
-Starting program: /home/user/go/src/regexp/regexp.test
-
-Breakpoint 1, regexp.TestFind (t=0xf8404a89c0) at /home/user/go/src/regexp/find_test.go:148
-148 func TestFind(t *testing.T) {
-
-
-
-(gdb) info goroutines
- 1 waiting runtime.gosched
-* 13 running runtime.goexit
-
-
-*
is the current goroutine.
-Inspecting the stack
-
-
-(gdb) bt # backtrace
-#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 ?? ()
-
-
-runtime.gosched
, blocked on a channel receive:
-
-(gdb) goroutine 1 bt
-#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/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/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/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 ?? ()
-
-
-regexp.TestFind
function, as expected.
-
-(gdb) info frame
-Stack level 0, frame at 0x7ffff7f9ff88:
- 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.
- Arglist at 0x7ffff7f9ff78, args: t=0xf840688b60
- Locals at 0x7ffff7f9ff78, Previous frame's sp is 0x7ffff7f9ff88
- Saved registers:
- rip at 0x7ffff7f9ff80
-
-
-info
locals
lists all variables local to the function and their values, but is a bit
-dangerous to use, since it will also try to print uninitialized variables. Uninitialized slices may cause gdb to try
-to print arbitrary large arrays.
-
-(gdb) info args
-t = 0xf840688b60
-
-
-Regexp
value. Note that GDB has incorrectly put the *
-on the right-hand side of the type name and made up a 'struct' keyword, in traditional C style.
-
-(gdb) p re
-(gdb) p t
-$1 = (struct testing.T *) 0xf840688b60
-(gdb) p t
-$1 = (struct testing.T *) 0xf840688b60
-(gdb) p *t
-$2 = {errors = "", failed = false, ch = 0xf8406f5690}
-(gdb) p *t->ch
-$3 = struct hchan<*testing.T>
-
-
-struct
hchan<*testing.T>
is the
-runtime-internal representation of a channel. It is currently empty,
-or gdb would have pretty-printed its contents.
-
-(gdb) n # execute next line
-149 for _, test := range findTests {
-(gdb) # enter is repeat
-150 re := MustCompile(test.pat)
-(gdb) p test.pat
-$4 = ""
-(gdb) p re
-$5 = (struct regexp.Regexp *) 0xf84068d070
-(gdb) p *re
-$6 = {expr = "", prog = 0xf840688b80, prefix = "", prefixBytes = []uint8, prefixComplete = true,
- prefixRune = 0, cond = 0 '\000', numSubexp = 0, longest = false, mu = {state = 0, sema = 0},
- machine = []*regexp.machine}
-(gdb) p *re->prog
-$7 = {Inst = []regexp/syntax.Inst = {{Op = 5 '\005', Out = 0, Arg = 0, Rune = []int}, {Op =
- 6 '\006', Out = 2, Arg = 0, Rune = []int}, {Op = 4 '\004', Out = 0, Arg = 0, Rune = []int}},
- Start = 1, NumCap = 2}
-
-
-
-String
function call with "s"
:
-
-(gdb) s
-regexp.(*Regexp).String (re=0xf84068d070, noname=void) at /home/user/go/src/regexp/regexp.go:97
-97 func (re *Regexp) String() string {
-
-
-
-(gdb) bt
-#0 regexp.(*Regexp).String (re=0xf84068d070, noname=void)
- at /home/user/go/src/regexp/regexp.go:97
-#1 0x0000000000425615 in regexp.TestFind (t=0xf840688b60)
- at /home/user/go/src/regexp/find_test.go:151
-#2 0x0000000000430233 in testing.tRunner (t=0xf840688b60, test=0x5747b8)
- at /home/user/go/src/testing/testing.go:156
-#3 0x000000000040ea6f in runtime.initdone () at /home/user/go/src/runtime/proc.c:243
-....
-
-
-
-(gdb) l
-92 mu sync.Mutex
-93 machine []*machine
-94 }
-95
-96 // String returns the source text used to compile the regular expression.
-97 func (re *Regexp) String() string {
-98 return re.expr
-99 }
-100
-101 // Compile parses a regular expression and returns, if successful,
-
-
-Pretty Printing
-
-
-(gdb) p utf
-$22 = []uint8 = {0 '\000', 0 '\000', 0 '\000', 0 '\000'}
-
-
-
-
-(gdb) p slc
-$11 = []int = {0, 0}
-(gdb) p slc-><TAB>
-array slc len
-(gdb) p slc->array
-$12 = (int *) 0xf84057af00
-(gdb) p slc->array[1]
-$13 = 0
-
-
-
-
-(gdb) p $len(utf)
-$23 = 4
-(gdb) p $cap(utf)
-$24 = 4
-
-
-hash<int,string>*
. Dereferencing will trigger prettyprinting
-$dtype
decodes the dynamic type for you (examples are taken from a breakpoint at regexp.go
line 293.)
-
-(gdb) p i
-$4 = {str = "cbb"}
-(gdb) whatis i
-type = regexp.input
-(gdb) p $dtype(i)
-$26 = (struct regexp.inputBytes *) 0xf8400b4930
-(gdb) iface i
-regexp.input: struct regexp.inputBytes *
-
diff --git a/content/doc/devel/pre_go1.html b/content/doc/devel/pre_go1.html
deleted file mode 100644
index 813e23cd..00000000
--- a/content/doc/devel/pre_go1.html
+++ /dev/null
@@ -1,455 +0,0 @@
-
-
-r60 (released 2011/09/07)
-
-weekly.2011-08-17
.
-This section highlights the most significant changes in this release.
-For a more detailed summary, see the
-weekly release notes.
-For complete information, see the
-Mercurial change list.
-Language
-
-Packages
-
-ParseURL
and URLEscape
) has been moved to
-the new url package, with several simplifications to
-the names. Client code can be updated automatically with gofix.
-Pix
field of struct types such as
-image.RGBA and
-image.NRGBA.
-The image.Image interface type has not changed,
-though, and you should not need to change your code if you don't explicitly
-refer to Pix
fields. For example, if you decode a number of images
-using the image/jpeg package, compose them using
-image/draw, and then encode the result using
-image/png, then your code should still work as
-before.
-If your code does refer to Pix
fields see the
-weekly.2011-07-19
-snapshot notes for how to update your code.
-exp/template
). The original template
-package is still available as old/template.
-The old/template
package is deprecated and will be removed.
-The Go tree has been updated to use the new template package. We encourage
-users of the old template package to switch to the new one. Code that uses
-template
or exp/template
will need to change its
-import lines to "old/template"
or "template"
,
-respectively.
-Tools
-
-"go."
prefix that corresponds to the local Go version. For Go
-release.r58
it looks for go.r58
. For
-weekly.2011-06-03
it looks for go.weekly.2011-06-03
.
-If the specific go.X
tag or branch is not found, it chooses the
-closest earlier version. If an appropriate tag or branch is found, goinstall
-uses that version of the code. Otherwise it uses the default version selected
-by the version control system. Library authors are encouraged to use the
-appropriate tag or branch names in their repositories to make their libraries
-more accessible.
-Minor revisions
-
-json
package
-fix and
-a new
-struct tag
-option.
-r59 (released 2011/08/01)
-
-weekly.2011-07-07
.
-This section highlights the most significant changes in this release.
-For a more detailed summary, see the
-weekly release notes.
-For complete information, see the
-Mercurial change list.
-Language
-
-goto
. In essence, a goto
statement outside a block
-cannot jump to a label inside that block. Your code may require changes if it
-uses goto
.
-See this
-changeset for how the new rule affected the Go tree.
-Packages
-
-FileSystem
argument instead of an explicit file system root. By
-implementing your own FileSystem
you can use the
-FileServer
to serve arbitrary data.
-ErrorString
type has been
-hidden. Most uses of os.ErrorString
can be replaced with
-os.NewError.
-
- `key:"value" key2:"value2"`
-
-Get
method. Clients of json and
-xml will need to be updated. Code that says
-
- type T struct {
- X int "name"
- }
-
-
- type T struct {
- X int `json:"name"` // or `xml:"name"`
- }
-
-IntArray
type has been
-renamed to IntSlice, and similarly for
-Float64Slice and
-StringSlice.
-Split
function has
-itself been split into Split and
-SplitN.
-SplitN
is the same as the old Split
.
-The new Split
is equivalent to SplitN
with a final
-argument of -1.
-
-Goinstall now installs packages and commands from -arbitrary remote repositories (not just Google Code, Github, and so on). -See the goinstall documentation for details. -
- -
-The r58 release corresponds to
-weekly.2011-06-09
-with additional bug fixes.
-This section highlights the most significant changes in this release.
-For a more detailed summary, see the
-weekly release notes.
-For complete information, see the
-Mercurial change list.
-
-This release fixes a use of uninitialized memory in programs that misuse goto
.
-
-As usual, gofix will handle the bulk of the rewrites -necessary for these changes to package APIs. -
- -
-Package http drops the finalURL
return
-value from the Client.Get method. The value
-is now available via the new Request
field on http.Response.
-Most instances of the type map[string][]string in have been
-replaced with the new Values type.
-
-Package exec has been redesigned with a more -convenient and succinct API. -
- -
-Package strconv's Quote
-function now escapes only those Unicode code points not classified as printable
-by unicode.IsPrint.
-Previously Quote would escape all non-ASCII characters.
-This also affects the fmt package's "%q"
-formatting directive. The previous quoting behavior is still available via
-strconv's new QuoteToASCII function.
-
-Package os/signal's -Signal and -UnixSignal types have been moved to the -os package. -
- -
-Package image/draw is the new name for
-exp/draw
. The GUI-related code from exp/draw
is now
-located in the exp/gui package.
-
-Goinstall now observes the GOPATH environment -variable to build and install your own code and external libraries outside of -the Go tree (and avoid writing Makefiles). -
- - -r58.1 adds -build and -runtime -changes to make Go run on OS X 10.7 Lion. -
- -
-The r57 release corresponds to
-weekly.2011-04-27
-with additional bug fixes.
-This section highlights the most significant changes in this release.
-For a more detailed summary, see the
-weekly release notes.
-For complete information, see the
-Mercurial change list.
-
The new gofix tool finds Go programs that use old APIs and rewrites them to use -newer ones. After you update to a new Go release, gofix helps make the -necessary changes to your programs. Gofix will handle the http, os, and syscall -package changes described below, and we will update the program to keep up with -future changes to the libraries. -Gofix can’t -handle all situations perfectly, so read and test the changes it makes before -committing them. -See the gofix blog post for more -information.
- -
-Multiple assignment syntax replaces the closed
function.
-The syntax for channel
-receives allows an optional second assigned value, a boolean value
-indicating whether the channel is closed. This code:
-
- v := <-ch - if closed(ch) { - // channel is closed - } -- -
should now be written as:
- -- v, ok := <-ch - if !ok { - // channel is closed - } -- -
Unused labels are now illegal, just as unused local variables are.
- --Package gob will now encode and decode values of types that implement the -GobEncoder and -GobDecoder interfaces. This allows types with unexported -fields to transmit self-consistent descriptions; examples include -big.Int and big.Rat. -
- --Package http has been redesigned. -For clients, there are new -Client and Transport -abstractions that give more control over HTTP details such as headers sent -and redirections followed. These abstractions make it easy to implement -custom clients that add functionality such as OAuth2. -For servers, ResponseWriter -has dropped its non-essential methods. -The Hijack and Flush methods are no longer required; -code can test for them by checking whether a specific value implements -Hijacker or Flusher. -The RemoteAddr and UsingTLS methods are replaced by Request's -RemoteAddr and TLS fields. -The SetHeader method is replaced by a Header method; -its result, of type Header, -implements Set and other methods. -
- -
-Package net
-drops the laddr
argument from Dial
-and drops the cname
return value
-from LookupHost.
-The implementation now uses cgo to implement
-network name lookups using the C library getaddrinfo(3)
-function when possible. This ensures that Go and C programs
-resolve names the same way and also avoids the OS X
-application-level firewall.
-
-Package os -introduces simplified Open -and Create functions. -The original Open is now available as OpenFile. -The final three arguments to StartProcess -have been replaced by a pointer to a ProcAttr. -
- -
-Package reflect has been redesigned.
-Type is now an interface that implements
-all the possible type methods.
-Instead of a type switch on a Type t
, switch on t.Kind()
.
-Value is now a struct value that
-implements all the possible value methods.
-Instead of a type switch on a Value v
, switch on v.Kind()
.
-Typeof and NewValue are now called TypeOf and ValueOf
-To create a writable Value, use New(t).Elem()
instead of Zero(t)
.
-See the change description
-for the full details.
-The new API allows a more efficient implementation of Value
-that avoids many of the allocations required by the previous API.
-
-Remember that gofix will handle the bulk of the rewrites -necessary for these changes to package APIs. -
- -Gofix, a new command, is described above.
- -
-Gotest is now a Go program instead of a shell script.
-The new -test.short
flag in combination with package testing's Short function
-allows you to write tests that can be run in normal or “short” mode;
-all.bash runs tests in short mode to reduce installation time.
-The Makefiles know about the flag: use make testshort
.
-
-The run-time support now implements CPU and memory profiling.
-Gotest's new
--test.cpuprofile
and
--test.memprofile
flags make it easy to
-profile tests.
-To add profiling to your web server, see the http/pprof
-documentation.
-For other uses, see the runtime/pprof documentation.
-
r57.1 fixes a nil pointer dereference in http.FormFile.
-r57.2 fixes a use of uninitialized memory in programs that misuse goto
.
-The r56 release was the first stable release and corresponds to
-weekly.2011-03-07.1
.
-The numbering starts at 56 because before this release,
-what we now consider weekly snapshots were called releases.
-
This page summarizes the changes between official stable releases of Go. -The change log has the full details.
- -To update to a specific release, use:
- --git pull -git checkout release-branch -- -
-Each major Go release is supported until there are two newer major releases. -For example, Go 1.5 was supported until the Go 1.7 release, and Go 1.6 was -supported until the Go 1.8 release. -We fix critical problems, including critical security problems, -in supported releases as needed by issuing minor revisions -(for example, Go 1.6.1, Go 1.6.2, and so on). -
- --Go 1.11 is a major release of Go. -Read the Go 1.11 Release Notes for more information. -
- -
-go1.11.1 (released 2018/10/01) includes fixes to the compiler, documentation, go
-command, runtime, and the crypto/x509
, encoding/json
,
-go/types
, net
, net/http
, and
-reflect
packages.
-See the Go
-1.11.1 milestone on our issue tracker for details.
-
-go1.11.2 (released 2018/11/02) includes fixes to the compiler, linker,
-documentation, go command, and the database/sql
and
-go/types
packages.
-See the Go
-1.11.2 milestone on our issue tracker for details.
-
-go1.11.3 (released 2018/12/12) includes three security fixes to "go get" and
-the crypto/x509
package.
-See the Go
-1.11.3 milestone on our issue tracker for details.
-
-go1.11.4 (released 2018/12/14) includes fixes to cgo, the compiler, linker,
-runtime, documentation, go command, and the net/http
and
-go/types
packages.
-It includes a fix to a bug introduced in Go 1.11.3 that broke go
-get
for import path patterns containing "...
".
-See the Go
-1.11.4 milestone on our issue tracker for details.
-
-Go 1.10 is a major release of Go. -Read the Go 1.10 Release Notes for more information. -
- -
-go1.10.1 (released 2018/03/28) includes fixes to the compiler, runtime, and the
-archive/zip
, crypto/tls
, crypto/x509
,
-encoding/json
, net
, net/http
, and
-net/http/pprof
packages.
-See the Go
-1.10.1 milestone on our issue tracker for details.
-
-go1.10.2 (released 2018/05/01) includes fixes to the compiler, linker, and go -command. -See the Go -1.10.2 milestone on our issue tracker for details. -
- -
-go1.10.3 (released 2018/06/05) includes fixes to the go command, and the
-crypto/tls
, crypto/x509
, and strings
packages.
-In particular, it adds
-minimal support to the go command for the vgo transition.
-See the Go
-1.10.3 milestone on our issue tracker for details.
-
-go1.10.4 (released 2018/08/24) includes fixes to the go command, linker, and the
-net/http
, mime/multipart
, ld/macho
,
-bytes
, and strings
packages.
-See the Go
-1.10.4 milestone on our issue tracker for details.
-
-go1.10.5 (released 2018/11/02) includes fixes to the go command, linker, runtime
-and the database/sql
package.
-See the Go
-1.10.5 milestone on our issue tracker for details.
-
-go1.10.6 (released 2018/12/12) includes three security fixes to "go get" and
-the crypto/x509
package.
-It contains the same fixes as Go 1.11.3 and was released at the same time.
-See the Go
-1.10.6 milestone on our issue tracker for details.
-
-go1.10.7 (released 2018/12/14) includes a fix to a bug introduced in Go 1.10.6
-that broke go
get
for import path patterns containing
-"...
".
-See the
-Go 1.10.7 milestone on our issue tracker for details.
-
-Go 1.9 is a major release of Go. -Read the Go 1.9 Release Notes for more information. -
- --go1.9.1 (released 2017/10/04) includes two security fixes. -See the Go -1.9.1 milestone on our issue tracker for details. -
- -
-go1.9.2 (released 2017/10/25) includes fixes to the compiler, linker, runtime,
-documentation, go
command,
-and the crypto/x509
, database/sql
, log
,
-and net/smtp
packages.
-It includes a fix to a bug introduced in Go 1.9.1 that broke go
get
-of non-Git repositories under certain conditions.
-See the Go
-1.9.2 milestone on our issue tracker for details.
-
-go1.9.3 (released 2018/01/22) includes fixes to the compiler, runtime,
-and the database/sql
, math/big
, net/http
,
-and net/url
packages.
-See the Go
-1.9.3 milestone on our issue tracker for details.
-
-go1.9.4 (released 2018/02/07) includes a security fix to “go get”. -See the Go -1.9.4 milestone on our issue tracker for details. -
- -
-go1.9.5 (released 2018/03/28) includes fixes to the compiler, go command, and
-net/http/pprof
package.
-See the Go
-1.9.5 milestone on our issue tracker for details.
-
-go1.9.6 (released 2018/05/01) includes fixes to the compiler and go command. -See the Go -1.9.6 milestone on our issue tracker for details. -
- -
-go1.9.7 (released 2018/06/05) includes fixes to the go command, and the
-crypto/x509
, and strings
packages.
-In particular, it adds
-minimal support to the go command for the vgo transition.
-See the Go
-1.9.7 milestone on our issue tracker for details.
-
-Go 1.8 is a major release of Go. -Read the Go 1.8 Release Notes for more information. -
- -
-go1.8.1 (released 2017/04/07) includes fixes to the compiler, linker, runtime,
-documentation, go
command and the crypto/tls
,
-encoding/xml
, image/png
, net
,
-net/http
, reflect
, text/template
,
-and time
packages.
-See the Go
-1.8.1 milestone on our issue tracker for details.
-
-go1.8.2 (released 2017/05/23) includes a security fix to the
-crypto/elliptic
package.
-See the Go
-1.8.2 milestone on our issue tracker for details.
-
-go1.8.3 (released 2017/05/24) includes fixes to the compiler, runtime,
-documentation, and the database/sql
package.
-See the Go
-1.8.3 milestone on our issue tracker for details.
-
-go1.8.4 (released 2017/10/04) includes two security fixes. -It contains the same fixes as Go 1.9.1 and was released at the same time. -See the Go -1.8.4 milestone on our issue tracker for details. -
- -
-go1.8.5 (released 2017/10/25) includes fixes to the compiler, linker, runtime,
-documentation, go
command,
-and the crypto/x509
and net/smtp
packages.
-It includes a fix to a bug introduced in Go 1.8.4 that broke go
get
-of non-Git repositories under certain conditions.
-See the Go
-1.8.5 milestone on our issue tracker for details.
-
-go1.8.6 (released 2018/01/22) includes the same fix in math/big
-as Go 1.9.3 and was released at the same time.
-See the Go
-1.8.6 milestone on our issue tracker for details.
-
-go1.8.7 (released 2018/02/07) includes a security fix to “go get”. -It contains the same fix as Go 1.9.4 and was released at the same time. -See the Go -1.8.7 milestone on our issue tracker for details. -
- --Go 1.7 is a major release of Go. -Read the Go 1.7 Release Notes for more information. -
- -
-go1.7.1 (released 2016/09/07) includes fixes to the compiler, runtime,
-documentation, and the compress/flate
, hash/crc32
,
-io
, net
, net/http
,
-path/filepath
, reflect
, and syscall
-packages.
-See the Go
-1.7.1 milestone on our issue tracker for details.
-
-go1.7.2 should not be used. It was tagged but not fully released. -The release was deferred due to a last minute bug report. -Use go1.7.3 instead, and refer to the summary of changes below. -
- -
-go1.7.3 (released 2016/10/19) includes fixes to the compiler, runtime,
-and the crypto/cipher
, crypto/tls
,
-net/http
, and strings
packages.
-See the Go
-1.7.3 milestone on our issue tracker for details.
-
-go1.7.4 (released 2016/12/01) includes two security fixes. -See the Go -1.7.4 milestone on our issue tracker for details. -
- -
-go1.7.5 (released 2017/01/26) includes fixes to the compiler, runtime,
-and the crypto/x509
and time
packages.
-See the Go
-1.7.5 milestone on our issue tracker for details.
-
-go1.7.6 (released 2017/05/23) includes the same security fix as Go 1.8.2 and -was released at the same time. -See the Go -1.8.2 milestone on our issue tracker for details. -
- --Go 1.6 is a major release of Go. -Read the Go 1.6 Release Notes for more information. -
- --go1.6.1 (released 2016/04/12) includes two security fixes. -See the Go -1.6.1 milestone on our issue tracker for details. -
- -
-go1.6.2 (released 2016/04/20) includes fixes to the compiler, runtime, tools,
-documentation, and the mime/multipart
, net/http
, and
-sort
packages.
-See the Go
-1.6.2 milestone on our issue tracker for details.
-
-go1.6.3 (released 2016/07/17) includes security fixes to the
-net/http/cgi
package and net/http
package when used in
-a CGI environment.
-See the Go
-1.6.3 milestone on our issue tracker for details.
-
-go1.6.4 (released 2016/12/01) includes two security fixes. -It contains the same fixes as Go 1.7.4 and was released at the same time. -See the Go -1.7.4 milestone on our issue tracker for details. -
- --Go 1.5 is a major release of Go. -Read the Go 1.5 Release Notes for more information. -
- -
-go1.5.1 (released 2015/09/08) includes bug fixes to the compiler, assembler, and
-the fmt
, net/textproto
, net/http
, and
-runtime
packages.
-See the Go
-1.5.1 milestone on our issue tracker for details.
-
-go1.5.2 (released 2015/12/02) includes bug fixes to the compiler, linker, and
-the mime/multipart
, net
, and runtime
-packages.
-See the Go
-1.5.2 milestone on our issue tracker for details.
-
-go1.5.3 (released 2016/01/13) includes a security fix to the math/big
package
-affecting the crypto/tls
package.
-See the release announcement for details.
-
-go1.5.4 (released 2016/04/12) includes two security fixes. -It contains the same fixes as Go 1.6.1 and was released at the same time. -See the Go -1.6.1 milestone on our issue tracker for details. -
- --Go 1.4 is a major release of Go. -Read the Go 1.4 Release Notes for more information. -
- -
-go1.4.1 (released 2015/01/15) includes bug fixes to the linker and the log
, syscall
, and runtime
packages.
-See the Go 1.4.1 milestone on our issue tracker for details.
-
-go1.4.2 (released 2015/02/17) includes bug fixes to the go
command, the compiler and linker, and the runtime
, syscall
, reflect
, and math/big
packages.
-See the Go 1.4.2 milestone on our issue tracker for details.
-
-go1.4.3 (released 2015/09/22) includes security fixes to the net/http
package and bug fixes to the runtime
package.
-See the Go 1.4.3 milestone on our issue tracker for details.
-
-Go 1.3 is a major release of Go. -Read the Go 1.3 Release Notes for more information. -
- -
-go1.3.1 (released 2014/08/13) includes bug fixes to the compiler and the runtime
, net
, and crypto/rsa
packages.
-See the change history for details.
-
-go1.3.2 (released 2014/09/25) includes bug fixes to cgo and the crypto/tls packages. -See the change history for details. -
- --go1.3.3 (released 2014/09/30) includes further bug fixes to cgo, the runtime package, and the nacl port. -See the change history for details. -
- --Go 1.2 is a major release of Go. -Read the Go 1.2 Release Notes for more information. -
- -
-go1.2.1 (released 2014/03/02) includes bug fixes to the runtime
, net
, and database/sql
packages.
-See the change history for details.
-
-go1.2.2 (released 2014/05/05) includes a -security fix -that affects the tour binary included in the binary distributions (thanks to Guillaume T). -
- --Go 1.1 is a major release of Go. -Read the Go 1.1 Release Notes for more information. -
- --go1.1.1 (released 2013/06/13) includes several compiler and runtime bug fixes. -See the change history for details. -
- -
-go1.1.2 (released 2013/08/13) includes fixes to the gc
compiler
-and cgo
, and the bufio
, runtime
,
-syscall
, and time
packages.
-See the change history for details.
-If you use package syscall's Getrlimit
and Setrlimit
-functions under Linux on the ARM or 386 architectures, please note change
-11803043
-that fixes issue 5949.
-
-Go 1 is a major release of Go that will be stable in the long term. -Read the Go 1 Release Notes for more information. -
- --It is intended that programs written for Go 1 will continue to compile and run -correctly, unchanged, under future versions of Go 1. -Read the Go 1 compatibility document for more -about the future of Go 1. -
- -
-The go1 release corresponds to
-weekly.2012-03-27
.
-
-go1.0.1 (released 2012/04/25) was issued to -fix an -escape analysis bug -that can lead to memory corruption. -It also includes several minor code and documentation fixes. -
- --go1.0.2 (released 2012/06/13) was issued to fix two bugs in the implementation -of maps using struct or array keys: -issue 3695 and -issue 3573. -It also includes many minor code and documentation fixes. -
- --go1.0.3 (released 2012/09/21) includes minor code and documentation fixes. -
- --See the go1 release branch history for the complete list of changes. -
- --See the Pre-Go 1 Release History page for notes -on earlier releases. -
- diff --git a/content/doc/devel/weekly.html b/content/doc/devel/weekly.html deleted file mode 100644 index e17461db..00000000 --- a/content/doc/devel/weekly.html +++ /dev/null @@ -1,6200 +0,0 @@ - - -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 change log and development mailing list.
- --* cmd/dist: fix detection of go1 version. -* cmd/go: add missing error check (thanks Evan Shaw), - allow underscores in tool name (thanks Shenghou Ma), - bug fixes, - copy tag_test.go from goinstall, - explain versions better, - respect $GOBIN always, - update for go1 tag format. -* cmd/godoc: canonicalize custom path redirects, - fix app engine version, - use virtual filesystem to implement -templates flag. -* codewalk/sharemem.xml: fix references to files. -* crypto/tls: don't select ECC ciphersuites with no mutual curve. -* doc: add JSON-RPC: a tale of interfaces article (thanks Francisco Souza), - describe the Windows MSI installer as experimental, - link to Go Project Dashboard from package list, - update wiki tutorial templates and template discussion, - and many minor fixes. -* exp/types: generalized GCImporter API. -* go/build: cgoEnabled is not known to cmd/dist anymore (thanks Shenghou Ma), - fix import check. -* godoc: make 'Overview' section collapsible. -* misc/dist: many fixes and tweaks. -* misc/emacs: fix indentation bug. -* misc/goplay: fix error on IE8 (thanks Yasuhiro Matsumoto). -* net: ignore ECONNABORTED from syscall.Accept (thanks Devon H. O'Dell). -* os: add missing byte to FileMode buffer (thanks Stefan Nilsson). -* path/filepath: convert drive letter to upper case in windows EvalSymlinks (thanks Alex Brainman), - correct comment in EvalSymlinks (thanks Alex Brainman), - use windows GetShortPathName api to force GetLongPathName to do its work (thanks Alex Brainman), - windows drive letter cannot be a digit (thanks Alex Brainman). -* run.bash: compile the codewalks. -* runtime: restore deadlock detection in the simplest case (thanks Rémy Oudompheng), - work around false negative in deadlock detection. -* text/template: fix typo in package comment. -* windows: installer fixes (thanks Joe Poirier). -- -
-As with last week's snapshot, this snapshot is another Go 1 release candidate. -A notable change in this snapshot are Windows installer fixes. - -Changes in this snapshot: -* 5l, 6l, 8l: fix stack split logic for stacks near default segment size. -* archive/zip: move r.zip off disk, into reader_test.go. -* build: catch API changes during build, - do more during windows build (thanks Alex Brainman), - lengthen timeout for the lengthy runtime test (thanks Shenghou Ma), - unset GOPATH before tests (thanks Shenghou Ma). -* cmd/cgo: add support for function export for gccgo (thanks Rémy Oudompheng), - fix handling of errno for gccgo. -* cmd/go: add -fno-common by default on Darwin (thanks Shenghou Ma), - don't add detail to errPrintedOutput, - fix directory->import path conversion, - make build errors more visible, - use .o, not .{5,6,8}, for gccgo created object files, - work around occasional ETXTBSY running cgo. -* cmd/godoc: add toys, tour button to playground, - inform users that the playground doesn't work via local godoc, - style example headings like links, - use *goroot as base path in zip file, - use FormatText for formating code in html template, - use shorter titles for tabs. -* cmd/gofmt: show ascii in usage (thanks Yasuhiro Matsumoto). -* cmd/pack: also recognize '\\' as path separator in filenames (thanks Shenghou Ma). -* crypto/tls: always send a Certificate message if one was requested. -* doc/install: remove reference to "Go Tutorial" (thanks Shenghou Ma). -* doc/play: use []rune instead of []int (thanks Yasuhiro Matsumoto). -* doc: add Go Concurrency Patterns: Timing out, moving on article (thanks Francisco Souza), - add Go image/draw package article and convert code snippets to Go1, - add Gobs of data article (thanks Francisco Souza), - add Godoc: documenting Go code article (thanks Francisco Souza), - add JSON and Go article (thanks Francisco Souza), - general update of gccgo installation instructions, - minor updates to most docs. -* flag: add examples. -* gc: fix struct and array comparisons for new bool rules (thanks Anthony Martin), - use quoted string format in import error, - when expanding append inline, preserve arguments. -* go/build: clarify why we exclude files starting with '_' or '.' (thanks Shenghou Ma), - clearer argument name for Import (src -> srcDir), - do not report Target for local imports, - fix match. -* go/printer, gofmt: fix multi-line logic. -* html/template: add Templates and XXXEscape functions, - fix nil pointer bug, - fix panic on Clone. -* io/ioutil: fix crash when Stat fails. -* make.bat: fix for old files (thanks Christopher Redden), - don't show error message if old generated files do not exist (thanks Shenghou Ma), - properly handle directories with spaces (thanks Alex Brainman). -* misc/cgo/gmp: update for Go 1 (thanks Shenghou Ma). -* misc/dashboard: remove old python package dashboard. -* misc/dist: don't ship cmd/cov or cmd/prof, - force modes to 0755 or 0644 in tarballs, - remove exp and old before building. -* misc/vim: restore fileencodings (thanks Yasuhiro Matsumoto). -* net/http: couple more triv.go modernizations, - ensure triv.go compiles and runs (thanks Robert Hencke). -* net: drop unnecessary type assertions and fix leak in test (thanks Mikio Hara). -* os: IsNotExist() should also consider ERROR_PATH_NOT_FOUND on Windows (thanks Shenghou Ma), - do not assume syscall.Write will write everything, - remove document duplication in error predicate functions (thanks Shenghou Ma), - return some invented data from Stat(DevNull) on windows (thanks Alex Brainman). -* path/filepath: implement Match and Glob on windows (thanks Alex Brainman). -* reflect: document PkgPath, Method, StructField, - panic if MakeSlice is given bad len/cap arguments. -* run.bat: disable test in test\bench\go1 to fix build (thanks Alex Brainman). -* runtime/cgo: darwin signal masking (thanks Mikio Hara), - linux signal masking (thanks Mikio Hara). -* runtime: do not handle signals before configuring handler, - manage stack by ourselves for badcallback on windows/amd64 (thanks Shenghou Ma), - remove unused goc2c.c (thanks Shenghou Ma). -* sort: add time complexity to doc (thanks Stefan Nilsson), - fix computation of maxDepth to avoid infinite loop (thanks Stefan Nilsson). -* spec: delete references to unsafe.Reflect,Typeof,Unreflect. -* syscall: Test SCM_CREDENTIALS, SO_PASSCRED on Linux (thanks Albert Strasheim), - add a test for passing an fd over a unix socket, - delete passfd_test.go. -* test: use testlib in a few more cases (thanks Shenghou Ma). -* text/template: fix a couple of parse bugs around identifiers, - variables do not take arguments. -- -
-This weekly snapshot is very close to what we expect will be the contents of -the Go 1 release. There are still a few minor documentation issues to resolve, -and a handful of bugs that should be addressed before the release, but the vast -majority of Go programs should be completely unaffected by any changes we make -between now and the full release. - -If you're interested in helping us test, eager to try out Go 1, or just -curious, this weekly snapshot is the one to try. We'll issue a new App Engine -Go 1 beta SDK very soon, so if you're an App Engine user you can try it there -too. - -To help us focus on any remaining bugs and avoid introducing new ones, we will -restrict our attention to critical fixes and issues marked Go1-Must in the -issue tracker. Everything non-essential will be held until after the Go 1 -release is cut and in the field for a while. - -Changes in this snapshot: -* archive/zip: verify CRC32s in non-streamed files, - write data descriptor signature for OS X; fix bugs reading it. -* build: build correct cmd/dist matching GOHOSTARCH (thanks Shenghou Ma), - re-enable some broken tests in run.bash (thanks Shenghou Ma), - remove some references to Make.inc etc. - use run.go for running tests. -* builder: use short test for subrepos (thanks Shenghou Ma). -* cgo, runtime: diagnose callback on non-Go thread. -* cmd/api: set compiler for all build contexts, - work on Windows again, and make gccgo files work a bit more. -* cmd/cgo: document CGO_LDFLAGS and CGO_CFLAGS, - silence const warnings. -* cmd/dist, cmd/go: move CGO_ENABLED from 'go tool dist env' to 'go env' (thanks Shenghou Ma). -* cmd/dist: fix build for Linux/ARM (thanks Shenghou Ma), - use correct hg tag for go version (thanks Alex Brainman). -* cmd/fix: add rules for net/http -> net/http/httputil renames. -* cmd/gc: allow ~ in import paths, - delete old map delete in walk, - do not confuse unexported methods of same name, - if $GOROOT_FINAL is set, rewrite file names in object files, - implement len(array) / cap(array) rule, - import path cannot start with slash on Windows (thanks Shenghou Ma), - must not inline panic, recover, - show duplicate key in error, - unnamed struct types can have methods. -* cmd/go: add -compiler, - add env command, use to fix misc/cgo/testso, - allow go get with arbitrary URLs, - allow ssh tunnelled bzr, git and svn (thanks Ingo Oeser), - always provide .exe suffix on windows (thanks Shenghou Ma), - document import path meta tag discovery in go help remote, - honor buildflags in run, test (thanks Rémy Oudompheng), - local import fixes, - make go get new.code/... work, - rebuild external test package dependencies, - respect $GOBIN always, - support -compiler for go list, fix isStale for gccgo (thanks Rémy Oudompheng). -* cmd/godoc: add support for serving templates. - fix codewalk handler (thanks Francisco Souza). - remove extra / in paths (thanks Ugorji Nwoke), - support $GOPATH, simplify file system code, - switch on +1 buttons. -* cmd/gofmt: fix race in long test (thanks Mikio Hara). -* codereview: fix for Mercurial 2.1. -* crypto/x509: allow server gated crypto in windows systemVerify (thanks Mikkel Krautz), - do not forget to free cert context (thanks Alex Brainman), - don't include empty additional primes in PKCS#1 private key, - enforce path length constraint, - new home for root fetchers; build chains using Windows API (thanks Mikkel Krautz). -* csv: clarify what a negative FieldsPerRecord means. -* database/sql: add docs about connection state, pooling, - ensure Stmts are correctly closed (thanks Gwenael Treguier), - fix double connection free on Stmt.Query error, - fix typo bug resulting in double-Prepare. -* database/sql: add ErrBadConn. -* doc/go1: template packages have changed since r60. -* doc/go_mem: init-created goroutine behavior changes for Go 1 (thanks Shenghou Ma). -* doc/gopher: flip frontpage gopher's eyes. -* doc: add "About the go command" article, - add C? Go? Cgo! article (thanks Francisco Souza), - add Go's declaration syntax article (thanks Francisco Souza), - add more gophers, - add note about import . to Go 1 compatibility notes, - several doc fixes and improvements, - update Effective Go init section, - update progs/run (thanks Shenghou Ma), - update reference gopher, - web site tweaks. -* encoding/asn1: handle UTCTime before the year 2000. -* encoding/binary: improve package comment (thanks Stefan Nilsson). -* encoding/gob: fix memory corruption. -* encoding/json: document that nil slice encodes as `null`. -* exp/wingui: moved to code.google.com/p/gowingui. -* expvar: add locking to String, and use RWMutex properly throughout, - add missing locking in String methods. -* fmt, log: stop using unicode. -* fmt: minor tweak of package doc to show headings in godoc (thanks Volker Dobler). -* go/build, cmd/go: add support for .syso files. -* go/build: add NoGoError, - add dependency test, - do not parse .syso files (thanks Alex Brainman). -* go/parser: avoid endless loop in case of internal error, - better error synchronization. -* go/printer, gofmt: nicer formatting of multi-line returns. -* go/printer: example for Fprint. -* go/scanner: better panic diagnostic. -* go spec: no known implementation differences anymore, - fix inaccuracy in type identity definition. -* io: better document WriterAt. -* misc/dashboard: remove obsolete package builder code. -* misc/dist: add source archive support, - add windows installer and zip support, - minimum target requirement is 10.6 for Darwin (thanks Shenghou Ma). -* misc/emacs: fix extra indentation after comments that end with a period. -* misc/xcode: example install of language spec for Xcode 4.x (thanks Emil Hessman). -* net, net/rpc, reflect, time: document concurrency guarantees. -* net/http: fix crash with Transport.CloseIdleConnections, - return appropriate errors from ReadRequest. -* net: add skip message to test (thanks Mikio Hara), - disable use of external listen along with other external network uses, - do not use reflect for DNS messages (thanks Rémy Oudompheng), - document ReadMsgUnix, WriteMsgUnix, - fix TestDialTimeout on windows builder, - improve server and file tests (thanks Mikio Hara), - make Dial and Listen behavior consistent across over platforms (thanks Mikio Hara), - remove dependence on bytes, fmt, strconv, - silence another epoll print, - use IANA reserved port to test dial timeout (thanks Mikio Hara). -* os: document FileInfo.Size as system-dependent for irregular files, - fix SameFile to work for directories on windows (thanks Alex Brainman). -* path/filepath/path_test.go: repair and enable TestAbs. -* path/filepath: disable AbsTest on windows, - retrieve real file name in windows EvalSymlinks (thanks Alex Brainman). -* runtime/pprof: disable test on Leopard 64-bit. -* runtime: add Compiler, - fix windows/amd64 exception handler (thanks Alex Brainman), - inline calls to notok, - move runtime.write back to C, - print error on receipt of signal on non-Go thread, - remove unused runtime·signame and runtime·newError, - try extending arena size in 32-bit allocator (thanks Rémy Oudompheng), - wait for main goroutine before setting GOMAXPROCS (thanks Rémy Oudompheng). -* strconv: add table-based isPrint, remove dependence on bytes, unicode, and strings. -* sync/atomic: disable store and load test on a single processor machine (thanks Mikio Hara). -* syscall: fix mkall.sh, mksyscall_linux.pl, and regen for Linux/ARM (thanks Shenghou Ma). -* test/run: use all available cores on ARM system (thanks Shenghou Ma). -* test: actually run them on windows (thanks Alex Brainman), - add inherited interface test to ddd.go, - enable method expression tests in ddd.go, - invoke go command in run.go, - match gccgo error messages for bug388.go, - skip . files in directory. -* testing: do not print 'no tests' when there are examples. -* time: during short test, do not bother tickers take longer than expected (thanks Shenghou Ma), - mention receiver in Unix, UnixNano docs. -* unicode/utf16: remove dependence on package unicode. -* unicode/utf8: remove dependence on unicode. -* windows: make background of gopher icon transparent (thanks Volker Dobler). -- -
-This snapshot includes a major re-design of the go/build package. -Its FindTree, ScanDir, Tree, and DirInfo types have been replaced with the -Import and Package types. There is no gofix. Code that uses go/build will need -to be updated manually to use the package's new interface. - -Other changes: -* 6a/6l: add IMUL3Q and SHLDL. -* all: remove unused unexported functions and constants (thanks Rémy Oudompheng). -* build: add GO_ prefix to LDFLAGS and GCFLAGS (thanks Gustavo Niemeyer). -* cmd/cc: fix an out of bounds array access (thanks Anthony Martin), - grow some global arrays. -* cmd/dist: force line-buffering stdout/stderr on Unix (thanks Shenghou Ma), - recognize CC="ccache clang" as clang. -* cmd/go: avoid repeated include dirs (thanks Rémy Oudompheng), - fix -I flag for gc command (thanks Gustavo Niemeyer), - fix verbose command displaying (thanks Gustavo Niemeyer), - fixes for gccgo (thanks Rémy Oudompheng), - many fixes, - test -i should not disable -c (thanks Shenghou Ma). -* cmd/vet: don't give error for Printf("%+5.2e", x) (thanks Shenghou Ma). -* cmd/yacc/units.y: update comment, give better error messages when $GOROOT not set (thanks Shenghou Ma). -* crypto/tls: force OS X target version to 10.6 for API compatibility (thanks Mikkel Krautz). -* crypto/x509: fix typo in Verify documentation (thanks Mikkel Krautz). -* dist: treat CC as one unit (thanks Scott Lawrence). -* doc/go1: add justification discussions to major changes, - minor corrections and updates. -* doc: describe API changes to go/build, - elaborate available checks for cmd/vet (thanks Shenghou Ma), - expand code.html to discuss the go tool in more depth, - instruct FreeBSD/Linux users to rm the old version first, - remove Go for C++ Programmers, - remove roadmap document, - remove tutorial, - update codelab/wiki to Go 1 (thanks Shenghou Ma), -* encoding/gob: fix "// +build" comment for debug.go (thanks Shenghou Ma), - more hardening for lengths of input strings. -* encoding/json: drop MarshalForHTML; gofix calls to Marshal, - escape output from Marshalers. -* encoding/xml: fix anonymous field Unmarshal example (thanks Gustavo Niemeyer), - fix xml test tag usage (thanks Gustavo Niemeyer). -* gc: disallow absolute import paths, - fix escape analysis + inlining + closure bug, - fix string comparisons for new bool rules (thanks Anthony Martin), - reject import paths containing special characters (thanks Anthony Martin). -* go/ast: examples for ast.Print, ast.Inspect. -* go/doc, godoc: fix range of type declarations. -* go/parser: check import path restrictions, - expand test cases for bad import. -* go/printer, gofmt: improved comment placement. -* go/printer: fix printing of variadic function calls (thanks Anthony Martin), - fix test for new import path restrictions (thanks Anthony Martin), - replace multiline logic, - simpler exprList code, more tests. -* godoc: add Examples link to top-level index, - bring back highlighting, selections, and alerts, - consistent placement of documentation sections, - don't show directories w/o packages in flat dir mode, - don't show testdata directories, - fix codewalks. -* gotype: provide -comments flag. -* html/template: make doctype check case-insensitive (thanks Scott Lawrence), - use correct method signature in introduction example (thanks Mike Rosset). -* io: document that I/O is not necessarily safe for parallel access. -* ld: allow more -L options (thanks Shenghou Ma), - fix alignment of rodata section. -* misc: add zsh completion for go tool (thanks Rémy Oudompheng). -* misc/bash: Completion for go tool (thanks Yissakhar Z. Beck). -* misc/dashboard: fix bug in UI template, - record install counts for external packages. -* misc/dist: implement binary distribution scripts in go. -* misc/gobuilder: send commit time in RFC3339 format. -* misc/xcode: move Xcode3 specific files into sub directory. -* net/http/cgi: add an empty response test, - fix empty response. -* net/http/httptest: make Server.Close wait for outstanding requests to finish. -* net/http/httputil: fix DumpRequestOut on https URLs, - make https DumpRequestOut less racy. -* net/http: add overlooked 418 status code, per RFC 2324, - fix ProxyFromEnvironment bug, docs, add tests, - make a test more paranoid & reliable on Windows. -* net/rpc: silence read error on closing connection. -* net: add stubs for NetBSD (thanks Benny Siegert), - make -external flag for tests default to true (thanks Mikio Hara), - reorganize test files (thanks Mikio Hara). -* os: diagnose chdir error during StartProcess, - implement UserTime/SystemTime on windows (thanks Alex Brainman), - implement sameFile on windows (thanks Alex Brainman), - release process handle at the end of windows (*Process).Wait (thanks Alex Brainman), - sleep 5ms after process has exited on windows (thanks Alex Brainman). -* path/filepath: note that SplitList is different from strings.Split, - steer people away from HasPrefix. -* reflect: don't panic comparing functions in DeepEqual. - make Value.Interface return immutable data. -* runtime/pprof: support OS X CPU profiling. -* runtime: add sanity checks to the runtime-gdb.py prettyprinters, - check for ARM syscall failures (thanks Shenghou Ma), - darwin and linux signal masking, - run init on main thread, - size arena to fit in virtual address space limit. -* spec: allow disallow of \uFFFD in import path, - apply method sets, embedding to all types, not just named types, - clarifications around exports, uniqueness of identifiers, - import path implementation restriction, - inside functions, variables must be evaluated, - use the term "lexical token" (rather then "lexical symbol"). -* sync: add Once example, remove old WaitGroup example. -* test/bench/shootout: update post-Makefile. -* test: add documentation, misc fixes. -* testing: add -test.example flag to control execution of examples. -* text/template: add example showing use of custom function, - add examples that use multiple templates, - fix redefinition bugs. -* time: add a comment about how to use the Duration constants. -- -
-This weekly snapshot includes changes to the os and runtime packages. - -This should be the last of the significant incompatible changes before Go 1. - -There are no longer error constants such as EINVAL in the os package, since the -set of values varied with the underlying operating system. There are new -portable functions like IsPermission to test common error properties, plus a -few new error values with more Go-like names, such as ErrPermission and -ErrNoEnv. - -The os.Getenverror function has been removed. To distinguish between a -non-existent environment variable and an empty string, use os.Environ or -syscall.Getenv. - -The Process.Wait method has dropped its option argument and the associated -constants are gone from the package. Also, the function Wait is gone; only the -method of the Process type persists. - -The non-portable Waitmsg type has been replaced with the portable ProcessState. - -Much of the API exported by package runtime has been removed in favor of -functionality provided by other packages. Code using the runtime.Type -interface or its specific concrete type implementations should now use package -reflect. Code using runtime.Semacquire or runtime.Semrelease should use -channels or the abstractions in package sync. - -The runtime.Alloc, runtime.Free, and runtime.Lookup functions, an unsafe API -created for debugging the memory allocator, have no replacement. - -The runtime.Cgocalls and runtime.Goroutines functions have been renamed to -runtime.NumCgoCall and runtime.NumGoroutine. - -The "go fix" command will update code to accommodate most of these changes. - -Other changes: -* 5c, 6c, 8c, 6g, 8g: correct boundary checking (thanks Shenghou Ma). -* 5g, 6g, 8g: flush modified globals aggressively. -* 8a, 8l: add EMMS instruction (thanks Evan Shaw). -* bufio: don't return errors from good Peeks. -* build: add make.bash --no-clean option, - improve Windows support. -* builder: reuse existing workspace if possible (thanks Shenghou Ma), - update for os.Wait changes. -* bytes: document Compare/Equal semantics for nil arguments, and add tests. -* cgo: fix definition of opaque types (thanks Gustavo Niemeyer). -* cmd/api: record return type of functions for variable typecheck (thanks Rémy Oudompheng). -* cmd/cgo: bug fixes. -* cmd/dist: add clang specific -Wno options (thanks Bobby Powers), - fix install cmd/5g on non-arm system, - fix pprof permissions (thanks Bobby Powers), - make dir check in defaulttarg() more robust (thanks Shenghou Ma), - use correct package target when cross-compiling (thanks Alex Brainman). -* cmd/gc: correctly typecheck expression lists in returns (thanks Rémy Oudompheng), - don't believe that variables mentioned 256 times are unused (thanks Rémy Oudompheng), - error on constant shift overflows (thanks Rémy Oudompheng), - fix comparison of struct with _ field. - fix error for floating-point constant %, - new, less strict bool rules. -* cmd/go: add tool -n flag, - go test -i correctly handle cgo packages (thanks Shenghou Ma). -* codereview: fix submit message for new clone URL (thanks Shenghou Ma). -* database/sql/driver: API cleanups. -* doc: many fixes and adjustments. -* encoding/gob: cache engine for user type, not base type, - catch internal error when it happens, - fix mutually recursive slices of structs. -* encoding/json: ignore anonymous fields. -* go/doc: return Examples in name order. -* go/parser: imaginary constants and ! may start an expression. -* go/printer, gofmt: improved comma placement. -* go/printer: don't lose relevant parentheses when rewriting selector expressions. -* godoc: adjust line height in pre blocks, - don't print spurious suggestion when running "go doc foo", - fix absolute->relative mapping, - fix tag mismatch validation errors (thanks Scott Lawrence), - import example code support, - support flat directory view again. -* html/template: add Clone and AddParseTree, - don't indirect past a Stringer, - minor tweak to docs to improve HTML typography. -* image: add Decode example. -* ld: add NOPTRBSS for large, pointer-free uninitialized data. -* math/rand: Intn etc. should panic if their argument is <= 0. -* misc/dist/windows: distro builder updates (thanks Joe Poirier). -* misc/goplay: remain in work directory, build in temp directory. -* net, os, syscall: delete os.EPLAN9 (thanks Mikio Hara). -* net/http: add optional Server.TLSConfig field. -* net/smtp: use EHLO then HELO. -* net/textproto: accept bad MIME headers as browsers do. -* net/url: regularise receiver names. -* net: make LocalAddr on multicast return group address (thanks Mikio Hara), - make parseProcNetIGMP more robust (thanks Mikio Hara), - more selfConnect debugging: panic if ra == nil in internetSocket, - panic if sockaddrToTCP returns nil incorrectly, - other miscellaneous fixes. -* path, path/filepath: polish documentation (thanks Rémy Oudompheng). -* pprof: add Profile type. -* runtime: avoid malloc during malloc, - define NSIG to fix plan 9 build (thanks David du Colombier), - fix FreeBSD signal handling around thread creation (thanks Devon H. O'Dell), - goroutine profile, stack dumps, - implement runtime.osyield on FreeBSD 386, amd64 (thanks Devon H. O'Dell), - permit default behavior of SIGTSTP, SIGTTIN, SIGTTOU, - release unused memory to the OS (thanks Sébastien Paolacci), - remove an obsolete file (thanks Mikio Hara). -* spec: make all comparison results untyped bool, - refine the wording about variables in type switches, - struct comparison only compares non-blank fields. -* syscall: Make Pdeathsig type Signal in SysProcAttr on Linux (thanks Albert Strasheim), - fix bounds check in Error, - force Windows to always use US English error messages (thanks Shenghou Ma). -* test: migrated to new go-based testing framework. -* text/template: evaluate function fields. -* time: use Go distribution zoneinfo if system copy not found. -- -
-This release includes some package changes that require changes to client code. - -The flate, gzip and zlib's NewWriterXxx functions no longer return an error. -The compiler will flag all affected code which must then be updated by hand. - -The os package's Exec and Time functions were removed. Callers should use -syscall.Exec and time.Now instead. The ShellExpand function was renamed to -ExpandEnv. The NewFile function now takes a uintptr and the *File.Fd method -returns a uintptr. - -The runtime package's Type type and its methods have been removed. -Use the reflect package instead. - -Other changes: -* 8a, 8l: add LFENCE, MFENCE, SFENCE (thanks Darren Elwood). -* all.bat: report error code back to the gobuilder (thanks Alex Brainman). -* archive/zip: hide Write method from *Writer type. -* build: create the correct $GOTOOLDIR, - get rid of deps.bash (thanks Anthony Martin), - reject make.bash on Windows. -* builder: set $GOBUILDEXIT for Windows (thanks Alex Brainman), -* bytes: add Reader, - return error in WriteTo if buffer is not drained. -* cgo: add support for returning errno with gccgo (thanks Rémy Oudompheng). -* cmd/api: follow constant references. -* cmd/cgo: omit //line in -godefs, -cdefs output. -* cmd/dist: fixes (thanks Alex Brainman, Gustavo Niemeyer, Mikio Hara, Shenghou Ma). -* cmd/fix: warn about exp, old, deleted packages. -* cmd/gc: suspend safemode during typecheck of inlined bodies. -* cmd/go: a raft of fixes, - connect os.Stdin for go run and go tool, - go get scheme detection (thanks Daniel Krech), - respect test -timeout flag. -* cmd/vet: warn for construct 'Println(os.Stderr, ...)' (thanks Shenghou Ma). -* compress/gzip: remove dead code (thanks Alex Brainman). -* container/heap: add example. -* dashboard: add gobuilder -fail mode. -* database/sql: more tests, - remove Into from ScannerInto/ScanInto, - rename ErrTransactionFinished to ErrTxDone, - support ErrSkip in Tx.Exec (thanks Andrew Balholm), - treat pointers as nullable types as with encoding/json (thanks Andrew Pritchard). -* debug/macho: drop terrifyingly monstrous URL from package comment. -* dist: prevent recusive loop on windows when fatal() is called (thanks Daniel Theophanes). -* doc: add App Engine docs to 'learn' and 'reference' pages, - add playground.js, - new document about compatibility of releases, - update install.html for binary distros, add install-source.html. -* effective_go: use new map deletion syntax. -* encoding/binary: add Size, to replace the functionality of the old TotalSize, - another attempt to describe the type of Read and Write's data, - slices are allowed; say so. -* encoding/json: document buffering. -* encoding/xml: add support for the omitempty flag (thanks Gustavo Niemeyer). -* exp/norm: merged charinfo and decomposition tables. -* exp/types: use build.FindTree in GcImporter (thanks James Whitehead). -* flate: delete WrongValueError type. -* fmt: diagnose invalid verb applied to pointer, - scan FALSE correctly. -* gc: bug fixes, better error messages. -* go/doc: handle recursive embedded types (thanks Gary Burd), - don't lose exported consts/vars with unexported type, - treat predeclared error interface like an exported type. -* go/printer: implement SourcePos mode. -* godoc: list examples in index, - new design, - regard lone examples as "whole file" examples. -* html/template: added more words about examples and doc (thanks Bjorn Tipling). -* log/syslog: return length of data provided by the user, not length of header. -* make.bat: remove double quotes (thanks Alex Brainman). -* math: fix gamma doc, link to OEIS. -* mime: unexport some internal details. -* misc/dist: add binary distribution packaging script for linux, - new hierarchy for binary distribution packaging scripts. -* net/http: add ServeContent, - don't spin on temporary accept failure, - fix client goroutine leak with persistent connections, - fix reference to URL.RawPath in docs (thanks Bjorn Tipling), - panic on duplicate registrations, - use mtime < t+1s to check for unmodified (thanks Hong Ruiqi). -* net: avoid Shutdown during Close, - avoid TCP self-connect, - disable TestDialTimeout on Windows, - disable multicast test on Alpha GNU/Linux, - disable wild use of SO_REUSEPORT on BSD variants (thanks Mikio Hara), - enable flags on stream for multicast listeners (thanks Mikio Hara), - make use of listenerBacklog (thanks Mikio Hara), - prefer an IPv4 listen if no address given (thanks Mikio Hara). -* os/exec: add Cmd.Waitmsg. -* os/signal: revive this package. -* regexp/syntax: add package and Parse commentary. -* regexp: allow substitutions in Replace, ReplaceString. -* runtime, pprof: add profiling of thread creation. -* runtime, time: accelerate tests in short mode (thanks Rémy Oudompheng). -* runtime: exit early on OABI systems (thanks Shenghou Ma), - drop to 32 bit malloc if 64 bit will not work, - fix "SysReserve returned unaligned address" bug on 32-bit systems (thanks Shenghou Ma), - fix grsec support (thanks Gustavo Niemeyer), - on 386, fix FP control word on all threads, not just initial thread, - put lockorder before pollorder in Select memory block, - use startpanic so that only one thread handles an incoming SIGQUIT. -* spec: add forward links from 'method set' to where it gets used, - clarify implementation restrictions on untyped floats, - disallow recursive embedded interfaces, - method names must be unique, - send on closed channel counts as "proceeding", - strings are more slices than arrays. -* strconv: handle very large inputs. -* strings: add Seek and ReadAt methods to Reader. -* sync/atomic: disable hammer pointer tests on wrong size system. -* testing: let runtime catch the panic. -* text/template: refer HTML users to html/template. -* text/template/parse: deep Copy method for nodes. -* time: clean up MarshalJSON, add RFC3339 method, - use "2006-01-02 15:04:05.999999999 -0700 MST" as String format. -- -
-This weekly snapshot includes a re-organization of the Go tools. - -Only the go, godoc, and gofmt tools are installed to $GOROOT/bin (or $GOBIN). -The remainder are installed to $GOROOT/bin/tool. -This puts the lesser-used tools (6g, cgo, govet, etc.) outside the user PATH. -Instead these tools may be called through the go tool with 'go tool command'. -For example, to vet hello.go you would type 'go tool vet hello.go'. -Type 'go tool' see the list of available tools. - -With the move, some tools were given simpler names: - 6cov -> cov - 6nm -> nm - goapi -> api - gofix -> fix - gopack -> pack - gopprof -> pprof - govet -> vet - goyacc -> yacc - -The os/signal package has been moved to exp/signal. - -A new tool named 'dist' has been introduced to handle building the gc tool -chain and to bootstrap the go tool. The old build scripts and make files -have been removed. - -Other changes: -* 5a, 6a, 8a, cc: check in y.tab.[ch]. -* 5l, 6l, 8l, ld: remove memory leaks (thanks Shenghou Ma). -* 5l, 6l, 8l: implement -X flag. -* 5l: make -v option output less nonessential clutter (thanks Shenghou Ma), - optimize the common case in patch() (thanks Shenghou Ma). -* 8a, 8l: implement support for RDTSC instruction (thanks Shenghou Ma). -* 8g: use uintptr for local pc. -* archive/zip: support full range of FileMode flags (thanks Gustavo Niemeyer). -* bufio: remove special error type, update docs. -* build: move the "-c" flag into HOST_CFLAGS (thanks Anthony Martin), - remove unnecessary pragmas (thanks Anthony Martin). -* builder: drop recover blocks. -* bytes: API tweaks. -* cgo: accept null pointers in gccgo flavour of C.GoString (thanks Rémy Oudompheng), - print line numbers in fatal errors when relevant (thanks Rémy Oudompheng). -* cmd/dist: add GOBIN to env's output (thanks Gustavo Niemeyer), - fix bug in bsubst (thanks Alex Brainman), - fix build on openbsd (thanks Mikio Hara), - generate files for package runtime, - ignore file names beginning with . or _, - prevent race on VERSION creation (thanks Gustavo Niemeyer). -* cmd/gc: another special (%hhS) case for method names, - describe debugging flags (thanks Anthony Martin), - diagnose \ in import path, - disallow switch _ := v.(type), - don't print implicit type on struct literal in export, - fix codegen reordering for expressions involving && and ||, - use octal escapes in mkopnames (thanks Anthony Martin). - use original constant expression in error messages (thanks Rémy Oudompheng). -* cmd/go: add support for release tags via git branches (thanks Gustavo Niemeyer), - build: print import errors when invoked on files (thanks Kyle Lemons), - clean test directories as they complete, - fix error message on non-existing tools (thanks Rémy Oudompheng), - fix handling of gccgo standard library (thanks Rémy Oudompheng), - fixed panic on `go clean -n` and `go clean -x` (thanks Sanjay Menakuru), - introduce support for "go build" with gccgo (thanks Rémy Oudompheng), - make vcs command actually gather output (thanks Roger Peppe), - pass env CGO_CFLAGS to cgo (thanks Jeff Hodges), - record location of failed imports for error reporting (thanks Rémy Oudompheng). -* cmd/goapi: expand embedded interfaces. -* cmd/goinstall: remove now that 'go get' works (thanks Gustavo Niemeyer). -* cmd/ld: fix gdbscript (thanks Wei Guangjing). -* cmd/pack: change gopack to pack in error messages. -* codereview: miscellaneous fixes and improvements. -* crypto/elliptic: p224Contract could produce a non-minimal representation. -* crypto/tls: better error message when connecting to SSLv3 servers. -* crypto/x509: use case-insensitive hostname matching. -* dashboard: support for sub-repositories, update to go1beta. -* database/sql: permit scanning into interface{}. -* doc: update go1.html for recent changes. -* encoding/base32: add DecodeString and EncodeToString helper methods, - ignore new line characters during decode. -* encoding/base64: ignore new line characters during decode. -* encoding/gob: document CommonType. -* encoding/hex: canonicalize error type names. -* encoding/json: call (*T).MarshalJSON for addressable T values. -* encoding/xml: fix decoding of xml.Name with sub-elements (thanks Gustavo Niemeyer), - fix documentation for Decoder.Skip. -* exp/norm: Added some benchmarks for form-specific performance measurements, - a few minor changes in prepration for a table format change. -* expvar: revise API. -* fix: add image/{bmp,tiff} to go1pkgrename. -* flag: allow a FlagSet to not write to os.Stderr, - describe valid input for Duration flags. -* fmt: add test of NaN map keys, - fix caching bug in Scan. -* go/build: put a space between 'generated by make' and package statement, - update syslist.go package comment. -* go/doc: fix URL linking in ToHTML (thanks Gary Burd), - added error, rune to list of predeclared types, - don't lose factory functions of non-exported types, - don't show methods of exported anonymous fields, - enable AllMethods flag (and fix logic). -* go/printer: don't print incorrect programs. -* go/scanner: idiomatic receiver names. -* go/spec: update language on map types. -* go/token: remove dependency on encoding/gob. -* gob: fuzz testing, plus a fix for very large type names. -* gobuilder: use go tool to build and test sub-repositories. -* godoc: add URL mode m=methods, - diagnostic for empty FS tree, - fix identifier search, - fix redirect loop for URL "/", - provide link to subdirectories, if any, - sort list of "other packages", - update metadata in appinit.go. -* gophertool: fix link to the build status dashboard (thanks Jongmin Kim). -* hgignore: add VERSION.cache (thanks Gustavo Niemeyer), - delete dregs, ignore tmpltohtml. -* html: add package doc. -* image: add package docs, rename s/UnknownFormatError/ErrFormat/ and, - delete the image.Repeated type, - remove image/bmp and image/tiff from std. -* io/ioutil: document EOF behavior in ReadFile and ReadAll. -* io: API tweaks. -* libmach: add stubs for Plan 9 (thanks Anthony Martin). -* make.bash: don't remove hgpatch. -* math/big: add raw access to Int bits, - API and documentation cleanup. -* misc/goplay: use go tool "run" (thanks Olivier Duperray). -* misc/osx: don't set GOROOT or modify profile files, - update for dist tool, drop image.bash, update readme. -* net, syscall: add IPv4 multicast helpers for windows (thanks Mikio Hara). -* net/http/httputil: fix race in DumpRequestOut, - preserve query params in reverse proxy. -* net/http: don't set Content-Type header for HEAD requests by default (thanks Patrick Mylund Nielsen), - fix nil pointer dereference in error case (thanks Volker Dobler), - close client fd sooner on response read error, - set cookies in client jar on POST requests (thanks Volker Dobler). -* net/rpc: fix data race on Call.Error. -* net: ListenMulticastUDP to listen concurrently across multiple listeners (thanks Mikio Hara), - disable normal multicast testing on linux/arm (thanks Mikio Hara), - fix Plan 9 build (thanks Anthony Martin), - fix windows build (thanks Alex Brainman), - move DNSConfigError to a portable file, - remove types InvalidConnError and UnknownSocketError, - replace error variable name e, errno with err (thanks Mikio Hara), - run TestDialTimeout on windows (thanks Alex Brainman), - update comments to remove redundant "net" prefix (thanks Mikio Hara). -* os/exec: TestExtraFiles - close any leaked file descriptors, - make sure file is not closed early in leaked fd test. -* os/signal: move to exp/signal. -* os/user: windows implementation (thanks Alex Brainman). -* os: Process.handle use syscall.Handle (thanks Wei Guangjing), - file windows use syscall.InvalidHandle instead of -1 (thanks Wei Guangjing), - remove SIGXXX signals variables, - turn FileStat.Sys into a method on FileInfo (thanks Gustavo Niemeyer). -* path/filepath: repair and simplify the symlink test. -* reflect: add comment about Type.Field allocation, - test that PtrTo returns types that match program types. -* runtime: add runtime.cputicks() and seed fastrand with it (thanks Damian Gryski), - delete UpdateMemStats, replace with ReadMemStats(&stats) (thanks Rémy Oudompheng), - fix float64 hash, - use GOTRACEBACK to decide whether to show runtime frames, - use per-map hash seeds (thanks Damian Gryski). -* spec: add number to the fibonacci sequence. -* std: add struct field tags to untagged literals. -* strings: add Fields example. -* syscall: add Timeval.Nano, Timespec.Nano, for conversion to Duration, - cache environment variables on Plan 9 (thanks Anthony Martin), - fix // +build comments in types_*.go, - fix build directive in types_linux.go, - update bootstrap scripts to sync with new go command (thanks Mikio Hara). -* test: add import test that caused an incorrect gccgo error, - add test for receiver named _, - add test of NaN in map, - add test which crashed gccgo compiler, - don't use package main for files without a main function, - fix bug headers, - float to integer test case, - make map nan timing test more robust, - match gccgo error messages, - test append with two different named types with same element type, - test method expressions with parameters, and with import, - test slice beyond len, - test that x := <-c accepts a general expression. -* testing: capture panics, present them, and mark the test as a failure. -* unicode: document large var blocks and the SpecialCase vars. -* vet: add a check for untagged struct literals. -- -
-This weekly snapshot renamed the html package to exp/html. The package will not -be present in the Go 1 distribution, but will be installable from source. - -Error variables in the archive/tar, archive/zip, compress/gzip, compress/zlib, -and crypto/bcrypt packages have been renamed from FooError to ErrFoo. -There is no gofix, but the compiler will flag code that needs updating. - -This weekly snapshot relocates many packages to sub-repositories of the main -Go repository. These are the old and new import paths: - - crypto/bcrypt code.google.com/p/go.crypto/bcrypt - crypto/blowfish code.google.com/p/go.crypto/blowfish - crypto/cast5 code.google.com/p/go.crypto/cast5 - crypto/md4 code.google.com/p/go.crypto/md4 - crypto/ocsp code.google.com/p/go.crypto/ocsp - crypto/openpgp code.google.com/p/go.crypto/openpgp - crypto/openpgp/armor code.google.com/p/go.crypto/openpgp/armor - crypto/openpgp/elgamal code.google.com/p/go.crypto/openpgp/elgamal - crypto/openpgp/errors code.google.com/p/go.crypto/openpgp/errors - crypto/openpgp/packet code.google.com/p/go.crypto/openpgp/packet - crypto/openpgp/s2k code.google.com/p/go.crypto/openpgp/s2k - crypto/ripemd160 code.google.com/p/go.crypto/ripemd160 - crypto/twofish code.google.com/p/go.crypto/twofish - crypto/xtea code.google.com/p/go.crypto/xtea - exp/ssh code.google.com/p/go.crypto/ssh - net/dict code.google.com/p/go.net/dict - net/websocket code.google.com/p/go.net/websocket - exp/spdy code.google.com/p/go.net/spdy - encoding/git85 code.google.com/p/go.codereview/git85 - patch code.google.com/p/go.codereview/patch - -Gofix will update imports of these packages to use the new import paths. -Installations that depend on these packages will need to install them using a -'go get' command. - -Other changes: -* 6c, 8c: make floating point code NaN-safe. -* 6l, 8l: remove unused macro definition (thanks Shenghou Ma). -* archive/tar: fix race in TestNonSeekable. -* archive/zip: add functions to convert between os.FileInfo & FileHeader. -* build: do not build all C compilers (thanks Shenghou Ma), - remove code now in subrepositories. -* bytes: remove dead code, complete documentation, - restore panic on out-of-memory, - turn buffer size overflows into errors. -* cgo: -cdefs should translate unsafe.Pointer to void * (thanks Shenghou Ma). -* cmd/gc: forgotten recursion on ninit itself in order.c. -* cmd/go: bug fixes, implement go get, - correctly handle -n and -x flags for 'go run' (thanks Shenghou Ma), - solve ambiguity of get lp.net/project/foo (thanks Gustavo Niemeyer), - update doc.go with text generated from the usage strings. -* cmd/goapi: new tool for tracking exported API over time. -* codereview: support for subrepositories. -* compress/flate: fix a typo, improve compression rate by 3-4%, - increase the length of hash table from 1<<15 to 1<<17. 0%-16% speedup, - make lazy matching work, - reduce memory pressure at cost of additional arithmetic operation, - use append instead of slice+counter. -* crypto: rename some FooError to ErrFoo. -* dashboard: fix -commit for new xml package. -* database/sql: add NullInt64, NullFloat64, NullBool (thanks James P. Cooper), - convert SQL null values to []byte as nil (thanks James P. Cooper), - fix Tx.Query (thanks Blake Mizerany). -* doc: expand FAQ on GOMAXPROCS, update to Go 1. -* doc/go1: add encoding/xml and net/url changes (thanks Gustavo Niemeyer), - add more info about hash and net changes, delete reference to html, - add flag, runtime, testing, image , mime, filepath.Walk, - document sub-repositories. -* encoding/binary: document that PutVarint, PutUvarint may panic. -* encoding/varint: deleted WriteXvarint. -* encoding/xml: add docs for ignoring tag (thanks Gustavo Niemeyer), - bring API closer to other packages (thanks Gustavo Niemeyer), - improve []byte handling (thanks Gustavo Niemeyer), - remove Marshaler support (thanks Gustavo Niemeyer), - support ignoring fields with "-" (thanks Gustavo Niemeyer). -* exp/ebnflint: test spec during 'go test'. -* exp/norm: fixes a subtle bug introduced by change 10087: random offset. -* gc, runtime: handle floating point map keys. -* gc: avoid DOT in error messages, - do not try to add a key with incorrect type to a hash (thanks Jeff R. Allen), - fix order of evaluation, - fix recursion loop in interface comparison, - handle function calls in arguments to builtin complex operations, - missed typecheck in subscripting a const string, - permit unsafe.Pointer for inlined functions, - softer criteria for inlinability, - static implements check on typeswitches only applies to concrete case types, - test case for recursive interface bug. -* go/ast: respect ImportSpec.EndPos (thanks Scott Lawrence). -* go/build: add BuildTags to Context, allow !tag. -* go/doc: rewrite and add lots of tests. -* go/parser: use explicit parser.Mode type. -* go/printer, gofmt: respect line breaks in signatures. -* go/scanner: use explicit scanner.Mode type. -* gob: annotate debug.go so it's not normally built, - reduce the maximum message size. -* godoc: log node printing error, - move overview before API TOC, - update metadata upon launch. -* gofix: add -debug flag for quicker diagnosis of internal errors, - handle xml.Unmarshal in xmlapi fix (thanks Gustavo Niemeyer), - update go1pkgrename for subrepositories. -* goyacc: fix indexing bug when yydebug >= 2. -* ld: fix Mach-O code signing for non-cgo binaries (thanks Mikkel Krautz). -* libmach: cross compiling support (thanks Shenghou Ma). -* math/big: assembly versions of bitLen for x86-64, 386, and ARM (thanks David G. Andersen), - return type of bitLen is an int; use MOVL on amd64 (thanks David G. Andersen), - add examples for Rat and Int's SetString and Scan methods, - slight improvement to algorithm used for internal bitLen function (thanks David G. Andersen), - test both bitLen and bitLen_g. -* net/http: add Request.RequestURI field, - disabled test for Transport race / deadlock bug, - fix Transport deadlock (thanks Yoshiyuki Kanno), - make ParseForm ignore unknown content types (thanks Roger Peppe), - parse CONNECT requests (thanks Andrew Balholm). -* net/rpc: fix data race in benchmark, - fix race in TestClientWriteError test, - log Call reply discard. -* net: Dial, ListenPacket with "ip:protocol" network for raw IP sockets (thanks Mikio Hara), - actually reset deadline when time is zero, - consistent OpError message (thanks Mikio Hara), - fix dialing google test (thanks Mikio Hara), - make WriteTo fail when UDPConn is already connected (thanks Mikio Hara). -* regexp: remove vestigial Error type. -* runtime: add type algorithms for zero-sized types, - move NumCPU declaration into debug.go. -* spec: function invocation, panic on *nil. -* syscall: add NOTE_* constants on OS X (thanks Robert Figueiredo). -* test: explicitly use variables to avoid gccgo "not used" error. -* text/template: add example for Template. -- -
-This weekly snapshot renamed the exp/sql package to database/sql, and moved -utf8.String from unicode/utf8 to exp/utf8string. - -Package net's SetTimeout methods were changed to SetDeadline. - -Many functions in package os now take a os.FileMode argument instead of a -plain uint32. An os.ModeSticky constant is also now defined. - -The meaning of the first buffer element for image.YCbCr has changed to match -the semantics of the other image types like image.RGBA. - -The NewMD5, NewSHA1 and NewSHA256 functions in crypto/hmac have been -deprecated. Use New instead, explicitly passing the hash function. - -Other changes: -* buildscripts: move to buildscript directory (thanks Shenghou Ma). -* bytes: add the usual copyright notice to example_test.go (thanks Olivier Duperray). -* cmd/go: remove mentions of 'gotest' from the documentation, - skip _obj directories in package scans. -* container/heap: better package documentation. -* crypto/elliptic: add constant-time P224. -* crypto/hmac: Add HMAC-SHA224 and HMAC-SHA384/512 (thanks Luit van Drongelen), -* crypto/tls: add FreeBSD root certificate location (thanks Shenghou Ma). -* crypto/x509: remove explicit uses of rsa. -* doc: various updates (thanks Jongmin Kim, Scott Lawrence, Shenghou Ma, Stefan Nilsson). -* encoding/json: allow / and % in tag names, - document angle bracket escaping, - fix comments, tweak tests for tag names (thanks Mikio Hara). -* encoding/xml: marshal/unmarshal xml.Name in field (thanks Gustavo Niemeyer). -* exp/inotify: fix data race in linux tests. -* exp/proxy: fix build after URL changes (thanks Gustavo Niemeyer). -* exp/sql: copy when scanning into []byte by default, - rename NullableString to NullString and allow its use as a parameter. -* exp/ssh: add marshal functions for uint32 and uint64 types, - handle versions with just '\n', - rename (some) fields (thanks Christopher Wedgwood). -* exp/terminal: fix build on non-Linux using Makefiles. -* fmt: enable and fix malloc test, -* gc: don't emit pkgpath for error type, - don't fault on return outside function (thanks Scott Lawrence), - fieldnames in structliterals in exported inlines should not be qualified if they're embedded builtin types, - fix infinite recursion for embedded interfaces, - give esc.c's sink an orig so -mm diagnostics work again, - handle printing of string/arrayrune conversions. - remove redundant code (thanks Shenghou Ma). -* go/build: no back slash in FindTree returned pkg name (thanks Alex Brainman). -* go/doc: collect imports, - don't shadow receiver. - rewrote and completed test framework. - print only one newline between paragraphs -* go/parser: expressions may have comments. -* go/scanner: fix example (thanks Olivier Duperray). -* go/token: replaced Files() with Iterate(). -* godoc: add anchors to cmd documentation headings, - remove "need more packages?" link, - specify HTML page metadata with a JSON blob, - support canonical Paths in HTML metadata. -* html/template: fix docs after API changes (thanks Gustavo Niemeyer). -* html: in foreign content, check for HTML integration points in breakout. -* image/color: rename modelYCbCr to yCbCrModel (thanks Benny Siegert), - simplify documentation (thanks David Crawshaw). -* image: add PixOffset methods. -* math/rand: decrease test duration in short mode, - document default initial seed for global generator (thanks Scott Lawrence). -* mime: make FormatMediaType take full type for consistency. -* misc/cgo/test: make tests run on windows (thanks Alex Brainman). -* net/http/cgi: increase a flaky test timeout. -* net/http: change test to use override param instead of chan, - log handler panic before closing HTTP connection, - send cookies in jar on redirect (thanks Jeff Hodges), - the documentation should call NewRequest with the right signature (thanks Christoph Hack), - update the Client docs a bit. -* net/url: cleaned up URL interface (v2) (thanks Gustavo Niemeyer). -* net: consistent log format in test (thanks Mikio Hara), - various build fixes (thanks Mikio Hara), - use NewTimer, not NewTicker, in fd_windows.go. -* old/netchan: fix data race on client hashmap. -* os/exec: trivial allocation removal in LookPath (thanks Gustavo Niemeyer). -* os: remove old note about NewSyscallError being special (thanks Alex Brainman), -* path: added examples (thanks Sanjay Menakuru). -* pkg: Add and fix Copyright of "hand generated" files (thanks Olivier Duperray), - add missing godoc comments to windows versions (thanks Alex Brainman). -* regexp: add SubexpNames. -* runtime: implement runtime.usleep for FreeBSD/386 and amd64 (thanks Shenghou Ma), - madvise and SysUnused for Darwin (thanks Dave Cheney). -* sync/atomic: fix data race in tests. -* syscall: add Unix method to TimeSpec, TimeVal, - fix plan9 build (thanks Mikio Hara). -* test: change several tests to not print, - fix bug364 to actually run, - match gccgo error messages for bug345, - split golden.out into expected output per test. -* testing: do not recover example's panic (thanks Shenghou Ma), - document examples. -* text/template/parse: use human error prints. -* text/template: fix nil error on redefinition. -* time: add Since, which returns the time elapsed since some past time t. -- -
-This weekly snapshot includes two package changes that may require changes to -client code. - -The image package's Tiled type has been renamed to Repeated. - -The encoding/xml package has been changed to make more idiomatic use of struct -tags, among other things. If you use the xml package please read the change -description to see if your code is affected: - http://code.google.com/p/go/source/detail?r=70e914beb409 - -Function inlining is now enabled by default in the gc compiler. - -Other changes: -* bytes: Buffer read of 0 bytes at EOF shouldn't be an EOF. -* cgo: if value for constant did not parse, get it from DWARF info, - write _cgo_export.h to object directory, not source dir. -* cmd/go: add -p flag for parallelism (like make -j), - add -v flag to build and install, - add ... patterns in import path arguments, - fix data race during build, - fix import directory list for compilation, - fix linker arguments, - handle cgo pkg-config pragmas, - handle path to cmd directory, - include test files in fmt, vet, and fix (thanks Sanjay Menakuru), - kill test processes after 10 minutes, - pass arguments to command for run (thanks Eric Eisner), - rely on exit code to tell if test passed, - use relative paths in go fix, go fmt, go vet output. -* cmd/gofmt: fix simplify.go by running gofmt on cmd/gofmt (thanks Olivier Duperray). -* crypto/openpgp: assorted cleanups, - truncate hashes before checking DSA signatures. -* crypto/tls: improve TLS Client Authentication (thanks Jeff R. Allen), - update generate_cert.go for new time package. -* dashboard: better caching, bug fixes. -* doc: update "How to Write Go Code" to use the go tool. - fix broken function codewalk examples. -* encoding/asn1: document support for *big.Int (thanks Florian Weimer). -* encoding/gob: fix panic when decoding []byte to incompatible slice types (thanks Alexey Borzenkov). -* encoding/json: don't marshal special float values (thanks Evan Shaw). -* encoding/xml: major Go 1 fixup (thanks Gustavo Niemeyer). -* exp/proxy: new package. -* exp/sql: add time.Time support, - close Rows on EOF, - fix potential corruption in QueryRow.Scan into a *[]byte. -* exp/ssh: various small fixes (thanks Dave Cheney). -* exp/terminal: add SetPrompt and handle large pastes, - add to level Makefile for the (non-Linux?) systems that need it. -* flag: add Duration flag type, - change Set method Value interface to return error instead of bool. -* gc: better errors messages, - avoid false positives when using scalar struct fields (thanks Rémy Oudompheng), - closure code gen improvements, - disallow declaration of variables outside package, - fix switch on interface values (thanks Rémy Oudompheng), - inlining bug fixes, - improve unsafe.Pointer type-check error messages (thanks Ryan Hitchman), - put limit on size of exported recursive interface (thanks Lorenzo Stoakes), -* go-mode.el: fix syntax highlighting of backticks (thanks Florian Weimer). -* go/ast: remove unnecessary result value from ast.Fprint/Print. -* go/build: allow colon in #cgo flags, - pass CgoLDFLAGS at end of link command. -* go/doc: new API, don't ignore anonymous non-exported fields, initial testing support. -* go/parser: remove unused Parse* functions. Simplified ParseExpr signature. -* go/printer: don't crash if AST contains BadXXX nodes. -* go/scanner: 17% faster scanning, remove InsertSemis mode. -* goinstall: use correct checkout URL for Google Code svn repos. -* gotest: make _testmain.go conform to gofmt rules (thanks Benny Siegert). -* goyacc: fix units.y build breakage (thanks Shenghou Ma). -* html/template: reenable testcases and fix mis-escaped sequences (thanks Mike Samuel). -* html: "in select in table" insertion mode (thanks Andrew Balholm), - adjust foreign attributes, - foreign element HTML integration points, tag name adjustment, - parse- -
-This snapshot includes changes to the images/ycbcr and testing packages, and -changes to the build system. - -The types for managing Y'CbCr images in the image/ycbcr have been moved to the -image and image/color packages. A gofix module will rewrite affected code. - -The testing package's B type (used when running benchmarks) now has the same -methods as T (used in tests), such as Print, Error, and Fatal. - -This weekly adds a new command named 'go' for building and testing go programs. -For Go 1, the go command will replace the makefile-based approach that we have -been using. It is not yet ready for general use, but all.bash does use it to -build the tree. If you have problems building the weekly, you can 'export -USE_GO_TOOL=false' before running all.bash to fall back to the makefiles. - -Other changes: -* archive/zip: add SetModTime method to FileHeader. -* build: make use of env (thanks Mikio Hara), - fixes to make "go install" work on windows (thanks Alex Brainman). -* bytes: add two Buffer examples. -* cgo: support export for built-in types (thanks Maxim Pimenov). -* cmd/go: avoid infinite loop with package specific flags (thanks Mikio Hara), - fixes to build standard library, - implement test command, - make sure use of pthread for gcc-4.5 and beyond (thanks Mikio Hara), - respect $GCFLAGS, - use spaces consistently in help message (thanks Roger Peppe), - many other improvements. -* codereview: initialize "found" in codereview.py (thanks Miki Tebeka). -* crypto/mime/net/time: add netbsd to +build tags (thanks Joel Sing). -* crypto/tls: don't assume an RSA private key in the API. -* crypto/x509: don't crash with nil receiver in accessor method. -* doc/effective_go: discuss redeclaration. -* doc: delete go course notes, - refer to http://build.golang.org/ where applicable (thanks Robert Hencke), - suggest code.google.com/p/go instead of go.googlecode.com/hg. -* encoding/binary: add Write and Read examples, - add more benchmarks (thanks Roger Peppe). -* encoding/gob: arrays are zero only if their elements are zero. -* encoding/json: cleanup leftover variables in array decoding (thanks Rémy Oudompheng), - examples for Marshal and Unmarshal. -* exp/ssh: rename ClientAuthPublicKey helper ClientAuthKeyring (thanks Dave Cheney), - simplify Stdin/out/errPipe methods (thanks Dave Cheney). -* fmt: speed up floating point print, clean up some code, - make the malloc test check its counts. -* gc: allow use of unsafe.Pointer in generated code, - avoid unsafe in defn of package runtime, - better linenumbers for inlined functions, - better loopdepth analysis for labels, - implement and test \r in raw strings, - inlining, allow empty bodies, fix _ arguments, - omit argument names from function types in error messages. -* go/ast, parser: remember short variable decls. w/ correspoding ident objects. -* go/build: add new +build tags 'cgo' and 'nocgo'. -* go/doc, godoc: move export filtering into go/doc -* go/printer, gofmt: fine tuning of line spacing. -* go/scanner: strip CRs from raw literals. -* gob: isZero for struct values. -* godoc: allow examples for methods (thanks Volker Dobler), - show methods of anonymous fields. -* goinstall: only suggest -fix for bad imports when appropriate. -* govet: add checking for printf verbs, - divide the program into one file per vetting suite. -* html: more parser improvements (thanks Andrew Balholm). -* json: some tests to demonstrate bad error messages, - use strconv.Append variants to avoid allocations in encoding. -* ld: add support for netbsd signature note section (thanks Joel Sing), - allow for IMAGE_REL_AMD64_ADDR32NB relocation type (thanks Alex Brainman). -* math/big: Rand shouldn't hang if argument is also receiver. -* misc/builder: set default builder host to build.golang.org. -* misc/dashboard: delete old build dashboard code , - improvements and fixes for the go implementation. -* misc/vim: fix go filetype detection (thanks Paul Sbarra). -* net, syscall, os: set CLOEXEC flag on epoll/kqueue descriptor. -* net, syscall: interface address and mask (thanks Mikio Hara). -* net/http: added interface for a cookie jar (thanks Volker Dobler), - test fixes (thanks Alex Brainman). -* net: add DialTimeout, - sort Makefile entries (thanks Mikio Hara). -* os, syscall: beginnings of NetBSD support (thanks Christopher Nielsen). -* os/exec: add test to verify net package's epoll fd doesn't go to child, - disable the ExtraFiles test on darwin. -* os: don't trust O_CLOEXEC on OS X, - make sure Remove returns correct error on windows (thanks Alex Brainman). -* path, path/filepath: add Dir to complement Base. -* path/filepath.Rel: document that the returned path is always relative. -* runtime: don't panic on SIGILL, just crash. -* spec: be precise about newlines. -* sql: add Rows.Columns. -* strconv: fix bug in extended-float based conversion, - implement faster parsing of decimal numbers, and - reduce buffer size for multi-precision decimals (thanks Rémy Oudompheng). -* syscall: regenerate z-files for linux/arm (thanks Mikio Hara), - sort Makefile, mkall.sh and mkerrors.sh entries (thanks Mikio Hara). -* test/bench/go1: first draft of Go 1 benchmark suite. -* testing: compare Log to Println (thanks Robert Hencke), - make signalling safer for parallel tests. -* text/template: better error message for empty templates, - fix handing of nil arguments to functions (thanks Gustavo Niemeyer). -* time: add JSON marshaler for Time (thanks Robert Hencke), - new AddDate method (thanks Roger Peppe). -* various: use $GCFLAGS and $GCIMPORTS like Make does (thanks Maxim Pimenov). -- -
-This snapshot includes language changes and changes to goinstall and gofmt. - -Equality and inequality (== and !=) are now defined for struct and array -values, respectively, provided the elements of the data structures can -themselves be compared. See the Go 1 release notes for the details: - http://weekly.golang.org/doc/go1.html#equality - -The rune type is now an alias for int32 and character literals have the default -type of rune. Code that uses int where it should use rune will break. -See the Go 1 release notes for the details: - http://weekly.golang.org/doc/go1.html#rune - -Goinstall now expects Google Code import paths to be of the form: - "code.google.com/p/go-tour/tree" -It will reject imports in the old style "go-tour.googlecode.com/hg/tree". -There is a gofix module to rename such imports. -Use goinstall -fix to update broken packages. - -Gofmt's flags have been modified slightly. -The -tabintent flag has been renamed -tabs. -The -spaces flag has been removed. - -Other changes: -* 5c, 6c, 8c: support 64-bit switch value (thanks Anthony Martin). -* 8c: handle 64-bit switch value. -* archive/tar: use struct comparison not DeepEqual (thanks Christopher Wedgwood). -* archive/zip: make zip understand os.FileMode (thanks Roger Peppe). -* bufio: make the minimum read buffer size 16 bytes. -* build: disable cgo on Windows/amd64, - regularize packages so they may be built without Makefiles. -* bytes: faster Count, Index, Equal. -* cgo: add basic gccgo support (thanks Rémy Oudompheng). -* codereview: fix path slash issue (thanks Yasuhiro Matsumoto). -* compress/flate: fix out of bounds error. -* contribute.html: do not fill in the reviewer field (thanks Florian Weimer). -* crypto/aes: made faster by eliminating some indirection (thanks Taru Karttunen). -* crypto/dsa: don't truncate input hashes. -* doc/go_tutorial: make clear the file example is Unix-specific. -* doc: add Defer, Panic, and Recover article, - add Error Handling article, - add Go 1 release notes document. -* encoding/gob: better error messages when types mismatch. -* env.bash: export CGO_ENABLED so cgo tests run (thanks Alex Brainman). -* exp/sql: simplify some string conversions. -* exp/ssh: Wait returns an *ExitError (thanks Gustav Paul). -* exp/ssh: improve client channel close behavior (thanks Dave Cheney). -* fmt: don't recur if String method (etc.) misbehaves. -* gc: better error messages, - inlining (disabled without -l), - many bug fixes (thanks Lucio De Re and Rémy Oudompheng). -* go/printer, godoc: print comments in example code. -* go: implement doc, fmt, fix, list, vet, build, and install. -* gobuilder: goinstall packages after building go tree. -* godoc: <pre> must not occur inside <p> (thanks Olivier Duperray), - added an opensearch description document (thanks Christoph Hack), - text wrapping. -* gofix: add httputil fix (thanks Yasuhiro Matsumoto). -* gotest: use go/build more (thanks Robert Hencke). -* gzip: convert between Latin-1 and Unicode (thanks Vadim Vygonets). -* html/template: define the FuncMap type locally. -* html: a first step at parsing foreign content (MathML, SVG), - more parser improvements (thanks Andrew Balholm). -* http: close connection after printing panic stack trace (thanks Roger Peppe), - fix failing Transport HEAD request with gzip-looking response. -* json: treat renamed byte slices the same as []byte. -* ld: first pass at linker support for NetBSD binaries (thanks Christopher Nielsen), - fix memory leaks (thanks Scott Lawrence), - increase default stack size on Windows for cgo. -* math: delete non-Sqrt-based Hypot, - implement, document, and fix special cases (thanks Charles L. Dorian), -* misc/benchcmp: don't require "Benchmark" at beginning of line. -* misc/osx: rename profile.go to profile_go (thanks Scott Lawrence). -* net/http: fix trivial example server (thanks Olivier Duperray), - net/http: make test remove temporary file and directory. -* net/smtp: add CRAM-MD5 authentication (thanks Vadim Vygonets). -* reflect: fix Slice cap (thanks Gustavo Niemeyer). -* regexp: performance improvements; avoid allocation of input interface. -* runtime: bump gc 'extra bytes' check (thanks Christopher Wedgwood), - madvise and SysUnused for Linux (thanks Sébastien Paolacci), - make gc_test test extra allocated space, not total space, - support for NetBSD (thanks Christopher Nielsen). -* spec: adjust complex constant example (thanks Robert Hencke), - values of underlying type uintptr can be converted to unsafe.Pointer, - var x = 'a' defaults to type rune. -* strconv: include package and function name in error strings, - make QuoteRune etc. take a rune argument, - some performance improvements. -* syscall: add constants for flock() system call under Linux, - regenerate z-files for darwin, freebsd (thanks Mikio Hara), - regenerate z-files for openbsd, - return error, not uintptr, when function returns error (thanks Alex Brainman). -* test/bench: move to test/bench/shootout. -* test/garbage: move to test/bench/garbage. -* test: make array smaller in nilptr test. -* time: allow sleep tests to run for 200% too long, - fix Time.Add (thanks Hector Chu), - fix daysIn for December (thanks Peter Mundy), - gob marshaler for Time (thanks Robert Hencke), - use Duration for AfterFunc. -* various: a grab-bag of time.Duration cleanups. -- -
-This snapshot includes a language change and changes to the strconv and go/doc -packages. The package changes require changes to client code. -The language change is backwards-compatible. - -Type elision in arrays, slices, or maps of composite literals has been -extended to include pointers to composite literals. Code like this - var t = []*T{&T{}, &T{}} -may now be written as - var t = []*T{{}, {}} -You can use gofmt -s to simplify such code. - -The strconv package has been given a more idiomatic and efficient interface. -Client code can be updated with gofix. See the docs for the details: - http://weekly.golang.org/pkg/strconv/ - -The go/doc package's ToHTML function now takes a []byte argument instead of a -string. - -Other changes: -* crypto/aes: eliminate some bounds checking and truncation (thanks Rémy Oudompheng). -* crypto/x509: if a parent cert has a raw subject, use it. -* encoding/gob: don't send type info for unexported fields. -* exp/ssh: allow for msgUserAuthBanner during authentication (thanks Gustav Paul). -* fmt: benchmark floating point, - only use Stringer or Error for strings. -* gc: changes in export format in preparation of inlining, - disallow map/func equality via interface comparison, - use gofmt spacing when printing map type. -* go/doc: exclude lines ending in ':' from possible headings. -* gobuilder: -commit mode for packages, - cripple -package mode temporarily, - use new dashboard protocol. -* godoc: improved output of examples in html (thanks Volker Dobler). -* gofmt: handle &T in composite literal simplify. -* goinstall: honour -install=false flag when -make=true. -* hash: rewrite comment on Hash.Sum method. -* html: more parser improvements (thanks Andrew Balholm). -* image: avoid func comparison during ColorModel comparison. -* math: add special-cases comments to Sinh and Tanh (thanks Charles L. Dorian). -* misc/dashboard: further implementation work. -* net, syscall: remove BindToDevice from UDPConn, IPConn (thanks Mikio Hara). -* net/mail: correctly compare parsed times in the test. -* os/exec: make LookPath always search CWD under Windows (thanks Benny Siegert). -* runtime: prep for type-specific algorithms. -* strconv: 34% to 63% faster conversions. -- -
-This weekly snapshot includes changes to the hash package and a gofix for the -time and os.FileInfo changes in the last snapshot. - -The hash.Hash's Sum method has been given a []byte argument, -permitting the user to append the hash to an existing byte slice. -Existing code that uses Sum can pass nil as the argument. -Gofix will make this change automatically. - -Other changes: -* crypto/tls: cleanup certificate load on windows (thanks Alex Brainman). -* exp/ssh: add Std{in,out,err}Pipe methods to Session (thanks Dave Cheney). -* dashboard: don't choke on weird builder names. -* exp/ssh: export type signal, now Signal (thanks Gustav Paul). -* os: add ModeType constant to mask file type bits (thanks Gustavo Niemeyer). -* text/template: replace Add with AddParseTree. -* go/doc: detect headings and format them in html (thanks Volker Dobler). -- -
-This weekly snapshot includes changes to the time, os, and text/template -packages. The changes to the time and os packages are significant and related. -Code that uses package time, package text/template, or package os's FileInfo -type will require changes. - -In package time, there is now one type - time.Time - to represent times. -Note that time.Time should be used as a value, in contrast to old code -which typically used a *time.Time, a pointer to a large struct. (Drop the *.) -Any function that previously accepted a *time.Time, an int64 -number of seconds since 1970, or an int64 number of nanoseconds -since 1970 should now accept a time.Time. Especially as a replacement -for the int64s, the type is good documentation about the meaning of -its value. - -Whether you were previously calling time.Seconds, time.Nanoseconds, -time.LocalTime, or time.UTC, the replacement is the new function -time.Now. - -If you previously wrote code like: - - t0 := time.Nanoseconds() - myFunction() - t1 := time.Nanoseconds() - delta := t1 - t0 - fmt.Printf("That took %.2f seconds\n", float64(t1-t0)/1e9) - -you can now write: - - t0 := time.Now() - myFunction() - t1 := time.Now() - delta := t1.Sub(t0) - fmt.Printf("That took %s\n", delta) - -In this snippet, the variable delta is of the new type time.Duration, the -replacement for the many int64 parameters that were nanosecond -counts (but not since 1970). - -Gofix can do the above conversions and some others, but it does not -rewrite explicit int64 types as time.Time. It is very likely that you will -need to edit your program to change these types after running gofix. -As always, be sure to read the changes that gofix makes using your -version control system's diff feature. - -See http://weekly.golang.org/pkg/time/ for details. - -In package os, the FileInfo struct is replaced by a FileInfo interface, -admitting implementations by code beyond the operating system. -Code that refers to *os.FileInfo (a pointer to the old struct) should -instead refer to os.FileInfo (the new interface). -The interface has just a few methods: - - type FileInfo interface { - Name() string // base name of the file - Size() int64 // length in bytes - Mode() FileMode // file mode bits - ModTime() time.Time // modification time - IsDir() bool // abbreviation for Mode().IsDir() - } - -If you need access to the underlying stat_t provided by the operating -system kernel, you can access it by assuming that the FileInfo you are -holding is actually an *os.FileStat, and that it's Sys field is actually a -*syscall.Stat_t, as in: - - dev := fi.(*os.FileStat).Sys.(*syscall.Stat_t).Dev - -Of course, this is not necessarily portable across different operating -systems. - -Gofix will take care of rewriting *os.FileInfo to os.FileInfo for you, -and it will also rewrite expressions like fi.Name into calls like fi.Name(). - -See http://weekly.golang.org/pkg/os/#FileInfo for details. - -The template package has been changed to export a new, simpler API. -The Set type is gone. Instead, templates are automatically associated by -being parsed together; nested definitions implicitly create associations. -Only associated templates can invoke one another. -This approach dramatically reduces the breadth of the construction API. -The html/template package has been updated also. -There's a gofix for the simplest and most common uses of the old API. -Code that doesn't mention the Set type is likely to work after running gofix; -code that uses Set will need to be updated by hand. -The template definition language itself is unchanged. - -See http://weekly.golang.org/pkg/text/template/ for details. - - -Other changes: -* cgo: add support for callbacks from dynamic libraries. -* codereview: gofmt check for non-src/ files (thanks David Crawshaw). -* crypto/openpgp/packet: fix private key checksum. -* crypto/tls: add openbsd root certificate location, - don't rely on map iteration order. -* crypto/x509, crypto/tls: support PKCS#8 private keys. -* dashboard: start of reimplementation in Go for App Engine. -* encoding/xml: fix copy bug. -* exp/gui: move exp/gui and exp/gui/x11 to http://code.google.com/p/x-go-binding -* exp/ssh: various improvements (thanks Dave Cheney and Gustav Paul). -* filepath/path: fix Rel buffer sizing (thanks Gustavo Niemeyer). -* gc: fix Nconv bug (thanks Rémy Oudompheng) and other fixes. -* go/printer, gofmt: performance improvements. -* gofix: test and fix missorted renames. -* goinstall: add -fix flag to run gofix on packages on build failure, - better error reporting, - don't hit network unless a checkout or update is required, - support Google Code sub-repositories. -* html: parser improvements (thanks Andrew Balholm). -* http: fix sniffing bug causing short writes. -* json: speed up encoding, caching reflect calls. -* ld: align ELF data sections. -* math/big: fix destination leak into result value (thanks Roger Peppe), - use recursive subdivision for significant speedup. -* math: faster Cbrt and Sincos (thanks Charles L. Dorian). -* misc/osx: scripts to make OS X package and disk image (thanks Scott Lawrence). -* os: fail if Open("") is called on windows (thanks Alex Brainman). -* runtime: make sure stack is 16-byte aligned on syscall (thanks Alex Brainman). -* spec, gc: allow direct conversion between string and named []byte, []rune. -* sql: add Tx.Stmt to use an existing prepared stmt in a transaction, - more driver docs & tests; no functional changes. -* strings: add ContainsAny and ContainsRune (thanks Scott Lawrence). -* syscall: add SUSv3 RLIMIT/RUSAGE constants (thanks Sébastien Paolacci), - fix openbsd sysctl hostname/domainname workaround, - implement Syscall15 (thanks Alex Brainman). -* time: fix Timer stop. -- -
-This snapshot includes some language changes. - -Map and function value comparisons are now disallowed (except for comparison -with nil) as per the Go 1 plan. Function equality was problematic in some -contexts and map equality compares pointers, not the maps' content. - -As an experiment, structs are now allowed to be copied even if they contain -unexported fields. This gives packages the ability to return opaque values in -their APIs. - -Other changes: -* 6a, 8a: allow $(-1) for consistency with $1, $(1), $-1. -* 6l: code generation fixes (thanks Michał Derkacz). -* build: fix check for selinux allow_execstack on Fedora (thanks Bobby Powers). -* builtin: document delete. -* cgo: don't panic on undeclared enums/structs (thanks Rémy Oudompheng), - fix g0 stack guard. -* crypto/tls: fix handshake message test. -* crypto: update incorrect references to Cipher interface; should be Block. -* doc: clean ups, additions, and fixes to several documents. -* doc/install: add openbsd (thanks Joel Sing!). -* doc: link to Chinese translation of A Tour of Go. -* encoding/json: add marshal/unmarshal benchmark, - decode [] as empty slice, not nil slice, - make BenchmarkSkipValue more consistent. -* env.bash: check for presence of make/gmake (thanks Scott Lawrence). -* exp/sql: NumInput() allow -1 to ignore checking (thanks Yasuhiro Matsumoto), - add DB.Close, fix bugs, remove Execer on Driver (only Conn), - document that for drivers, io.EOF means no more rows, - add client side support for publickey auth (thanks Dave Cheney), - add direct-tcpip client support (thanks Dave Cheney), - change test listen address, also exit test if fails, - other fixes and improvements (thanks Dave Cheney). -* exp/terminal: rename shell to terminal and add SetSize. -* fcgi: fix server capability discovery. -* fmt: distinguish empty vs nil slice/map in %#v. -* gc: better error, type checks, and many fixes, - remove m[k] = x, false syntax (use delete(m, k) instead), - support for building with Plan 9 yacc (thanks Anthony Martin). -* go/printer: make //line formatting idempotent. -* godefs: delete, replaced by cgo -godefs. -* godoc: document -templates flag, fix remote search, - provide mode for flat (non-indented) directory listings. -* gofmt: leave nil nodes of the AST unchanged (thanks Rémy Oudompheng). -* html/template: indirect top-level values before printing. -* html: more parser improvements (thanks Andrew Balholm). -* http: fix serving from CWD with http.ServeFile, - make Dir("") equivalent to Dir("."). -* ld: fix .bss for ldpe (thanks Wei Guangjing). -* math/big: replace nat{} -> nat(nil). -* math: faster Lgamma (thanks Charles L. Dorian). -* mime: implement TypeByExtension for windows. -* misc/bbedit: error and rune support (thanks Anthony Starks). -* misc/benchcmp: benchmark comparison script. -* misc/emacs: add delete builtin (thanks Bobby Powers). -* misc/kate: add error and rune (thanks Evan Shaw). -* misc/notepadplus: error and rune support (thanks Anthony Starks). -* misc/windows: Windows installer in MSI format (thanks Joe Poirier). -* net, io/ioutil: remove use of os.Time (thanks Anthony Martin). -* net/http: fix EOF handling on response body (thanks Gustavo Niemeyer), - fix sniffing when using ReadFrom, - use t.Errorf from alternate goroutine in test. -* os: remove undocumented Envs (use os.Environ instead). -* reflect: empty slice/map is not DeepEqual to nil, - make Value an opaque struct. -* runtime, syscall: convert from godefs to cgo. -* runtime: add nanotime for Plan 9 (thanks Anthony Martin), - add timer support, use for package time, - avoid allocation for make([]T, 0). -* strconv: add Ftoa benchmarks, make Ftoa faster. -* syscall: delete syscall.Sleep, take over env implementation, use error. -* testing: add file:line stamps to messages, print results to standard output. -* text/template: refactor set parsing. -* time: add ISOWeek method to Time (thanks Volker Dobler). -* various: avoid func compare, reduce overuse of os.EINVAL + others. -- -
-This weekly snapshot renames various Go packages as described in the Go 1 plan. -Import statements in client code can be updated automatically with gofix. - -The changes are: - asn1 -> encoding/asn1 - big -> math/big - cmath -> math/cmplx - csv -> encoding/csv - exec -> os/exec - exp/template/html -> html/template - gob -> encoding/gob - http -> net/http - http/cgi -> net/http/cgi - http/fcgi -> net/http/fcgi - http/httptest -> net/http/httptest - http/pprof -> net/http/pprof - json -> encoding/json - mail -> net/mail - rpc -> net/rpc - rpc/jsonrpc -> net/rpc/jsonrpc - scanner -> text/scanner - smtp -> net/smtp - syslog -> log/syslog - tabwriter -> text/tabwriter - template -> text/template - template/parse -> text/template/parse - rand -> math/rand - url -> net/url - utf16 -> unicode/utf16 - utf8 -> unicode/utf8 - xml -> encoding/xml -- -
-This weekly snapshot includes some package changes. - -In preparation for the Go 1 package reorganziation the sources for various -packages have been moved, but the import paths remain unchanged. This -inconsistency breaks goinstall at this snapshot. If you use goinstall, please -stay synced to the previous weekly snapshot until the next one is tagged. - -The Error methods in the html, bzip2, and sql packages that return error values -have been renamed to Err. - -Some non-core parts of the http package have been moved to net/http/httputil. -The Dump* and NewChunked* functions and ClientConn, ServerConn, and -ReverseProxy types have been moved from http to httputil. - -The API for html/template is now a direct copy of the template API, instead of -exposing a single Escape function. For HTML templates, use the -html/template package as you would the template package. - -Other changes: -* all: rename os.EOF to io.EOF in non-code contexts (thanks Vincent Vanackere), - sort imports with gofix. -* archive/zip: close file opened with OpenReader (thanks Dmitry Chestnykh). -* bufio: return nil line from ReadLine on error, as documented. -* builtin: document basic types and the built-in error type. -* bytes: add Contains function. -* exp/sql: finish implementation of transactions, flesh out types, docs. -* exp/ssh: improved client authentication support (thanks Dave Cheney). -* gc: better error message for range over non-receive channel, - bug fixes and clean-ups, - detect type switch variable not used cases, - fix escaping of package paths in symbol names, - helpful error message on method call on pointer to pointer, - portably read archive headers (thanks Ron Minnich). -* gob: fix bug when registering the same type multiple times. -* gofix: avoid panic on body-less functions in netudpgroup, - make fix order implicit by date. -* gofmt, gofix: sort imports. -* goinstall: support launchpad.net/~user branches (thanks Jani Monoses). -* gopack: do not look for Go metadata in non-Go objects. -* gotest: don't run examples that have no expected output. -* html: the parser bug fixing campaign continues (thanks Andrew Balholm). -* http: fix whitespace handling in sniffer, - only recognize application/x-www-form-urlencoded in ParseForm, - support Trailers in ReadRequest. -* lib9: add ctime. -* math: faster Gamma (thanks Charles L. Dorian), - improved accuracy for Tan (thanks Charles L. Dorian), - improved high-angle test for Cos, Sin and Tan (thanks Charles L. Dorian). -* net: implement LookupTXT for windows (thanks Alex Brainman). -* os,text,unicode: renamings. -* runtime/cgo: fix data declaration to be extern. -* runtime: add timespec definition for freebsd, - add windows callback tests (thanks Alex Brainman), - fix prototype for openbsd thrsleep, - fix set and not used, - unify mutex code across OSes, - windows_386 sighandler to use correct g (thanks Alex Brainman). -* template: format error with pointer receiver, - make redefinition of a template in a set more consistent. -* test: clear execute bit from source file (thanks Mikio Hara), - make closedchan.go exit with failure if something fails. -* time: faster Nanoseconds call. -* websocket: return an error HTTP response for bad websocket request. -* xml: allow parsing of <_> </_>. (thanks David Crawshaw). -- -
-This snapshot introduces the built-in error type, defined as - - type error interface { - Error() string - } - -The error type replaces os.Error. Notice that the method name has changed from -String to Error. Package fmt's Print formats both Stringers and errors: -in general there is no need to implement both String and Error methods. - -Gofix can update most code. If you have split your package across many files, -it may help to use the -force=error command-line option, which forces gofix to -apply the error fix even if it is not obvious that a particular file needs it. -As always, it is a good idea to read and test the changes that gofix made -before committing them to your version control system. -- -
-* 6l: remove mention of -e flag - it does nothing. -* cc: change cas to newcase (thanks Ron Minnich). -* crypto/openpgp/error: use Error in names of error impl types. -* crypto/rsa: change public exponent from 3 to 65537. -* crypto/tls: add Error method to alert. -* doc: add link to A Tour of Go in Japanese, - add 'all' make rule to build all docs, - refer to tour.golang.org instead of go-tour.appspot.com. -* exp/norm: fixed bug that crept in with moving to the new regexp. -* exp/ssh: fix length header leaking into channel data (thanks Dave Cheney). -* fmt: handle os.Error values explicity (as distinct from Stringer). -* gc: clean up printing, - fix [568]g -V crash (thanks Mikio Hara), - test + fix escape analysis bug. -* go/build: avoid os.Error in tests. -* go/doc: remove os.NewError anti-heuristic. -* go/parser: test and fix := scoping bug. -* gob: split uses of gobError, remove unnecessary embedding. -* gofix: test import insertion, deletion. -* goinstall: intelligent vcs selection for common sites (thanks Julian Phillips). -* gopack: change archive file name length back to 16. -* html: fix print argument in test, - more parser improvements (thanks Andrew Balholm). -* json: properly handle nil slices (thanks Alexander Reece). -* math: improved accuracy for Sin and Cos (thanks Charles L. Dorian). -* misc/emacs: fix restoration of windows after gofmt (thanks Jan Newmarch). -* misc/vim: add rune keyword (thanks Jongmin Kim). -* misc/windows: can be used for amd64 (thanks Alex Brainman). -* net: document why we do not use SO_REUSEADDR on windows (thanks Alex Brainman). -* os: do not interpret 0-length read as EOF. -* pkg: remove .String() from some print arguments. -* rpc: avoid infinite loop on input error. -* runtime/pprof: document OS X being broken. -* runtime: lock the main goroutine to the main OS thread during init. -* spec: define that initialization is sequential. -* strconv: use better errors than os.EINVAL, os.ERANGE. -* syscall: fix Await msg on Plan 9 (thanks Andrey Mirtchovski). -* template: do not use error as stringer, - fix error checking on execute without parse (thanks Scott Lawrence). -* test/alias.go: additional tests. -* test: error-related fixes. -* textproto: prevent long lines in HTTP headers from causing HTTP 400 responses. -* time: add RFC1123 with numeric timezone format (thanks Scott Lawrence). -- -
-This snapshot introduces the rune type, an alias for int that -should be used for Unicode code points. - -A future release of Go (after Go 1) will change rune to be an -alias for int32 instead of int. Using rune consistently is the way -to make your code build both before and after this change. - -To test your code for rune safety, you can rebuild the Go tree with - - GOEXPERIMENT=rune32 ./all.bash - -which builds a compiler in which rune is an alias for int32 instead of int. - -Also, run govet on your code to identify methods that might need to have their -signatures updated. -- -
-* big: make SetString return nil if an error occurs, - new Rat.Inv method, - usable zero Rat values without need for explicit initialization. -* codereview: show LGTMs in hg p. -* crypto/x509: fix names in certificate generation. -* exp/ssh: add experimental ssh client, - introduce Session to replace Cmd for interactive commands, - server cleanups (thanks Dave Cheney). -* exp/types: fix crash in parseBasicType on unknown type. -* fmt: don't panic formatting nil interfaces (thanks Gustavo Niemeyer). -* go/ast, go/token: actually run tests; fix go/ast test. -* gotest: explicit -help flag, use $GCFLAGS like make does. -* govet: check canonical dynamic method signatures. -* html: improved parsing (thanks Andrew Balholm), - parse <select> tags, parse and render comment nodes, - remove the Tokenizer.ReturnComments option. -* http: Transport: with TLS InsecureSkipVerify, skip hostname check. -* misc/vim: add highlighting for delete (thanks Dave Cheney). -* net: do not set SO_REUSEADDR for windows (thanks Alex Brainman). -* os/inotify: move to exp/inotify (thanks Mikio Hara). -* runtime: include bootstrap m in mcpu accounting (thanks Hector Chu). -* syscall: use uintptr for Mount flags. -- -
-This weekly snapshot includes some language and package changes that may -require code changes. Please read these notes carefully, as there are many -changes and your code will likely be affected. - -The syntax for map deletion has been changed. Code that looks like: - m[x] = 0, false -should be written as: - delete(m, x) -The compiler still accepts m[x] = 0, false for now; even so, you can use gofix -to rewrite such assignments into delete(m, x). - -The Go compiler will reject a return statement without arguments when any of -the result variables has been shadowed. Code rejected as a result of this -change is likely to be buggy. - -Receive-only channels (<-chan T) cannot be closed. -The compiler will diagnose such attempts. - -The first element of a map iteration is chosen at random. Code that depends on -iteration order will need to be updated. - -Goroutines may be run during program initialization. - -A string may be appended to a byte slice. This code is now legal: - var b []byte - var s string - b = append(b, s...) - -The gotry command and its associated try package have been deleted. -It was a fun experiment that - in the end - didn't carry its weight. - -The gotype tool has been moved to exp/gotype and its associated go/types -package has been moved to exp/types. The deprecated go/typechecker package has -been deleted. - -The enbflint tool has been moved to pkg/exp/ebnflint and its associated ebnf -package has been moved to pkg/exp/ebnf. - -The netchan package has been moved to old/netchan. - -The http/spdy package has been moved to exp/spdy. - -The exp/datafmt package has been deleted. - -The container/vector package has been deleted. Slices are better: - http://code.google.com/p/go-wiki/wiki/SliceTricks - -Other changes: -* 5l/6l/8l: correct ELFRESERVE diagnostic (thanks Anthony Martin). -* 6l/8l: support OS X code signing (thanks Mikkel Krautz). -* asn1: accept UTF8 strings as ASN.1 ANY values. -* big: handle aliasing correctly for Rat.SetFrac. -* build: add missing nuke target (thanks Anthony Martin), - catch future accidental dependencies to exp or old packages, - more robustly detect gold 2.20 (thanks Christopher Wedgwood), - pass $GCFLAGS to compiler, - stop on failed deps.bash. -* crypto/tls: add 3DES ciphersuites, - add server side SNI support, - fetch root CA from Windows store (thanks Mikkel Krautz), - fetch root certificates using Mac OS API (thanks Mikkel Krautz), - fix broken looping code in windows root CA fetcher (thanks Mikkel Krautz), - more Unix root certificate locations. -* crypto/x509: add code for dealing with PKIX public keys, - keep the raw Subject and Issuer. -* csv: fix overly aggressive TrimLeadingSpace. -* exp/ssh: general cleanups for client support (thanks Dave Cheney). -* exp/template/html: fix bug in cssEscaper. -* exp/terminal: split terminal handling from exp/ssh. -* exp/winfsnotify: filesystem watcher for Windows (thanks Hector Chu). -* fmt: fix test relying on map iteration order. -* gc: changes to export format in preparation for inlining, - pass FlagNoPointers to runtime.new, - preserve uint8 and byte distinction in errors and import data, - stricter multiple assignment + test, - treat uintptr as potentially containing a pointer. -* go/scanner: remove AllowIllegalChars mode. -* go/token: document deserialization property. -* gob: avoid one copy for every message written. -* godefs: add enum/const testdata (thanks Dave Cheney). -* godoc: generate package toc in template, not in JavaScript, - show "unexported" declarations when executing "godoc builtin", - show correct source name with -path. -* gofix: make fix order explicit, add mapdelete. -* gofmt: fix //line handling, - disallow rewrites for incomplete programs. -* gotest: avoid conflicts with the name of the tested package (thanks Esko Luontola), - test example code. -* goyacc: clean up after units (thanks Anthony Martin), - make more gofmt-compliant. -* html: add a Render function, various bug fixes and improvements, - parser improvements (thanks Andrew Balholm). -* http: DoS protection: cap non-Handler Request.Body reads, - RoundTrippers shouldn't mutate Request, - avoid panic caused by nil URL (thanks Anthony Martin), - fix read timeouts and closing, - remove Request.RawURL. -* image/tiff: implement PackBits decoding (thanks Benny Siegert). -* ld: fix "cannot create 8.out.exe" (thanks Jaroslavas Počepko). -* misc/emacs: add a "godoc" command, like M-x man (thanks Evan Martin). -* misc/swig: delete binaries (thanks Anthony Martin). -* misc/windows: automated toolchain packager (thanks Joe Poirier). -* net/windows: implement ip protocol name to number resolver (thanks Alex Brainman). -* net: add File method to IPConn (thanks Mikio Hara), - allow LookupSRV on non-standard DNS names, - fix "unexpected socket family" error from WriteToUDP (thanks Albert Strasheim), - fix socket leak in case of Dial failure (thanks Chris Farmiloe), - remove duplicate error information in Dial (thanks Andrey Mirtchovski), - return error from CloseRead and CloseWrite (thanks Albert Strasheim), - skip ICMP test on Windows too unless uid 0. -* reflect: disallow Interface method on Value obtained via unexported name, - make unsafe use of SliceHeader gc-friendly. -* rpc: don't panic on write error. -* runtime: faster strings, - fix crash if user sets MemProfileRate=0, - fix crash when returning from syscall during gc (thanks Hector Chu), - fix memory leak in parallel garbage collector. -* scanner: invalidate scanner.Position when no token is present. -* spec: define order of multiple assignment. -* syscall/windows: dll function load and calling changes (thanks Alex Brainman). -* syscall: add #ifdefs to fix the manual corrections in ztypes_linux_arm.go (thanks Dave Cheney), - adjust Mount to accommodate stricter FS implementations. -* testing: fix time reported for failing tests. -* utf8: add Valid and ValidString. -* websocket: tweak hybi ReadHandshake to support Firefox (thanks Luca Greco). -* xml: match Marshal's XMLName behavior in Unmarshal (thanks Chris Farmiloe). -- -
-This weekly snapshot includes changes to the io, image, and math packages that -may require changes to client code. - -The io package's Copyn function has been renamed to CopyN. - -The math package's Fabs, Fdim, Fmax, Fmin and Fmod functions -have been renamed to Abs, Dim, Max, Min, and Mod. - -Parts of the image package have been moved to the new image/color package. -The spin-off renames some types. The new names are simply better: - image.Color -> color.Color - image.ColorModel -> color.Model - image.ColorModelFunc -> color.ModelFunc - image.PalettedColorModel -> color.Palette - image.RGBAColor -> color.RGBA - image.RGBAColorModel -> color.RGBAModel - image.RGBA64Color -> color.RGBA64 - image.RGBA64ColorModel -> color.RGBA64Model -(similarly for NRGBAColor, GrayColorModel, etc) -The image.ColorImage type stays in the image package, but is renamed: - image.ColorImage -> image.Uniform -The image.Image implementations (image.RGBA, image.RGBA64, image.NRGBA, -image.Alpha, etc) do not change their name, and gain a nice symmetry: -an image.RGBA is an image of color.RGBA, etc. -The image.Black, image.Opaque uniform images remain unchanged (although their -type is renamed from image.ColorImage to image.Uniform). -The corresponding color types (color.Black, color.Opaque, etc) are new. -Nothing in the image/ycbcr is renamed yet. The ycbcr.YCbCrColor and -ycbcr.YCbCrImage types will eventually migrate to color.YCbCr and image.YCbCr, -at a later date. - -* 5g/6g/8g: fix loop finding bug, fix -f(), registerize variables again. -* 5l/6l/8l: add a DT_DEBUG dynamic tag to a dynamic ELF binary. -* archive/zip: read and write unix file modes (thanks Gustavo Niemeyer). -* build: clear execute bit from source files (thanks Mikio Hara). -* bytes: add EqualFold. -* cgo: allow Windows path characters in flag directives (thanks Joe Poirier), - support for mingw-w64 4.5.1 and newer (thanks Wei Guangjing). -* codereview: extra repo sanity check, - fix for Mercurial 1.9.2, - fix hg change in Windows console (thanks Yasuhiro Matsumoto). -* crypto/elliptic: use %x consistently in error print. -* doc/spec: remove notes about gccgo limitations, now fixed. -* doc: add 'Debugging Go code with GDB' tutorial, - fix memory model read visibility bug. -* encoding/binary: PutX functions require buffer of sufficient size, - added benchmarks, support for varint encoding. -* exec: add Command.ExtraFiles. -* exp/sql{,/driver}: new database packages. -* exp/ssh: move common code to common.go (thanks Dave Cheney). -* exp/template/html: work continues. -* fmt: replace channel cache with slice. -* gc: limit helper threads based on ncpu. -* go/doc, godoc, gotest: support for reading example documentation. -* go: documentation and skeleton implementation of new command. -* gob: protect against invalid message length, - allow sequential decoders on the same input stream. -* hgpatch: do not use hg exit status (thanks Yasuhiro Matsumoto). -* http: add Location method to Response, - don't send a 400 Bad Request after a client shutdown. -* index/suffixarray: 4.5x faster index serialization (to memory). -* io/ioutil: add a comment on why devNull is a ReaderFrom. -* json: use strings.EqualFold instead of strings.ToLower. -* misc/emacs: fix indent bug. -* net: add shutdown: TCPConn.CloseWrite and CloseRead. -* net: use AF_UNSPEC instead of individual address family (thanks Mikio Hara). -* path/filepath: added Rel as the complement of Abs (thanks Gustavo Niemeyer). -* pkg/syscall: add Mkfifo for linux platforms. -* regexp: move to old/regexp, replace with exp/regexp, speedups. -* runtime/gdb: fix pretty printing of channels, - gracefully handle not being able to find types. -* runtime: check for nil value pointer in select syncsend case, - faster finalizers, - fix malloc sampling bug, - fix map memory leak, - fix spurious deadlock reporting, - fix usleep on linux/386 and re-enable parallel gc (thanks Hector Chu), - parallelize garbage collector mark + sweep. -* strconv: faster Unquote in common case. -* strings: add EqualFold, Replacer, NewReplacer. -* suffixarray: add benchmarks for construction (thanks Eric Eisner). -* syscall: add GetsockoptByte, SetsockoptByte for openbsd (thanks Mikio Hara), - add IPv4 ancillary data for linux (thanks Mikio Hara), - mark stdin, stdout, stderr non-inheritable by child processes (thanks Alex Brainman), - mksyscall_windows.pl creates non-syscall packages (thanks Jaroslavas Počepko), - update multicast socket options (thanks Mikio Hara). -* testing: support for running tests in parallel (thanks Miki Tebeka). -* time: make month/day name comparisons case insenstive. -* unicode: fix make tables. -* vim: Send GoFmt errors to a location list (thanks Paul Sbarra). -* websocket: add hybi-13 support, add mutex to make websocket full-duplex. -- -
-This weekly contains several improvements, bug fixes, and new packages. - -* archive/tar: document Header fields and Type flags (thanks Mike Rosset). -* bytes: fix Replace so it actually copies (thanks Gustavo Niemeyer). -* cgo: use GOARCH from the environment (thanks Jaroslavas Počepko). -* codereview: save CL messages in $(hg root)/last-change. -* crypto/bcrypt: new package (thanks Jeff Hodges). -* crypto/blowfish: exposing the blowfish key schedule (thanks Jeff Hodges). -* doc: link to golang-france. -* doc: when configuring gold for gccgo, use --enable-gold=default. -* exp/norm: changed trie to produce smaller tables. -* exp/ssh: new package, - refactor halfConnection to transport (thanks Dave Cheney). -* exp/template/html: more fixes and improvements. -* filepath: fix Glob to return no error on nonmatching patterns. -* gc: disallow invalid map keys, - handle complex CONVNOP. -* gob: allocation fixes. -* godoc: simplify internal FileSystem interface. -* http/cgi: clean up environment (thanks Yasuhiro Matsumoto). -* http: always include Content-Length header, even for 0 (thanks Dave Grijalva), - check explicit wrong Request.ContentLength values, - fix TLS handshake blocking server accept loop, - prevent DumpRequest from adding implicit headers. -* httptest: add NewUnstartedServer. -* json: clearer Unmarshal doc, - skip nil in UnmarshalJSON and (for symmetry) MarshalJSON. -* net: use /etc/hosts first when looking up IP addresses (thanks Andrey Mirtchovski). -* reflect: add comment about the doubled semantics of Value.String. -* runtime: implement pprof support for windows (thanks Hector Chu), - increase stack system space on windows/amd64 (thanks Hector Chu). -* suffixarray: generate less garbage during construction (thanks Eric Eisner), - improved serialization code using gob instead of encoding/binary. -* sync/atomic: replace MFENCE with LOCK XADD. -- -
-This weekly snapshot includes changes to the image, path/filepath, and time -packages. Code that uses these packages may need to be updated. - -The image package's NewX functions (NewRGBA, NewNRGBA, etc) have been changed -to take a Rectangle argument instead of a width and height. -Gofix can make these changes automatically. - -The path/filepath package's Walk function has been changed to take a WalkFunc -function value instead of a Visitor interface value. WalkFunc is like the -Visitor's VisitDir and VisitFile methods except it handles both files and -directories: - func(path string, info *os.FileInfo, err os.Error) os.Error -To skip walking a directory (like returning false from VisitDir) the WalkFunc -must return SkipDir. - -The time package's Time struct's Weekday field has been changed to a method. -The value is calculated on demand, avoiding the need to re-parse -programmatically-constructed Time values to find the correct weekday. - -There are no gofixes for the filepath or time API changes, but instances of the -old APIs will be caught by the compiler. The Weekday one is easy to update by -hand. The Walk one may take more consideration, but will have fewer instances -to fix. - -* build: add build comments to core packages. -* codereview: Mercurial 1.9 fix for hg diff @nnn. -* crypto/tls: handle non-TLS more robustly, - support SSLv3. -* debug/elf: permit another case of SHT_NOBITS section overlap in test. -* exm/template/html: more work on this auto-escaping HTML template package. -* exp/norm: added regression test tool for the standard Unicode test set. -* exp/regexp/syntax: fix invalid input parser crash, - import all RE2 parse tests + fix bugs. -* exp/regexp: add MustCompilePOSIX, CompilePOSIX, leftmost-longest matching. -* flag: make zero FlagSet useful. -* gc: clean up if grammar. -* go/build: handle cgo, // +build comments. -* go/printer: use panic/defer instead of goroutine for handling errors. -* go/token: support to serialize file sets. -* godoc, suffixarray: switch to exp/regexp. -* godoc: show packages matching a query at the top, - support for complete index serialization, - use go/build to find files in a package. -* gofmt: accept program fragments on standard input, add else test. -* http/cgi: add openbsd environment configuration. -* http: document that Response.Body is non-nil. -* image/png: don't use a goroutine to decode, to permit decode during init. -* json: if a field's tag is "-", ignore the field for encoding and decoding. -* ld: grow dwarf includestack on demand. -* net, syscall: implement SetsockoptIPMReq(), and - move to winsock v2.2 for multicast support (thanks Paul Lalonde). -* net: add a LookupTXT function. -* os: os.RemoveAll to check for wboth error codes on Windows (thanks Jaroslavas Počepko). -* path/filepath: fix Visitor doc (thanks Gustavo Niemeyer), - make UNC file names work (thanks Yasuhiro Matsumoto). -* runtime: optimizations to channels on Windows (thanks Hector Chu), - syscall to return both AX and DX for windows/386 (thanks Alex Brainman). -* sync/atomic: add 64-bit Load and Store. -* syscall: add route flags for linux (thanks Mikio Hara). -* test: add test for inheriting private method from anonymous field. -* websocket: fix infinite recursion in Addr.String() (thanks Tarmigan Casebolt), - rename websocket.WebSocketAddr to *websocket.Addr. -- -
-This weekly snapshot consists of improvements and bug fixes, including fixes -for issues introduced by escape analysis changes in the gc compiler. - -* build: clear execute bit from Go files (thanks Mike Rosset), - error out if problem with sudo.bash /usr/local/bin (thanks Mike Rosset). -* exp/norm: add Reader and Writer, - performance improvements of quickSpan. -* exp/regexp: bug fixes and RE2 tests. -* exp/template/html: string replacement refactoring, - tweaks to js{,_test}.go. -* gc: add -p flag to catch import cycles earlier, - fix label recursion bugs, - fix zero-length struct eval, - zero stack-allocated slice backing arrays, -* gc, ld: fix Windows file paths (thanks Hector Chu). -* go/parser: accept corner cases of signature syntax. -* gobuilder: ignore _test.go files when looking for docs, more logging. -* godoc: minor tweaks for App Engine use. -* gofix: do not convert url in field names (thanks Gustavo Niemeyer). -* gofmt: indent multi-line signatures. -* gopprof: regexp fixes (thanks Hector Chu). -* image/png: check zlib checksum during Decode. -* libmach: fix incorrect use of memset (thanks Dave Cheney). -* misc/goplay: fix template output. -* net: ParseCIDR returns IPNet instead of IPMask (thanks Mikio Hara), - sync CIDRMask code, doc. -* os: use GetFileAttributesEx to implement Stat on windows (thanks Alex Brainman). -* runtime: fix openbsd 386 raisesigpipe, - implement exception handling on windows/amd64 (thanks Hector Chu), - test for concurrent channel consumers (thanks Christopher Wedgwood). -* sort: use heapsort to bail out quicksort (thanks Ziad Hatahet). -* sync/atomic: add LoadUintptr, add Store functions. -* syscall: update routing message attributes handling (thanks Mikio Hara). -* template: fix deadlock, - indirect or dereference function arguments if necessary, - slightly simplify the test for assignability of arguments. -* url: handle ; in ParseQuery. -* websocket: fix incorrect prints found by govet (thanks Robert Hencke). -- -
-This weekly contains performance improvements and bug fixes. - -The gc compiler now does escape analysis, which improves program performance -by placing variables on the call stack instead of the heap when it is safe to -do so. - -The container/vector package is deprecated and will be removed at some point -in the future. - -Other changes: -* archive/tar: support symlinks. (thanks Mike Rosset) -* big: fix nat.scan bug. (thanks Evan Shaw) -* bufio: handle a "\r\n" that straddles the buffer. - add openbsd. - avoid redundant bss declarations. - fix unused parameters. - fix windows/amd64 build with newest mingw-w64. (thanks Hector Chu) -* bytes: clarify that NewBuffer is not for beginners. -* cgo: explain how to free something. - fix GoBytes. (thanks Gustavo Niemeyer) - fixes callback for windows amd64. (thanks Wei Guangjing) - note that CString result must be freed. (thanks Gustavo Niemeyer) -* cov: remove tautological #defines. (thanks Lucio De Re) -* dashboard: yet another utf-8 fix. -* doc/codelab/wiki: fix Makefile. -* doc/progs: fix windows/amd64. (thanks Jaroslavas Počepko) -* doc/tmpltohtml: update to new template package. -* doc: emphasize that environment variables are optional. -* effective_go: convert to use tmpltohtml. -* exp/norm: reduced the size of the byte buffer used by reorderBuffer by half by reusing space when combining. - a few minor fixes to support the implementation of norm. - added implementation for []byte versions of methods. -* exp/template/html: add some tests for ">" attributes. - added handling for URL attributes. - differentiate URL-valued attributes (such as href). - reworked escapeText to recognize attr boundaries. -* exp/wingui: made compatible with windows/amd64. (thanks Jaroslavas Počepko) -* flag: add Parsed, restore Usage. -* gc: add openbsd. - escape analysis. - fix build on Plan 9. (thanks Lucio De Re) - fix div bug. - fix pc/line table. (thanks Julian Phillips) - fix some spurious leaks. - make static initialization more static. - remove JCXZ; add JCXZW, JCXZL, and JCXZQ instructions. (thanks Jaroslavas Počepko) - shuffle #includes. - simplify escape analysis recursion. - tweak and enable escape analysis. -* go/ast cleanup: base File/PackageExports on FilterFile/FilterPackage code. - adjustments to filter function. - fix ast.MergePackageFiles to collect infos about imports. (thanks Sebastien Binet) - generalize ast.FilterFile. -* go/build: add test support & use in gotest. - separate test imports out when scanning. (thanks Gustavo Niemeyer) -* go/parser: fix type switch scoping. - fix type switch scoping. -* gob: explain that Debug isn't useful unless it's compiled in. -* gobuilder: increase log limit. -* godashboard: fix utf-8 in user names. -* godoc: first step towards reducing index size. - add dummy playground.js to silence godoc warning at start-up. - added systematic throttling to indexing goroutine. - fix bug in zip.go. - support for reading/writing (splitted) index files. - use virtual file system when generating package synopses. -* gofix: forgot to rename the URL type. - osopen: fixed=true when changing O_CREAT. (thanks Tarmigan Casebolt) -* goinstall: error out with paths that end with '/'. (thanks Tarmigan Casebolt) - report lack of $GOPATH on errors. (thanks Gustavo Niemeyer) - select the tag that is closest to runtime.Version. -* gotry: add missing $. (thanks Tarmigan Casebolt) -* http: add MaxBytesReader to limit request body size. - add file protocol transport. - adjust test threshold for larger suse buffers. - delete error kludge. - on invalid request, send 400 response. - return 413 instead of 400 when the request body is too large. (thanks Dave Cheney) - support setting Transport's TLS client config. -* image/tiff: add a decode benchmark. (thanks Benny Siegert) - decoder optimization. (thanks Benny Siegert) -* image: add PalettedImage interface, and make image/png recognize it. (thanks Jaroslavas Počepko) -* io: add TeeReader. (thanks Hector Chu) -* json: add struct tag option to wrap literals in strings. - calculate Offset for Indent correctly. (thanks Jeff Hodges) - fix decode bug with struct tag names with ,opts being ignored. -* ld: handle Plan 9 ar format. (thanks Lucio De Re) - remove duplicate bss definitions. -* libmach: support reading symbols from Windows .exe for nm. (thanks Mateusz Czapliński) -* math: fix Pow10 loop. (thanks Volker Dobler) -* mime: ParseMediaType returns os.Error now, not a nil map. - media type formatter. (thanks Pascal S. de Kloe) - text charset defaults. (thanks Pascal S. de Kloe) -* misc/dashboard: remove limit for json package list. -* misc/emacs: refine label detection. -* net: add ParseMAC function. (thanks Paul Borman) - change the internal form of IPMask for IPv4. (thanks Mikio Hara) - disable "tcp" test on openbsd. - fix windows build. (thanks Alex Brainman) - join and leave a IPv6 group address, on a specific interface. (thanks Mikio Hara) - make use of IPv4len, IPv6len. (thanks Mikio Hara) - move internal string manipulation routines to parse.go. (thanks Mikio Hara) -* os: disable Hostname test on OpenBSD. - fix WNOHANG Waitmsg. (thanks Gustavo Niemeyer) -* reflect: add Value.Bytes, Value.SetBytes methods. -* rpc: add benchmark for async rpc calls. -* runtime: add openbsd 386 defs.h. - add runtime support for openbsd 386. - add runtime· prefix to showframe. - ctrlhandler for windows amd64. (thanks Wei Guangjing) - fix stack cleanup on windows/amd64. (thanks Hector Chu) - fix void warnings. - go interface to cdecl calbacks. (thanks Jaroslavas Počepko) - handle string + char literals in goc2c. - make arm work on Ubuntu Natty qemu. - openbsd thread tweaks. - simplify stack traces. - speed up cgo calls. (thanks Alex Brainman) - use cgo runtime functions to call windows syscalls. (thanks Alex Brainman) - windows/amd64 callbacks fixed and syscall fixed to allow using it in callbacks. (thanks Jaroslavas Počepko) -* strconv: put decimal on stack. -* spec: update section on Implementation Differences. -* syscall: SOMAXCONN should be 0x7fffffff at winsock2. (thanks Yasuhiro Matsumoto) - add openbsd 386. - handle RTM_NEWROUTE in ParseNetlinkRouteAttr on Linux. (thanks Albert Strasheim) - handle routing entry in ParseRoutingSockaddr on BSD variants. (thanks Mikio Hara) - openbsd amd64 syscall support. - use the vdso page on linux x86 for faster syscalls instead of int $0x80. (thanks Yuval Pavel Zholkover) -* template/parse: give if, range, and with a common representation. -* template: grammar fix for template documentation. (thanks Bill Neubauer) - range over channel. - remove else and end nodes from public view. -* test: put GOROOT/bin before all others in run. -* time: fix Plan 9 build. (thanks Fazlul Shahriar) - fix zone during windows test. -* type switches: test for pathological case. -* version.bash: update VERSION on -save if already present. (thanks Gustavo Niemeyer) -* websocket: implements new version of WebSocket protocol. (thanks Fumitoshi Ukai) -* windows/386: clean stack after syscall. (thanks Jaroslavas Počepko) -* xml: marshal "parent>child" tags correctly. (thanks Ross Light) -- -
-This weekly contains some package re-shuffling. Users of the http and -template packages may be affected. - -This weekly replaces the template package with exp/template. -The original template package is still available as old/template. -The old/template package is deprecated and will be removed at some point -in the future. The Go tree has been updated to use the new template package. -We encourage users of the old template package to switch to the new one. -Code that uses template or exp/template will need to change -its import lines to "old/template" or "template", respectively. - -The http package's URL parsing and query escaping code (such as ParseURL and -URLEscape) has been moved to the new url package, with several simplifications -to the names. Client code can be updated automatically with gofix. - -* asn1: support unmarshaling structs with int32 members (thanks Dave Cheney). -* build: allow builds without cgo or hg, - support versioning without hg (thanks Gustavo Niemeyer). -* builtin: add documentation for builtins. -* cgo: omit duplicate symbols in writeDefs (thanks Julian Phillips). -* misc: add support for OpenBSD. -* doc/codewalk: new Markov chain codewalk. -* exp/norm: added trie lookup code and associated tests, - generate trie struct in triegen.go for better encapsulation, - implementation of decomposition and composing functionality. -* exp/template/html: new experimental package for auto-escaping HTML templates. -* exp/template: don't panic on range of nil interface, - rename Parse*File and Parse*Files for clarity, - support field syntax on maps (thanks Gustavo Niemeyer), and - many other fixes and changes. -* gc: implement nil chan and nil map support. -* go/parser: range clause and type literal fixes. -* godoc: show all top-level decls for (fake) package builtin. -* goinstall: really report all newly-installed public packages. -* html: parse more malformed tags. -* http: fix ParseMultipartForm after MultipartReader error, - fix side effects in DefaultTransport's RoundTrip method (thanks Dave Grijalva). -* json: fix []unmarshaler case. -* ld: make addaddrplus4 static (thanks Lucio De Re). -* syscall: move multicast address handling to the net package. -* net: Plan 9 support (thanks Fazlul Shahriar), - add SetTimeout to Listener interface (thanks Aleksandar Dezelin), - add multicast stubs for OpenBSD, - return correct local address for an accepted TCP connection (thanks Mikio Hara). -* reflect: panic on Invalid Interface call (thanks Gustavo Niemeyer). -* rpc: implement ServeRequest to synchronously serve a single request, - make Server.Mutex unexported. -* runtime: better checks for syscall.NewCallback parameter (thanks Alex Brainman), - correct SEH installation during callbacks (thanks Alex Brainman), - fix GC bitmap corruption, - fix pseudo-randomness on some selects (thanks Gustavo Niemeyer). -* syscall: make LazyDLL/LazyProc.Mutex unexported. -* test: allow multiple patterns in errchk, - new nil semantics. -* time: take fractional seconds even if not in the format string. -* url: new package. -* utf8: rename some internal constants to remove leading underscores. -* xml: escape string chardata in xml.Marshal. -- -
-This weekly contains performance improvements and bug fixes. - -There are no outward-facing changes, but imports of the old-style -container/vector package have also been removed from the core library (thanks -John Asmuth, Kyle Consalus). - -Other changes: - -* 5g: fix set but not used error (thanks Dave Cheney). -* cmd/ld: Corrected mismatched print formats and variables (thanks Lucio De Re). -* errchk: add -0 flag. -* exp/norm: fix build by adding a test placeholder, - maketables tool for generating tables for normalization. -* exp/template: bug fixes, - ensure that a valid Set is returned even on error (thanks Roger Peppe), - make index on maps return zero when key not present (thanks Roger Peppe), - split the parse tree into a separate package exp/template/parse, - add url query formatting filter. -* faq: lots of small tweaks plus a couple of new discussions, - variant types, unions. -* fmt: call UpdateMemStats in malloc counter. -* go/build: use GOBIN as binary path for GOROOT. -* gob: add UpdateMemStats calls to malloc counter, - avoid a couple of init-time allocations, - don't invoke GobEncoder on zero values. -* gofmt: update test script so 'make test' succeeds. -* html: parse doctype tokens; merge adjacent text nodes. -* http: add more MPEG-4 MIME types to sniffer, and disable MP4 sniffing, - add test to serve content in index.html (thanks Yasuhiro Matsumoto), - configurable and default request header size limit, - correct format flags when printing errors in tests (thanks Alex Brainman), - correct path to serve index.html (thanks Yasuhiro Matsumoto), -* ld: add one empty symbol into pe to make dumpbin works (thanks Wei Guangjing), - fail linking if the top-level package is not main. -* misc/vim: godoc command (thanks Yasuhiro Matsumoto). -* net: add support for openbsd (thanks Joel Sing), - fix /proc/net/igmp,igmp6 reading bug on linux (thanks Mikio Hara), - implement windows LookupMX and LookupAddr (thanks Mikio Hara), - sort SRV records before returning from LookupSRV (thanks Alex Brainman), -* os: add support for openbsd (thanks Joel Sing). -* runtime: add more specialized type algorithms, - correct Note documentation, - faster chan creation on Linux/FreeBSD/Plan9, - openbsd amd64 runtime support (thanks Joel Sing), - remove unnecessary locking (thanks Hector Chu). -* scanner: correct error position for illegal UTF-8 encodings. -* syscall: delay load of dll functions on Windows (thanks Alex Brainman), - move BSD mmap syscall (thanks Joel Sing), - update routing message support for BSD variants (thanks Mikio Hara). -* test/bench: note changes after recent improvements to locking and runtime. -* time: add nanoseconds to the Time structure, - parse and format fractional seconds. -- -
-This weekly contains performance improvements and many bug fixes. - -* 6l: OpenBSD support. -* archive/zip: handle zip files with more than 65535 files, - more efficient reader and bug fix. -* big: refine printf formatting and optimize string conversion. -* build: fixes for mingw-w64 (thanks Wei Guangjing), - miscellaneous fixes. -* cgo: add GoBytes, fix gmp example. -* exp/norm: API for normalization library. -* exp/regexp: implement regexp API using exp/regexp/syntax. -* exp/template: more tweaks and fixes, convert the tree to use exp/template. -* fmt: handle precision 0 format strings in standard way. -* gc: a raft of bug fixes. -* go/parser: report illegal label declarations at ':'. -* gob: send empty but non-nil maps. -* godoc: allow form feed in text files, - app engine configuration and updated documentation. -* goinstall: abort and warn when using any url scheme, not just 'http://', - write to goinstall.log in respective GOPATH. -* html: handle character entities without semicolons (thanks Andrew Balholm), - parse misnested formatting tags according to the HTML5 spec, - sync html/testdata/webkit with upstream WebKit. -* http: content-type sniffing, - make serveFile redirects relative (thanks Andrew Balholm), - other fixes. -* image/tiff: Do not panic when RowsPerStrip is missing (thanks Benny Siegert). -* io/ioutil: improve performance of ioutil.Discard (thanks Mike Solomon). -* ld: detect all import cycles, - ldpe fixes (thanks Wei Guangjing), - remove cseekend and redo pe writing (thanks Alex Brainman), - remove overlap of ELF sections on dynamic binaries (thanks Gustavo Niemeyer). -* net/textproto: avoid 1 copy in ReadLine, ReadContinuedLine. -* net: fix memory corruption in windows *netFD.ReadFrom (thanks Alex Brainman). -* runtime: faster entersyscall/exitsyscall, - fix scheduler races (thanks Hector Chu), - higher goroutine arg limit, clearer error, - parallelism-related performance optimizations and fixes, - replace byte-at-a-time zeroing loop with memclr (thanks Quan Yong Zhai). -* sort: fix Float64Slice sort; NaN smallest value (thanks Florian Uekermann). -* src: removed some uses of container/vector (thanks John Asmuth). -* sync: improve Once fast path. -* unicode: fix case-mapping for roman numerals. -- -
-This weekly snapshot includes a language change and a change to the image -package that may require changes to client code. - -The language change is that an "else" block is now required to have braces -except if the body of the "else" is another "if". Since gofmt always puts those -braces in anyway, programs will not be affected unless they contain "else for", -"else switch", or "else select". Run gofmt to fix any such programs. - -The image package has had significant changes made to the Pix field of struct -types such as image.RGBA and image.NRGBA. The image.Image interface type has -not changed, though, and you should not need to change your code if you don't -explicitly refer to Pix fields. For example, if you decode a number of images -using the image/jpeg package, compose them using image/draw, and then encode -the result using image/png, then your code should still work as before. - -If you do explicitly refer to Pix fields, there are two changes. First, Pix[0] -now refers to the pixel at Bounds().Min instead of the pixel at (0, 0). Second, -the element type of the Pix slice is now uint8 instead of image.FooColor. For -example, for an image.RGBA, the channel values will be packed R, G, B, A, R, G, -B, A, etc. For 16-bits-per-channel color types, the pixel data will be stored -as big-endian uint8s. - -Most Pix field types have changed, and so if your code still compiles after -this change, then you probably don't need to make any further changes (unless -you use an image.Paletted's Pix field). If you do get compiler errors, code -that used to look like this: - - // Get the R, G, B, A values for the pixel at (x, y). - var m *image.RGBA = loadAnImage() - c := m.Pix[y*m.Stride + x] - r, g, b, a := c.R, c.G, c.B, c.A - -should now look like this: - - // Get the R, G, B, A values for the pixel at (x, y). - var m *image.RGBA = loadAnImage() - i := (y-m.Rect.Min.Y)*m.Stride + (x-m.Rect.Min.X)*4 - r := m.Pix[i+0] - g := m.Pix[i+1] - b := m.Pix[i+2] - a := m.Pix[i+3] - -This image package change will not be fixed by gofix: how best to translate -code into something efficient and idiomatic depends on the surrounding context, -and is not easily automatable. Examples of what to do can be found in the -changes to image/draw/draw.go in http://codereview.appspot.com/4675076/ - -Other changes: -* 6l: change default output name to 6.out.exe on windows (thanks Alex Brainman). -* archive/zip: add Writer, - add Mtime_ns function to get modified time in sensible format. -* cc, ld, gc: fixes for Plan 9 build (thanks Lucio De Re). -* cgi: close stdout reader pipe when finished. -* cgo: add missing semicolon in generated struct, - windows amd64 port (thanks Wei Guangjing). -* codereview: fix for Mercurial 1.9. -* dashboard: list "most installed this week" with rolling count. -* debug/elf: read ELF Program headers (thanks Matthew Horsnell). -* debug/pe: fixes ImportedSymbols for Win64 (thanks Wei Guangjing). -* debug/proc: remove unused package. -* doc/talks/io2010: update with gofix and handle the errors. -* exp/eval, exp/ogle: remove packages eval and ogle. -* exp/regexp/syntax: add Prog.NumCap. -* exp/template: API changes, bug fixes, and tweaks. -* flag: make -help nicer. -* fmt: Scan(&int) was mishandling a lone digit. -* gc: fix closure bug, - fix to build with clang (thanks Dave Cheney), - make size of struct{} and [0]byte 0 bytes (thanks Robert Hencke), - some enhancements to printing debug info. -* gif: fix local color map and coordinates. -* go/build: fixes for windows (thanks Alex Brainman), - include processing of .c files for cgo packages (thanks Alex Brainman), - less aggressive failure when GOROOT not found. -* go/printer: changed max. number of newlines from 3 to 2. -* gob: register more slice types (thanks Bobby Powers). -* godoc: support for file systems stored in .zip files. -* goinstall, dashboard: Google Code now supports git (thanks Tarmigan Casebolt). -* hash/crc32: add SSE4.2 support. -* html: update section references in comments to the latest HTML5 spec. -* http: drain the pipe output in TestHandlerPanic to avoid logging deadlock, - fix Content-Type of file extension (thanks Yasuhiro Matsumoto), - implement http.FileSystem for zip files, - let FileServer work when path doesn't begin with a slash, - support for periodic flushing in ReverseProxy. -* image/draw: add benchmarks. -* json: add omitempty struct tag option, - allow using '$' and '-' as the struct field's tag (thanks Mikio Hara), - encode \r and \n in strings as e.g. "\n", not "\u000A" (thanks Evan Martin), - escape < and > in any JSON string for XSS prevention. -* ld: allow seek within write buffer< - add a PT_LOAD PHDR entry for the PHDR (thanks David Anderson). -* net: windows/amd64 port (thanks Wei Guangjing). -* os: plan9: add Process.Signal as a way to send notes (thanks Yuval Pavel Zholkover). -* os: don't permit Process.Signal after a successful Wait. -* path/filepath: fixes for windows paths (thanks Alex Brainman). -* reflect: add Value.NumMethod, - panic if Method index is out of range for a type. -* runtime: faster entersyscall, exitsyscall, - fix panic for make(chan [0]byte), - fix subtle select bug (thanks Hector Chu), - make goc2c build on Plan 9 (thanks Lucio De Re), - make TestSideEffectOrder work twice, - several parallelism-related optimizations and fixes, - stdcall_raw stack 16byte align for Win64 (thanks Wei Guangjing), - string-related optimizations (thanks Quan Yong Zhai), - track running goroutine count. -* strconv: handle [-+]Infinity in atof. -* sync: add fast paths to WaitGroup, - improve RWMutex performance. -* syscall: add Flock on Linux, - parse and encode SCM_RIGHTS and SCM_CREDENTIALS (thanks Albert Strasheim). -- -
-This weekly snapshot includes changes to the strings, http, reflect, json, and -xml packages. Code that uses these packages will need changes. Most of these -changes can be made automatically with gofix. - -The strings package's Split function has itself been split into Split and -SplitN. SplitN is the same as the old Split. The new Split is equivalent to -SplitN with a final argument of -1. - -The http package has a new FileSystem interface that provides access to files. -The FileServer helper now takes a FileSystem argument instead of an explicit -file system root. By implementing your own FileSystem you can use the -FileServer to serve arbitrary data. - -The reflect package supports a new struct tag scheme that enables sharing of -struct tags between multiple packages. -In this scheme, the tags must be of the form: - key:"value" key2:"value2" -reflect.StructField's Tag field now has type StructTag (a string type), which -has method Get(key string) string that returns the associated value. -Clients of json and xml will need to be updated. Code that says - type T struct { - X int "name" - } -should become - type T struct { - X int `json:"name"` // or `xml:"name"` - } -Use govet to identify struct tags that need to be changed to use the new syntax. - -Other changes: -* 5l, 6l, 8l: drop use of ed during build. -* asn1: support T61 and UTF8 string. -* bufio: do not cache Read errors (thanks Graham Miller). -* build: make version.bash aware of branches. -* cgi: don't depend on CGI.pm for tests. -* codereview: make --ignore_hgpatch_failure work again, - restrict sync to default branch. -* crypto/openpgp: add ability to reserialize keys, - bug fix (thanks Gideon Jan-Wessel Redelinghuys). -* crypto/tls: fix generate_cert.go. -* crypto/x509: prevent chain cycles in Verify. -* csv: new package. -* doc: remove ed from apt-get package list. -* docs: fold the prog.sh scripting from makehtml into htmlgen itself. -* ebnflint: better handling of stdin. -* exp/regexp/syntax: new experimental RE2-based regexp implementation. -* exp/template: a new experimental templating package. -* fmt: add SkipSpace to fmt's ScanState interface. -* fmt: rename errno and error to err for doc consistency. -* gc: avoid package name ambiguity in error messages, - fix package quoting logic, - fixes for Plan 9 (thanks Lucio De Re). -* go/build: evaluate symlinks before comparing path to GOPATH. -* gob: use exported fields in structs in the package documentation. -* godoc: ignore directories that begin with '.', - search GOPATH for documentation. -* gofix: os/signal, path/filepath, and sort fixes (thanks Robert Hencke), -* goinstall: add support for generic hosts (thanks Julian Phillips), - only report successfully-installed packages to the dashboard, - try to access via https (thanks Yasuhiro Matsumoto). -* gotest: add -test.benchtime and -test.cpu flags. -* html: fixes and improvements (thanks Yasuhiro Matsumoto). -* http/cgi: add Handler.Dir to specify working directory (thanks Yasuhiro Matsumoto). -* http: add StripPrefix handler wrapper, - assume ContentLength 0 on GET requests, - better handling of 0-length Request.Body, - do TLS handshake explicitly before copying TLS state, - document that ServerConn and ClientConn are low-level, - make NewChunkedReader public (thanks Andrew Balholm), - respect Handlers setting Connection: close in their response. -* image: more tests, Paletted.Opaque optimization. -* io.WriteString: if the object has a WriteString method, use it (thanks Evan Shaw). -* ld: elide the Go symbol table when using -s (thanks Anthony Martin). -* ld: fix ELF strip by removing overlap of sections (thanks Gustavo Niemeyer). -* mime/multipart: parse LF-delimited messages, not just CRLF. -* mime: permit lower-case media type parameters (thanks Pascal S. de Kloe). -* misc/dashboard: new features and improvements (not yet deployed). -* misc/emacs: update list of builtins (thanks Quan Yong Zhai). -* misc/vim: allow only utf-8 for file encoding (thanks Yasuhiro Matsumoto). -* os: fix documentation for FileInfo.Name, - simplify WriteString, - use a different symbol from syscall in mkunixsignals.sh. -* path/filepath: enable TestWalk to run on windows (thanks Alex Brainman). -* reflect: add MethodByName, - allow Len on String values. -* regexp: document that Regexp is thread-safe. -* runtime/cgo: check for errors from pthread_create (thanks Albert Strasheim). -* runtime: add Semacquire/Semrelease benchmarks, - improved Semacquire/Semrelease implementation, - windows/amd64 port (thanks Wei Guangjing). -* sync: add fast path to Once, - improve Mutex to allow successive acquisitions, - new and improved benchmarks. -* syscall: regenerate zerrors for darwin/linux/freebsd, - support for tty options in StartProcess (thanks Ken Rockot). -* testing: make ResetTimer not start/stop the timer, - scale benchmark precision to 0.01ns if needed. -* time: zero-pad two-digit years. -* unicode/maketables: update debugging data. -* windows: define and use syscall.Handle (thanks Wei Guangjing). -* xml: add Marshal and MarshalIndent. -- -
-This snapshot includes a language change that restricts the use of goto. -In essence, a "goto" statement outside a block cannot jump to a label inside -that block. Your code may require changes if it uses goto. -This changeset shows how the new rule affected the Go tree: - http://code.google.com/p/go/source/detail?r=dc6d3cf9279d - -The os.ErrorString type has been hidden. If your code uses os.ErrorString it -must be changed. Most uses of os.ErrorString can be replaced with os.NewError. - -Other changes: -* 5c: do not use R9 and R10. -* 8l: more fixes for Plan 9 (thanks Lucio De Re). -* build: Make.ccmd: link with mach lib (thanks Joe Poirier). -* build: exclude packages that fail on Plan 9 (thanks Anthony Martin). -* cc: nit: silence comment warnings (thanks Dave Cheney). -* codereview.py: note that hg change -d abandons a change list (thanks Robert Hencke). -* crypto/openpgp: add ElGamal support. -* doc/faq: add question about converting from []T to []interface{}. -* doc: Effective Go: fix variadic function example (thanks Ben Lynn). -* exec: LookPath should not search %PATH% for files like c:cmd.exe (thanks Alex Brainman), - add support for Plan 9 (thanks Anthony Martin), - better error message for windows LookPath (thanks Alex Brainman). -* fmt: catch panics from calls to String etc. -* gc: descriptive panic for nil pointer -> value method call, - implement goto restriction, - unsafe.Alignof, unsafe.Offsetof, unsafe.Sizeof now return uintptr. -* go/build: include Import objects in Script Inputs. -* godefs: rudimentary tests (thanks Robert Hencke). -* goinstall: refactor and generalize repo handling code (thanks Julian Phillips), - temporarily use Makefiles by default (override with -make=false). -* gopprof: update list of memory allocators. -* http: add Server.ListenAndServeTLS, - buffer request.Write, - fix req.Cookie(name) with cookies in one header, - permit handlers to explicitly remove the Date header, - write Header keys with empty values. -* image: basic test for the 16-bits-per-color-channel types. -* io: clarify Read, ReadAt, Copy, Copyn EOF behavior. -* ld: don't attempt to build dynamic sections unnecessarily (thanks Gustavo Niemeyer). -* libmach: fix disassembly of FCMOVcc and FCOMI (thanks Anthony Martin), - fix tracing on linux (for cov) (thanks Anthony Martin). -* mime: fix RFC references (thanks Pascal S. de Kloe). -* misc/gobuilder: run make single-threaded on windows (thanks Alex Brainman). -* misc/godashboard: Accept sub-directories for goinstall's report (thanks Yasuhiro Matsumoto). -* nacl, tiny: remove vestiges (thanks Robert Hencke). -* net, syscall: interface for windows (thanks Yasuhiro Matsumoto). -* os: change Waitmsg String method to use pointer receiver (thanks Graham Miller). -* runtime: don't use twice the memory with grsec-like kernels (thanks Gustavo Niemeyer), -* spec: disallow goto into blocks. -* sync: restore GOMAXPROCS during benchmarks. -* syscall: add LSF support for linux (thanks Mikio Hara), - add socket control message support for darwin, freebsd, linux (thanks Mikio Hara), - add tty support to StartProcess (thanks Ken Rockot), - fix build for Sizeof change. -* test: test of goto restrictions. -* time: add support for Plan 9 (thanks Anthony Martin). -- -
-This snapshot includes changes to the sort and image/draw packages that will -require changes to client code. - -The sort.IntArray type has been renamed to IntSlice, and similarly for -StringArray and Float64Array. - -The image/draw package's Draw function now takes an additional argument, -a compositing operator. If in doubt, use draw.Over. - -Other changes: -* build: fix header files for Plan 9 (thanks Lucio De Re). -* cgo: handle new Apple LLVM-based gcc from Xcode 4.2. -* crypto/openpgp: add ability to encrypt and sign messages. -* doc/gopher: add goggled gopher logo for App Engine. -* doc: Update notes for 3-day Go course. -* exec: make LookPath work when PATHEXT var not set on Windows (thanks Alex Brainman). -* exp/regexp/syntax: syntax data structures, parser, escapes, character classes. -* exp/template: lexical scanner for new template package. -* fmt: debugging formats for characters: %+q %#U. -* gc: frame compaction for arm, - handle go print() and go println(), - work around goto bug. -* go/build: fixes, self-contained tests. -* go/printer, gofmt: print "select {}" on one line. -* godoc: replace OS file system accesses in favor of a FileSystem interface. -* gofix: fix inconsistent indentation in help output (thanks Scott Lawrence). -* goinstall: use go/build package to scan and build packages. -* http/spdy: improve error handling (thanks William Chan). -* http: use runtime/debug.Stack() to dump stack trace on panic. -* ld: dwarf emit filenames in debug_line header instead of as extended opcodes, - fix link Windows PE __declspec(dllimport) symbol (thanks Wei Guangjing), - make .rodata section read-only (thanks Gustavo Niemeyer). -* mail: decode RFC 2047 "B" encoding. -* mime/multipart: remove temp files after tests on Windows (thanks Alex Brainman). -* net: export all fields in Interface (thanks Mikio Hara), - rearrange source to run more tests on Windows (thanks Alex Brainman), - sendfile for win32 (thanks Yasuhiro Matsumoto). -* os: Plan 9, fix OpenFile & Chmod, add Process.Kill (thanks Yuval Pavel Zholkover). -* runtime: fix Plan 9 "lingering goroutines bug" (thanks Yuval Pavel Zholkover). -* spec: clarify rules for append, scope rules for :=, - specify constant conversions, - unsafe.Alignof/Offsetof/Sizeof return uintptr. -* syscall, os, exec: add *syscall.SysProcAttr field to os.ProcAttr and exec.Cmd. -* syscall: add ptrace on darwin (thanks Jeff Hodges), - mksyscall_windows.pl should output unix newline (thanks Yasuhiro Matsumoto). - update BPF support for BSD variants (thanks Mikio Hara), - use strict in perl scripts (thanks Yasuhiro Matsumoto). -* xml: handle non-string attribute fields (thanks Maxim Ushakov). -- -
-This snapshot includes changes to the strconv, http, and exp/draw packages. -Client code that uses the http or exp/draw packages will need to be changed, -and code that uses strconv or fmt's "%q" formatting directive merits checking. - -The strconv package's Quote function now escapes only those Unicode code points -not classified as printable by unicode.IsPrint. Previously Quote would escape -all non-ASCII characters. This also affects the fmt package's "%q" formatting -directive. The previous quoting behavior is still available via strconv's new -QuoteToASCII function. - -Most instances of the type map[string][]string in the http package have been -replaced with the new Values type. The http.Values type has the Get, Set, Add, -and Del helper methods to make working with query parameters and form values -more convenient. - -The exp/draw package has been split into the image/draw and exp/gui packages. - -Other changes: -* 8l, ld: initial adjustments for Plan 9 native compilation of 8l (thanks Lucio De Re). -* arm: floating point improvements (thanks Fan Hongjian). -* big: Improved speed of nat-to-string conversion (thanks Michael T. Jones), - Rat outputs the requested precision from FloatString (thanks Graham Miller), - gobs for big.Rats. -* cgo: support non intel gcc machine flags (thanks Dave Cheney). -* compress/lzw: do not use background goroutines, - reduce decoder buffer size from 3*4096 to 2*4096. -* crypto/twofish: fix Reset index overflow bug. -* crypto: reorg, cleanup and add function for generating CRLs. -* exec: export the underlying *os.Process in Cmd. -* gc: enable building under clang/2.9 (thanks Dave Cheney), - preparatory work toward escape analysis, compact stack frames. -* go/build: new incomplete package for building go programs. -* godefs: do not assume forward type references are enums (thanks Robert Hencke). -* gofix, gofmt: fix diff regression from exec change. -* html: improve attribute parsing, note package status. -* http: don't fail on accept hitting EMFILE, - fix handling of 0-length HTTP requests. -* image/draw: fix clipping bug where sp/mp were not shifted when r.Min was. -* image/gif: fix buglet in graphics extension. -* image/tiff: support for bit depths other than 8 (thanks Benny Siegert). -* ld: fix and simplify ELF symbol generation (thanks Anthony Martin) -* libmach: use the standardized format for designated initializers (thanks Jeff Hodges) -* mail: address list parsing. -* net: add network interface identification API (thanks Mikio Hara), - fix bug in net.Interfaces: handle elastic sdl_data size correctly (thanks Mikio Hara). -* netchan: added drain method to importer (thanks David Jakob Fritz). -* os: add Process.Kill and Process.Signal (thanks Evan Shaw), - fix Getenv for Plan 9 (thanks Yuval Pavel Zholkover). -* runtime: improve memmove by checking memory overlap (thanks Quan Yong Zhai), - support for Linux grsecurity systems (thanks Jonathan Mark). -* spec: handle a corner case for shifts. -* testing: check that tests and benchmarks do not affect GOMAXPROCS (thanks Dmitriy Vyukov). -* unicode: add IsPrint and related properties, general categories. -- -
-This snapshot includes changes to the exec package that will require changes -to client code. - -The exec package has been re-designed with a more convenient and succinct API. -This code: - args := []string{"diff", "-u", "file1.txt", "file2.txt"} - p, err := exec.Run("/usr/bin/diff", args, os.Environ(), "", - exec.DevNull, exec.Pipe, exec.DevNull) - if err != nil { - return nil, err - } - var buf bytes.Buffer - io.Copy(&buf, p.Stdout) - w, err := p.Wait(0) - p.Close() - if err != nil { - return nil, err - } - return buf.Bytes(), err -can be rewritten as: - return exec.Command("diff", "-u", "file1.txt", "file2.txt").Output() -See the exec package documentation for the details ("godoc exec"). - -By setting the GOPATH environment variable you can use goinstall to build and -install your own code and external libraries outside of the Go tree (and avoid -writing Makefiles). -See the goinstall command documentation for the details ("godoc goinstall"). - -Other changes: -* 5g: alignment fixes. -* 6l, 8l: fix Mach-O binaries with many dynamic libraries. -* 8l: emit resources (.rsrc) in Windows PE. (thanks Wei Guangjing). -* asn1: fix marshaling of empty optional RawValues (thanks Mikkel Krautz). -* big: make Int and Rat implement fmt.Scanner (thanks Evan Shaw), - ~8x faster number scanning, - remove some unnecessary conversions. -* cgo: restrict #cgo directives to prevent shell expansion (thanks Gustavo Niemeyer), - support pkg-config for flags and libs (thanks Gustavo Niemeyer). -* compress/flate: fix Huffman tree bug, - do not use background goroutines. -* crypto/openpgp: add support for symmetrically encrypting files. -* crypto/tls/generate_cert.go: fix misspelling of O_CREATE. -* dashboard: send notification emails when the build breaks. -* doc: mention go/printer instead of container/vector in effective go, - put Release History link on 'Documentation' page, - put Weekly Snapshot History link on 'Contributing' page. -* encoding/base64: add DecodeString and EncodeToString. -* encoding/binary: add a non-reflect fast path for Read, - add a non-reflect fast path for Write. -* encoding/hex: add hex dumping. -* encoding/line: delete package. Its functionality is now in bufio. -* filepath: Abs must always return a clean path (thanks Gustavo Niemeyer). -* fmt: fix bug in UnreadRune, - make %q work for integers, printing a quoted character literal, - return EOF when out of input in Scan*. -* gc: check parameter declarations in interface fields (thanks Anthony Martin), - disallow ... in type conversions (thanks Anthony Martin), - do not force heap allocation on referencing outer variable in a closure, - fix m[x], _ = y.(T), - implement new shift rules, - patch y.tab.c to fix build when using Bison 2.5, - relax assignability of method receivers (thanks Anthony Martin), - typecheck the whole tree before walking. -* go/scanner: don't allow "0x" and "0X" as integers (thanks Evan Shaw). -* gobuilder: fixes for windows (thanks Alex Brainman). -* godoc: basic setup for running godoc on local app engine emulator, - display advert for the package dashboard on package list page. -* goinstall: fixes for windows (thanks Alex Brainman), - more verbose logging with -v. -* gotest, pkg/exec: use bash to run shell scripts on windows (thanks Alex Brainman). -* http/spdy: redo interfaces, flesh out implementation & frame types (thanks William Chan). -* http: Transport hook to register non-http(s) protocols, - add client+server benchmark, - catch Handler goroutine panics, - fix Set-Cookie date parsing, - have client set Content-Length when possible, - let Transport use a custom net.Dial function, - propagate Set-Cookie in reverse proxy, - ServeFile shouldn't send Content-Length when Content-Encoding is set. -* image: add a SubImage method. -* image/gif: simplify blockReader.Read. -* image/png: fix encoding of images that don't start at (0, 0). -* io, net, http: sendfile support. -* io: add ByteScanner, RuneScanner interfaces. -* ld: add -w to disable dwarf, make errors obviously from dwarf. -* mail: new package. -* mime/multipart: misc code/doc fixes. -* misc/cgo: remove reference to 'destroy' function. -* misc/emacs: don't select the mark after gofmt (thanks Eric Eisner). -* misc/gophertool: Chrome extension to aid in Go development -* misc/vim: limit Fmt command to Go buffers (thanks Yasuhiro Matsumoto). -* net: if we stop polling, remove any pending events for the socket, - update IP multicast socket options (thanks Mikio Hara). -* os: Fix test to work on Solaris, - fix Readdir(0) on EOF, - fix Readdir, Readdirnames (thanks Yuval Pavel Zholkover), - fix os.MkdirAll with backslash path separator (thanks Yasuhiro Matsumoto), - handle OpenFile flag parameter properly on Windows (thanks Alex Brainman). -* path/filepath: remove string constants. -* pkg: spelling tweaks, I-Z (thanks Robert Hencke). -* quietgcc: fix typo, respect $TMPDIR. -* runtime: do not garbage collect windows callbacks (thanks Alex Brainman), - fix mmap error return on linux (thanks Dmitry Chestnykh), - reset GOMAXPROCS during tests, - save cdecl registers in Windows SEH handler (thanks Alexey Borzenkov). -* spec: be precise with the use of the informal ellipsis and the Go token, - clarify rules for shifts. -* strconv: add QuoteRune; analogous to Quote but for runes rather than strings. -* strings: implement UnreadByte, UnreadRune. -* sync: always wake up sleeping goroutines on Cond.Signal (thanks Gustavo Niemeyer). -* sync/atomic: fix check64. -* syscall: add ProcAttr field to pass an unescaped command line on windows (thanks Vincent Vanackere), - add routing messages support for Linux and BSD (thanks Mikio Hara). -* template: fixes and clean-ups (thanks Gustavo Niemeyer). -* time: fix Format bug: midnight/noon are 12AM/PM not 0AM/PM. -* unicode: make the tables smaller. -- -
-This snapshot includes changes to the http package that will require changes to -client code. - -The finalURL return value of the Client.Get method has been removed. -This value is now accessible via the new Request field on http.Response. -For example, this code: - - res, finalURL, err := http.Get(...) - -should be rewritten as: - - res, err := http.Get(...) - if err != nil { - // ... - } - finalURL := res.Request.URL.String() - -Uses of http.Get that assign the finalURL value to _ can be rewritten -automatically with gofix. - -This snapshot also includes an optimization to the append function that makes it -between 2 and 5 times faster in typical use cases. - -Other changes: -* 5a, 6a, 8a, cc: remove old environment variables. -* 5c, 5g: fix build with too-smart gcc. -* 5l, 8l: add ELF symbol table to binary. -* 5l: delete pre-ARMv4 instruction implementations, other fixes. -* 6l, 8l: emit windows dwarf sections like other platforms (thanks Alex Brainman). -* 6l: fix emit windows dwarf sections (thanks Wei Guangjing). -* 8g: fix conversion from float to uint64 (thanks Anthony Martin). -* Make.cmd: create TARGDIR if necessary (thanks Gustavo Niemeyer). -* asn1: add big support. -* big: add Int methods to act on numbered bits (thanks Roger Peppe), - better support for string conversions, - support %v and # modifier, better handling of unknown formats. -* cgi: export RequestFromMap (thanks Evan Shaw), - set Request.TLS and Request.RemoteAddr for children. -* cgo: use packed struct to fix Windows behavior. -* codereview: add release branch support, - fetch metadata using JSON API, not XML scraping, - handle 'null as missing field' in rietveld json. -* compress/lzw: silently drop implied codes that are too large. -* compress/zlib: actually use provided dictionary in NewWriterDict -* crypto/openpgp: add key generation support, - change PublicKey.Serialize to include the header. -* crypto/rand: add utility functions for number generation (thanks Anthony Martin). -* crypto/tls: export the verified chains. -* crypto/x509/crl: add package. -* crypto/x509: export raw SubjectPublicKeyInfo, - support DSA public keys in X.509 certs, - support parsing and verifying DSA signatures (thanks Jonathan Allie). -* doc/roadmap: put "App Engine support" under "Done". -* doc: add I/O 2011 talks to talks/, docs.html, and front page. -* effective go: explain about values/pointers in String() example, - update to new Open signature. -* exp/draw: fast paths for drawing a YCbCr or an NRGBA onto an RGBA. -* filepath: make EvalSymlinks work on Windows (thanks Alex Brainman). -* flag: allow distinct sets of flags. -* gc: fix type switch error message for invalid cases (thanks Lorenzo Stoakes), - fix unsafe.Sizeof, - preserve original expression for errors. -* go/ast, go/doc, godoc: consider struct fields and interface methods when filtering ASTs. -* go/ast: consider anonymous fields and set Incomplete bit when filtering ASTs, - properly maintain map of package global imports. -* go/doc, godoc: when filtering for godoc, don't remove elements of a declaration. -* go/parser: accept parenthesized receive operations in select statements, - always introduce an ast.Object when declaring an identifier. -* go/printer, gofmt: fix alignment of "=" in const/var declarations, - fix formatting of expression lists (missing blank). -* go/printer: added simple performance benchmark, - make tests follow syntactic restrictions, - more accurate comment for incomplete structs/interfaces, -* go/token: faster FileSet.Position implementation. -* go/types: type checker API + testing infrastructure. -* godoc: added -index flag to enable/disable search index, - if there is no search box, don't run the respective JS code. -* gofmt: update test.sh (exclude a file w/ incorrect syntax). -* html: parse empty, unquoted, and single-quoted attribute values. -* http/cgi: correctly set request Content-Type (thanks Evan Shaw), - pass down environment variables for IRIX and Solaris. -* http/pprof: fix POST reading bug. -* http/spdy: new incomplete package (thanks Ross Light). -* http: Client.Do should follow redirects for GET and HEAD, - add Header.Write method (thanks Evan Shaw), - add Request.SetBasicAuth method, - add Transport.ProxySelector, - add http.SetCookie(ResponseWriter, *Cookie), - don't Clean query string in relative redirects, - fix FormFile nil pointer dereference on missing multipart form, - fix racy test with a simpler version, - fix two Transport gzip+persist crashes, - include Host header in requests, - make HEAD client request follow redirects (thanks Eivind Uggedal). - update cookie doc to reference new RFC 6265, - write cookies according to RFC 6265 (thanks Christian Himpel). -* image/bmp: implement a BMP decoder. -* image/gif: new package provides a GIF decoder. -* image/jpeg: decode grayscale images, not just color images. - optimizations and tweaks. -* image/png: encode paletted images with alpha channel (thanks Dmitry Chestnykh), - speed up opaque RGBA encoding. -* image/tiff: implement a decoder (thanks Benny Siegert). -* image: add type-specific Set methods and use them when decoding PNG, - make AlphaColor.Set conform to usual signature (thanks Roger Peppe), - png & jpeg encoding benchmarks. -* ld: do not emit reference to dynamic library named "", - fix alignment of rodata section on Plan 9 (thanks Anthony Martin), - make ELF binaries with no shared library dependencies static binaries. -* make.bash: remove old bash version of gotest on Windows (thanks Alex Brainman). -* make: add nuke target for C commands and libs (thanks Anthony Martin). -* mime/multipart: add FileName accessor on Part, - add Writer, - return an error on Reader EOF, not (nil, nil). -* misc/cgo/test: run tests. -* misc/emacs: use UTF-8 when invoking gofmt as a subprocess (thanks Sameer Ajmani). -* misc/vim: new Vim indentation script. -* net, http: add and make use of IP address scope identification API (thanks Mikio Hara). -* net: default to 127.0.0.1, not localhost, in TestICMP, - don't crash on unexpected DNS SRV responses, - enable SO_REUSEPORT on BSD variants (thanks Mikio Hara), - protocol family adaptive address family selection (thanks Mikio Hara), - re-enable wildcard listening (thanks Mikio Hara), - sort records returned by LookupSRV (thanks Gary Burd). -* os: make Readdir & Readdirnames return os.EOF at end, - make Setenv update C environment variables. -* reflect: allow unexported key in Value.MapIndex. -* runtime, sync/atomic: fix arm cas. -* runtime: add newline to "finalizer already set" error (thanks Albert Strasheim), - handle out-of-threads on Linux gracefully (thanks Albert Strasheim), - fix function args not checked warning on ARM (thanks Dave Cheney), - make StackSystem part of StackGuard (thanks Alexey Borzenkov), - maybe fix Windows build broken by cgo setenv CL. -* spec: clarify semantics of integer division, - clarify semantics of range clause, - fix error in production syntax, - narrow syntax for expression and select statements, - newlines cannot be used inside a char or "" string literal, - restricted expressions may still be parenthesized. -* strings: make Reader.Read use copy instead of an explicit loop. -* syscall: add Windows file mapping functions and constants (thanks Evan Shaw), - add IPv6 scope zone ID support (thanks Mikio Hara), - add netlink support for linux/386, linux/amd64, linux/arm (thanks Mikio Hara), - add Sendfile, - adjust freebsd syscalls.master URL properly (thanks Mikio Hara), - change Overlapped.HEvent type, it is a handle (thanks Alex Brainman). -* syslog: fix skipping of net tests (thanks Gustavo Niemeyer). -* template: support string, int and float literals (thanks Gustavo Niemeyer). -* xml: fix reflect error. -- -
-This snapshot includes revisions to the reflect package to make it more -efficient, after the last weekly's major API update. If your code uses reflect -it may require further changes, not all of which can be made automatically by -gofix. For the full details of the change, see - http://codereview.appspot.com/4435042 -Also, the Typeof and NewValue functions have been renamed to TypeOf and ValueOf. - -Other changes: -* 5c: make alignment rules match 5g, just like 6c matches 6g. -* 8g, 8l: fix "set but not used" gcc error (thanks Fazlul Shahriar). -* all-qemu.bash: remove DISABLE_NET_TESTS. -* build: remove DISABLE_NET_TESTS. -* builder: build multiple targets in parallel. -* cgo: avoid "incompatible pointer type" warning (thanks Albert Strasheim). -* codereview: add 'hg undo' command, various other fixes. -* compress/flate: dictionary support. -* compress/zlib: add FDICT flag in Reader/Writer (thanks Ross Light). -* container/heap: fix circular dependency in test. -* crypto/openpgp: better handling of keyrings. -* crypto/rsa: support > 3 primes. -* crypto/tls: add server-side OCSP stapling support. -* crypto/x509: memorize chain building. -* crypto: move certificate verification into x509. -* dashboard: build most recent revision first. -* doc: mention make version in install.html. -* expvar: add Func for functions that return values that are JSON marshalable. -* fmt: decrease recursion depth in tests to permit them to run under gccgo, - tweak the doc for %U. -* gc: allow complex types to be receiver types (thanks Robert Hencke), - correct handling of unexported method names in embedded interfaces, - explain why invalid receiver types are invalid, - fix copy([]int, string) error message (thanks Quan Yong Zhai), - fix 'invalid recursive type' error (thanks Lorenzo Stoakes), - many bug fixes. -* go spec: attempt at clarifying language for "append", - for map types, mention indexing operations. -* go/types: update for export data format change. -* gob: fix handling of indirect receivers for GobDecoders, - fix trivial bug in map marshaling, - have errorf always prefix the message with "gob: ", - test case for indirection to large field, - use new Implements and AssignableTo methods in reflect, - when decoding a string, allocate a string, not a []byte. -* gobuilder: permit builders of the form goos-goarch-foo, - respect MAKEFLAGS if provided (thanks Dave Cheney). -* godoc: use "search" input type for search box (thanks Dmitry Chestnykh). -* gofix: add support for reflect rename. -* gofmt: add -d (diff) (thanks David Crawshaw), - don't crash when rewriting nil interfaces in AST, - exclude test case that doesn't compile w/o errors, - gofmt test harness bug fix. -* goinstall: support GOPATH; building and installing outside the Go tree, - support building executable commands. -* gopack: fix prefix bug, - preserve safe flag when not adding unsafe objects to archive. -* gotest: add timing, respect $GOARCH, - generate gofmt-compliant code. -* http/cgi: copy some PATH environment variables to child, - improve Location response handling, - pass some default environment variables. -* http/fcgi: new package (thanks Evan Shaw). -* http: add NewRequest helper, - add MultipartForm, ParseMultipartForm, and FormFile to Request, - be clear when failing to connect to a proxy, - bug fixes and new tests, - consume request bodies before replying, - don't quote Set-Cookie Domain and Path (thanks Petar Maymounkov), - fix IP confusion in TestServerTimeouts, - handler timeout support, - ServerConn, ClientConn: add real Close (thanks Petar Maymounkov), - make Client redirect policy configurable, - put a limit on POST size, - reverse proxy handler. -* image/jpeg: add an encoder, - decode to a YCbCr image instead of an RGBA image. -* ioutil: add Discard. -* json: keep track of error offset in SyntaxError. -* ld: defend against some broken object files, - do not emit empty dwarf pe sections (thanks Alex Brainman), - fix 6l -d on Mac, diagnose invalid use of -d, - fix Plan 9 symbol table (thanks Anthony Martin), - remove MachoLoad limit. -* make: prevent rm provoking 'text file busy' errors (thanks Lorenzo Stoakes). -* mime/multipart: add ReadForm for parsing multipart forms, - limit line length to prevent abuse. -* mime: RFC 2231 continuation / non-ASCII support, - bunch more tests, few minor parsing fixes. -* misc/goplay: fix Tab and Shift+Enter in Firefox (thanks Dmitry Chestnykh). -* net: disable one more external network test, - fix EAI_BADFLAGS error on freebsd (thanks Mikio Hara), - fix ParseIP (thanks Quan Yong Zhai), - fix dialgoogle_test.go (thanks Quan Yong Zhai), - try /etc/hosts before loading DNS config (thanks Dmitry Chestnykh), - use C library resolver on FreeBSD, Linux, OS X / amd64, 386. -* os/user: new package to look up users. -* os: Open with O_APPEND|O_CREATE to append on Windows (thanks Alex Brainman), - fix race in ReadAt/WriteAt on Windows (thanks Alex Brainman), - turn EPIPE exit into panic. -* rc/env.bash: fix to build on windows under msys (thanks Joe Poirier). -* reflect: allow Slice of arrays, - fix Copy of arrays (thanks Gustavo Niemeyer), - require package qualifiers to match during interface check, - add Type.Implements, Type.AssignableTo, Value.CallSlice, - make Set match Go. -* rpc: allow the first argument of a method to be a value rather than a pointer, - run benchmarks over HTTP as well as direct network connections. -* run.bash: remove redundant rebuilds. -* runtime/plan9: warning remediation for Plan 9 (thanks Lucio De Re), -* runtime: many bug fixes, - fix GOMAXPROCS vs garbage collection bug (thanks Dmitriy Vyukov), - fix mkversion to output valid path separators (thanks Peter Mundy), - more graceful out-of-memory crash, - require package qualifiers to match during interface check, - skip functions with no lines when building src line table, - turn "too many EPIPE" into real SIGPIPE. -* src/pkg: make package doc comments consistently start with "Package foo". -* syscall: Madvise and Mprotect for Linux (thanks Albert Strasheim), - Mlock, Munlock, Mlockall, Munlockall on Linux (thanks Albert Strasheim), - add BPF support for darwin/386, darwin/amd64 (thanks Mikio Hara), - correct Windows CreateProcess input parameters (thanks Alex Brainman), - fix Ftruncate under linux/arm5 (thanks Dave Cheney), - permit StartProcess to hide the executed program on windows (thanks Vincent Vanackere). -* test/bench: update timings; moving to new machine. -* time: support Irix 6 location for zoneinfo files. -* tutorial: modernize the definition and use of Open, - replace the forever loops with finite counts in sieve programs. -* websocket: include *http.Request in websocket.Conn. -* xml: Parser hook for non-UTF-8 charset converters. -- -
-weekly.2011-04-13 - -This weekly snapshot includes major changes to the reflect package and the -os.Open function. Code that uses reflect or os.Open will require updating, -which can be done mechanically using the gofix tool. - -The reflect package's Type and Value types have changed. Type is now an -interface that implements all the possible type methods. Instead of a type -switch on a reflect.Type t, switch on t.Kind(). Value is now a struct value -that implements all the possible value methods. Instead of a type switch on a -reflect.Value v, switch on v.Kind(). See the change for the full details: - http://code.google.com/p/go/source/detail?r=843855f3c026 - -The os package's Open function has been replaced by three functions: - OpenFile(name, flag, perm) // same as old Open - Open(name) // same as old Open(name, O_RDONLY, 0) - Create(name) // same as old Open(name, O_RDWR|O_TRUNC|O_CREAT, 0666) - -To update your code to use the new APIs, run "gofix path/to/code". Gofix can't -handle all situations perfectly, so read and test the changes it makes before -committing them. - -Other changes: -* archive/zip: add func OpenReader, type ReadCloser (thanks Dmitry Chestnykh). -* asn1: Implement correct marshaling of length octets (thanks Luit van Drongelen). -* big: don't crash when printing nil ints. -* bufio: add ReadLine, to replace encoding/line. -* build: make the build faster, quieter. -* codereview: automatically port old diffs forward, - drop Author: line on self-clpatch, - recognize code URL without trailing slash. -* crypto/block: remove deprecated package. -* crypto/des: new package implementating DES and TDEA (thanks Yasuhiro Matsumoto). -* crypto/ecdsa, crypto/rsa: use io.ReadFull to read from random source (thanks Dmitry Chestnykh). -* crypto/rsa: add 3-prime support, - add support for precomputing CRT values, - flip the CRT code over so that it matches PKCS#1. -* crypto/x509: expose complete DER data (thanks Mikkel Krautz). -* doc: new "Functions" codewalk (thanks John DeNero). -* doc/roadmap: add sections on tools, packages. -* fmt: allow %U for unsigned integers. -* gc: fixes and optimizations. -* go/printer, gofmt: use blank to separate import rename from import path. -* go/scanner: better TokenString output. -* go/types: new Go type hierarchy implementation for AST. -* godashboard: show packages at launchpad.net (thanks Gustavo Niemeyer). -* gofix: add -diff, various fixes and helpers. -* gotest: fix a bug in error handling, - fixes for [^.]_test file pattern (thanks Peter Mundy), - handle \r\n returned by gomake on Windows (thanks Alex Brainman). -* gotype: use go/types GcImporter. -* govet: make name-matching for printf etc. case-insensitive. -* http: allow override of Content-Type for ServeFile, - client gzip support, - do not listen on 0.0.0.0 during test, - flesh out server Expect handling + tests. -* image/ycbcr: new package. -* image: allow "?" wildcards when registering image formats. -* io: fixes for Read with n > 0, os.EOF (thanks Robert Hencke). -* ld: correct Plan 9 compiler warnings (thanks Lucio De Re), - ELF header function declarations (thanks Lucio De Re), - fix Mach-O X86_64_RELOC_SIGNED relocations (thanks Mikkel Krautz), - fix Mach-O bss bug (thanks Mikkel Krautz), - fix dwarf decoding of strings for struct's fieldnames (thanks Luuk van Dijk), - fixes and optimizations (25% faster). -* log: generalize getting and setting flags and prefix. -* misc/cgo/life: enable build and test on Windows (thanks Alex Brainman). -* misc/vim: add plugin with Fmt command (thanks Dmitry Chestnykh), - update type highlighting for new reflect package. -* net: disable multicast tests by default (thanks Dave Cheney), - sort records returned by LookupMX (thanks Corey Thomasson). -* openpgp: Fix improper := shadowing (thanks Gustavo Niemeyer). -* os: rename Open to OpenFile, add new Open, Create, - fix Readdir in Plan 9 (thanks Fazlul Shahriar). -* os/inotify: use _test for test files, not _obj. -* pkg/path: enable tests on Windows (thanks Alex Brainman). -* reflect: new Type and Value API. -* src/pkg/Makefile: trim per-directory make output except on failure. -* syscall: Add DT_* and MADV_* constants on Linux (thanks Albert Strasheim), - add Mmap, Munmap on Linux, FreeBSD, OS X, - fix StartProcess in Plan 9 (thanks Fazlul Shahriar), - fix Windows Signaled (thanks Alex Brainman). -* test/bench: enable build and test on Windows (thanks Alex Brainman). -- -
-This snapshot includes changes to the net package. Your code will require -changes if it uses the Dial or LookupHost functions. - -The laddr argument has been removed from net.Dial, and the cname return value -has been removed from net.LookupHost. The new net.LookupCNAME function can be -used to find the canonical host for a given name. You can update your -networking code with gofix. - -The gotest shell script has been replaced by a Go program, making testing -significantly faster. - -Other changes: -* asn1: extensions needed for parsing Kerberos. -* bufio: Write and WriteString cleanup (thanks Evan Shaw). -* bytes, strings: simplify Join (thanks Evan Shaw). -* crypto/cipher: bad CTR IV length now triggers panic. -* crypto/tls: extend NPN support to the client, - added X509KeyPair function to parse a Certificate from memory. -* crypto/x509: parse Extended Key Usage extension (thanks Mikkel Krautz). -* debug/gosym: remove need for gotest to run preparatory commands. -* fmt: implement precision (length of input) values for %q: %.20q. -* go/parser: fix scoping for local type declarations (thanks Roger Peppe), - package name must not be the blank identifier. -* go/printer, gofmt: remove special case for multi-line raw strings. -* gopack: add P flag to remove prefix from filename information. -* gotest: add -test.timeout option, - replace the shell script with the compiled program written in go, - execute gomake properly on Windows (thanks Alex Brainman). -* gotry: move into its own directory, separate from gotest. -* gotype: support for more tests, added one new test. -* http: add Transport.MaxIdleConnsPerHost, - use upper case hex in URL escaping (thanks Matt Jones). -* httptest: add NewTLSServer. -* misc/kate: reorganize, remove closed() (thanks Evan Shaw). -* misc/notepadplus: support for notepad++ (thanks Anthony Starks). -* net: implement non-blocking connect (thanks Alexey Borzenkov). -* os: fix MkdirAll("/thisdoesnotexist") (thanks Albert Strasheim), - Plan 9 support (thanks Yuval Pavel Zholkover), - add a few missing Plan 9 errors (thanks Andrey Mirtchovski), - fix FileInfo.Name returned by Stat (thanks David Forsythe). -* path/filepath.Glob: add an error return, - don't drop known matches on error. -* path/filepath: add support for Plan 9 (thanks Andrey Mirtchovski). -* scanner: treat line comments like in Go. -* syscall: Plan 9 support (thanks Yuval Pavel Zholkover), - StartProcess Chroot and Credential (thanks Albert Strasheim), - add BPF support for freebsd/386, freebsd/amd64 (thanks Mikio Hara), - make [Raw]Syscall6 pass 6th arg on linux/386 (thanks Evan Shaw). -- -
-This weekly release includes improved support for testing. - -Memory and CPU profiling is now available via the gotest tool. Gotest will -produce memory and CPU profiling data when invoked with the -test.memprofile -and -test.cpuprofile flags. Run "godoc gotest" for details. - -We have also introduced a way for tests to run quickly when an exhaustive test -is unnecessary. Gotest's new -test.short flag in combination with the testing -package's new Short function allows you to write tests that can be run in -normal or "short" mode; short mode is now used by all.bash to reduce -installation time. -The Makefiles know about the flag - you can just run "make testshort". - -Other changes: -* .hgignore: Ignore all goinstalled packages (thanks Evan Shaw). -* build: add all-qemu.bash, handful of arm fixes, - add support for SWIG, and add two SWIG examples, - diagnose Ubuntu's buggy copy of gold, - handle broken awk in version.bash (thanks Dave Cheney), - reenable clean.bash without gomake (thanks Gustavo Niemeyer). -* cgo: fix index-out-of-bounds bug. -* codereview: permit CLs of the form weekly.DATE -* crypto/ecdsa: truncate hash values. -* crypto/openpgp: add DSA signature support. -* dashboard: remove old python/bash builder, update README. -* doc: explain release and weekly tags in install.html. -* exec: document dir option for Run (thanks Gustavo Niemeyer). -* flag: document Nflag function (thanks Fazlul Shahriar). -* gc: remove interim ... error which rejects valid code. -* go/ast: implemented NewPackage, - merge CaseClause and TypeCaseClause. -* go/parser: fix memory leak by making a copy of token literals, - resolve identifiers properly. -* go/printer, gofmt: avoid exponential layout algorithm, - gofmt: simplify struct formatting and respect line breaks. -* go/scanner: to interpret line comments with Windows filenames (thanks Alex Brainman). -* go/token: use array instead of map for token->string table. -* gob: optimizations to reduce allocations, - use pointers in bootstrapType so interfaces behave properly. -* gobuilder: recognize CLs of the form weekly.DATE. -* godefs: handle volatile. -* godoc: add -template flag to specify custom templates, - fix path problem for windows (thanks Yasuhiro Matsumoto). -* gofix: httpserver - rewrite rw.SetHeader to rw.Header.Set. -* gofmt: add profiling flag. -* gopprof: fix bug: do not rotate 180 degrees for large scrolls, - update list of memory allocation functions. -* gotest: fix gofmt issue in generated _testmain.go. -* http: add NewProxyClientConn, - avoid crash when asked for multiple file ranges, - don't chunk 304 responses, - export Transport, add keep-alive support. -* ld: return > 0 exit code on unsafe import. -* misc/bbedit: remove closed keyword (thanks Anthony Starks). -* misc/emacs: gofmt: don't clobber the current buffer on failure. -* misc/vim: remove 'closed' as a builtin function. -* net: add FileConn, FilePacketConn, FileListener (thanks Albert Strasheim), - don't force epoll/kqueue to wake up in order to add new events, - let OS-specific AddFD routine wake up polling thread, - use preallocated buffer for epoll and kqueue/kevent. -* path/filepath: add EvalSymlinks function, - fix TestEvalSymlinks when run under symlinked GOROOT. -* path: work for windows (thanks Yasuhiro Matsumoto). -* rpc: increase server_test timeout (thanks Gustavo Niemeyer), - optimizations to reduce allocations. -* runtime: fix darwin/amd64 thread VM footprint (thanks Alexey Borzenkov), - fix gdb support for goroutines, - more stack split fixes, - os-specific types and code for setitimer, - update defs.h for freebsd-386 (thanks Devon H. O'Dell). -* strings: Map: avoid allocation when string is unchanged. -* syscall: GetsockoptInt (thanks Albert Strasheim), - StartProcess fixes for windows (thanks Alex Brainman), - permit non-blocking syscalls, - rename from .sh to .pl, because these files are in Perl. -* test: enable tests using v, ok := <-ch syntax (thanks Robert Hencke). -* time: give a helpful message when we can't set the time zone for testing. - isolate syscall reference in sys.go. -- -
-This week's release introduces a new release tagging scheme. We intend to -continue with our weekly releases, but have renamed the existing tags from -"release" to "weekly". The "release" tag will now be applied to one hand-picked -stable release each month or two. - -The revision formerly tagged "release.2011-03-07.1" (now "weekly.2011-03-07.1") -has been nominated our first stable release, and has been given the tag -"release.r56". As we tag each stable release we will post an announcement to -the new golang-announce mailing list: - http://groups.google.com/group/golang-announce - -You can continue to keep your Go installation updated using "hg update -release", but now you should only need to update once we tag a new stable -release, which we will announce here. If you wish to stay at the leading edge, -you should switch to the weekly tag with "hg update weekly". - - -This weekly release includes significant changes to the language spec and the -http, os, and syscall packages. Your code may need to be changed. It also -introduces the new gofix tool. - -The closed function has been removed from the language. The syntax for channel -receives has been changed to return an optional second value, a boolean value -indicating whether the channel is closed. This code: - v := <-ch - if closed(ch) { - // channel is closed - } -should now be written as: - v, ok := <-ch - if !ok { - // channel is closed - } - -It is now illegal to declare unused labels, just as it is illegal to declare -unused local variables. - -The new gofix tool finds Go programs that use old APIs and rewrites them to use -newer ones. After you update to a new Go release, gofix helps make the -necessary changes to your programs. Gofix will handle the http, os, and syscall -package changes described below, and we will update the program to keep up with -future changes to the libraries. - -The Hijack and Flush methods have been removed from the http.ResponseWriter -interface and are accessible via the new http.Hijacker and http.Flusher -interfaces. The RemoteAddr and UsingTLS methods have been moved from -http.ResponseWriter to http.Request. - -The http.ResponseWriter interface's SetHeader method has been replaced by a -Header() method that returns the response's http.Header. Caller code needs to -change. This code: - rw.SetHeader("Content-Type", "text/plain") -should now be written as: - rw.Header().Set("Content-Type", "text/plain") -The os and syscall packages' StartProcess functions now take their final three -arguments as an *os.ProcAttr and *syscall.ProcAttr values, respectively. This -code: - os.StartProcess(bin, args, env, dir, fds) -should now be written as: - os.StartProcess(bin, args, &os.ProcAttr{Files: fds, Dir: dir, Env: env}) - -The gob package will now encode and decode values of types that implement the -gob.GobEncoder and gob.GobDecoder interfaces. This allows types with unexported -fields to transmit self-consistent descriptions; one instance is big.Int and -big.Rat. - -Other changes: -* 5l, 6l, 8l: reduce binary size about 40% by omitting symbols for type, string, go.string. -* 5l, 8l: output missing section symbols (thanks Anthony Martin). -* 6l, 8l: fix gdb crash. -* Make.cmd: also clean _test* (thanks Gustavo Niemeyer). -* big: implemented custom Gob(En/De)coder for Int type. -* build: remove duplicate dependency in Make.cmd (thanks Robert Hencke), - run gotest in misc/cgo/test. -* codereview.py: don't suggest change -d if user is not CL author (thanks Robert Hencke). -* compress/lzw: benchmark a range of input sizes. -* crypto/ecdsa: add package. -* crypto/elliptic: add the N value of each curve. -* crypto/openpgp: bug fixes and fix misnamed function. -* crypto/tls: fix compile error (thanks Dave Cheney). -* doc: Effective Go: some small cleanups, - update FAQ. hello, world is now 1.1MB, down from 1.8MB, - update codelab wiki to fix template.Execute argument order. -* flag: visit the flags in sorted order, for nicer messages. -* fmt: do not export EOF = -1. -* fmt: make ScanState.Token more general (thanks Roger Peppe). -* gc: diagnose unused labels, - fix handling of return values named _, - include all dependencies in export metadata, - make unsafe.Pointer its own kind of type, instead of an equivalent to *any. -* go/ast, go/parser: populate identifier scopes at parse time. -* go/ast: add FileSet parameter to ast.Print and ast.Fprint. -* go/parser: first constant in a constant declaration must have a value. -* gob: efficiency and reliability fixes. -* gofmt: remove -trace and -ast flags. -* goinstall: handle $(GOOS) and $(GOARCH) in filenames, - handle .c files with gc when cgo isn't used, and - handle .s files with gc (thanks Gustavo Niemeyer). -* gopack: omit time stamps, makes output deterministic. -* gotype: commandline tool to typecheck go programs. -* govet: handle '*' in print format strings. -* hash: new FNV-1a implementation (thanks Pascal S. de Kloe). -* http/cgi: child support (e.g. Go CGI under Apache). -* http: adapt Cookie code to follow IETF draft (thanks Petar Maymounkov), - add test for fixed HTTP/1.0 keep-alive issue, - don't hit external network in client_test.go, - fix transport crash when request URL is nil, - rename interface Transport to RoundTripper, - run tests even with DISABLE_NET_TESTS=1. -* httptest: default the Recorder status code to 200 on a Write. -* io/ioutil: clean-up of ReadAll and ReadFile. -* ioutil: add NopCloser. -* ld: preserve symbol sizes during data layout. -* lib9, libmach: Change GOOS references to GOHOSTOS (thanks Evan Shaw). -* libmach: correct string comparison to revive 6cov on darwin (thanks Dave Cheney). -* misc/vim: Add indent script for Vim (thanks Ross Light). -* net, os, syslog: fixes for Solaris support. -* net: don't loop to drain wakeup pipe. -* nm: document -S flag. -* openpgp: add PublicKey KeyId string accessors. -* rpc: optimizations, add benchmarks and memory profiling, - use httptest.Server for tests (thanks Robert Hencke). -* runtime: reduce lock contention via wakeup on scheduler unlock, - scheduler, cgo reorganization, - split non-debugging malloc interface out of debug.go into mem.go. -* spec: clarify return statement rules. -* strings: add IndexRune tests, ASCII fast path, - better benchmark names; add BenchmarkIndex. -* syscall: implement Mount and Unmount for linux, - implement Reboot for linux. -* time: fix Time.ZoneOffset documentation (thanks Peter Mundy). -* tls: move PeerCertificates to ConnectionState. -- -
-This release includes changes to the reflect and path packages. -Code that uses reflect or path may need to be updated. - -The reflect package's Value.Addr method has been renamed to Value.UnsafeAddr. -Code that uses the Addr method will have to call UnsafeAddr instead. - -The path package has been split into two packages: path and path/filepath. -Package path manipulates slash-separated paths, regardless of operating system. -Package filepath implements the local operating system's native file paths. -OS-specific functioanlity in pacakge path, such as Walk, moved to filepath. - -Other changes: -* build: fixes and simplifications (thanks Dave Cheney), - move $GOBIN ahead of /bin, /usr/bin in build $PATH. -* bzip2: speed up decompression. -* cgo: fix dwarf type parsing (thanks Gustavo Niemeyer), - put temporary source files in _obj (thanks Roger Peppe), - fix bug involving 0-argument callbacks. -* compress/lzw: optimizations. -* doc: add FAQ about "implements", - add FAQ about large binaries , - add FAQ about stack vs heap allocation, - add internationalization to roadmap, - describe platform-specific conventions in code.html. -* fmt: allow recursive calls to Fscan etc (thanks Roger Peppe), - make %#p suppress leading 0x. -* gc, gopack: add some missing flags to the docs. -* gc: fix init of packages named main (thanks Gustavo Niemeyer), -* gob: make recursive map and slice types work, and other fixes. - tentative support for GobEncoder/GobDecoder interfaces. -* gobuilder: add -package flag to build external packages and -v for verbose. -* gofmt: exclude test file that is not legal Go. -* goinstall: protect against malicious filenames (thanks Roger Peppe). -* goyacc: provide -p flag to set prefix for names, documentation update. -* http: add cookie support (thanks Petar Maymounkov), - allow handlers to send non-chunked responses, - export ParseHTTPVersion, - expose Client's Transport, - use WriteProxy, - rename ClientTransport to Transport. -* http/cgi: new package. -* http/httptest: new package. -* image: add a decoding test for common file formats. -* io/ioutil: add TempDir. -* mime/multipart: Header changed from map to MIMEHeader -* path/filepath: new OS-specific path support (thanks Gustavo Niemeyer). -* reflect: add PtrTo, add Value.Addr (old Addr is now UnsafeAddr). -* runtime: use kernel-supplied compare-and-swap on linux/arm. -* spec: minor clarification of scope rule for functions. -* sync/atomic: new package to expose atomic operations. -* syscall: regenerate zerrors_freebsd_amd64.go (thanks Mikio Hara), - work around FreeBSD execve kernel bug (thanks Devon H. O'Dell). -* template: document the delimiters. -* testing: run GC before each benchmark run (thanks Roger Peppe). -* unsafe: fix the documentation. -* websocket: use httptest.Server for tests (thanks Robert Hencke). -* xml: permit nested directives (thanks Chris Dollin). -- -
-This release includes changes to the http package and a small language change. -Your code will require changes if it manipulates http Headers or omits the -condition in if statements. - -The new http.Header type replaces map[string]string in the Header and Trailer -fields of http.Request and http.Response. -A Header value can be manipulated via its Get, Set, Add, and Del methods. -See http://golang.org/pkg/http/#Header - -The condition is now mandatory in if statements. -Previously it would default to true, as in switch and for statements. -This code is now illegal: - if x := foo(); { - // code that is always executed - } -The same effect can be achieved like this: - if x := foo(); true { - // code - } -Or, in a simpler form: - { - x := foo() - // code - } - -Other changes: -* 6l: new -Hwindowsgui flag allows to build windows gui pe (thanks Alex Brainman), - pe fixes (thanks Wei Guangjing). -* 8l, 6l: allow for more os threads to be created on Windows (thanks Alex Brainman), -* build: reduce the use of subshells in recursive make, and - remove unused NaCl conditional from make.bash (thanks Dave Cheney). -* codereview: fix clpatch with empty diffs (thanks Gustavo Niemeyer). -* compress/bzip2: add package. -* compress/lzw: implement a decoder. -* crypto/openpgp: add package. -* crypto/rand: add read buffer to speed up small requests (thanks Albert Strasheim). -* crypto/rsa: left-pad OAEP results when needed. -* crypto/tls: make protocol negotiation failure fatal. -* fmt: stop giving characters to the Scan method of Scanner when we hit a newline in Scanln. -* gc: interface error message fixes, - make string const comparison unsigned (thanks Jeff R. Allen). -* go spec: minor clarification on channel types. -* go/ast, parser: condition in if statement is mandatory. -* gob: compute information about a user's type once. - protect against pure recursive types. -* godoc: accept symbolic links as path names provided to -path, - add robots.txt, log errors when reading filter files. -* html: tokenize HTML comments. -* http: add proxy support (thanks Yasuhiro Matsumoto), - implement with net/textproto (thanks Petar Maymounkov), - send full URL in proxy requests, - introduce start of Client and ClientTransport. -* image/png: support for more formats (thanks Mikael Tillenius). -* json: only use alphanumeric tags, - use base64 to encode []byte (thanks Roger Peppe). -* ld: detect stack overflow due to NOSPLIT, drop rpath, support weak symbols. -* misc/dashboard/builder: talk to hg with utf-8 encoding. -* misc/dashboard: notify golang-dev on build failure. -* net: *netFD.Read to return os.EOF on eof under windows (thanks Alex Brainman), - add IPv4 multicast to UDPConn (thanks Dave Cheney), - more accurate IPv4-in-IPv6 API test (thanks Mikio Hara), - reject invalid net:proto network names (thanks Olivier Antoine). -* netchan: allow use of arbitrary connections (thanks Roger Peppe). -* os: add ENODATA and ENOTCONN (thanks Albert Strasheim). -* reflect: add a couple of sentences explaining how Methods operate, - add a secret method to ArrayOrSliceType to ensure it's only implemented by arrays and slices, - add pointer word to CommonType (placeholder for future work). -* runtime-gdb.py: gdb pretty printer for go strings properly handles length. -* runtime: various bug fixes, more complete stack traces, - record $GOROOT_FINAL for runtime.GOROOT. -* spec: delete incorrect mention of selector working on pointer to interface type. -* sync: add Cond (thanks Gustavo Niemeyer). -* syscall: add MCL_* flags for mlockall (thanks Albert Strasheim), - implement chmod() for win32 (thanks Yasuhiro Matsumoto). -* test/bench: update timings for new GC. -* testing: rename cmdline flags to avoid conflicts (thanks Gustavo Niemeyer). -* textproto: introduce Header type (thanks Petar Maymounkov). -* websocket: use new interface to access Header. -- -
-This release includes changes to the io, os, and template packages. -You may need to update your code. - -The io.ReadByter and io.ReadRuner interface types have been renamed to -io.ByteReader and io.RuneReader respectively. - -The os package's ForkExec function has been superseded by the new StartProcess -function and an API built around the Process type: - http://golang.org/pkg/os/#Process - -The order of arguments to template.Execute has been reversed to be consistent -the notion of "destination first", as with io.Copy, fmt.Fprint, and others. - -Gotest now works for package main in directories using Make.cmd-based makefiles. - -The memory allocation runtime problems from the last release are not completely -fixed. The virtual memory exhaustion problems encountered by people using -ulimit -v have been fixed, but there remain known garbage collector problems -when using GOMAXPROCS > 1. - -Other changes: -* 5l: stopped generating 64-bit eor. -* 8l: more work on plan9 support (thanks Yuval Pavel Zholkover). -* archive/zip: handle files with data descriptors. -* arm: working peep-hole optimizer. -* asn1: marshal true as 255, not 1. -* buffer.go: minor optimization, expanded comment. -* build: drop syslog on DISABLE_NET_TESTS=1 (thanks Gustavo Niemeyer), - allow clean.bash to work on fresh checkout, - change "all tests pass" message to be more obvious, - fix spaces in GOROOT (thanks Christopher Nielsen). -* bytes: fix bug in buffer.ReadBytes (thanks Evan Shaw). -* 5g: better int64 code, - don't use MVN instruction. -* cgo: don't run cgo when not compiling (thanks Gustavo Niemeyer), - fix _cgo_run timestamp file order (thanks Gustavo Niemeyer), - fix handling of signed enumerations (thanks Gustavo Niemeyer), - os/arch dependent #cgo directives (thanks Gustavo Niemeyer), - rename internal f to avoid conflict with possible C global named f. -* codereview: fix hgpatch on windows (thanks Yasuhiro Matsumoto), - record repository, base revision, - use cmd.communicate (thanks Yasuhiro Matsumoto). -* container/ring: replace Iter() with Do(). -* crypto/cipher: add resync open to OCFB mode. -* crypto/openpgp/armor: bug fixes. -* crypto/openpgp/packet: new subpackage. -* crypto/tls: load a chain of certificates from a file, - select best cipher suite, not worst. -* crypto/x509: add support for name constraints. -* debug/pe: ImportedSymbols fixes (thanks Wei Guangjing). -* doc/code: update to reflect that package names need not be unique. -* doc/codelab/wiki: a bunch of fixes (thanks Andrey Mirtchovski). -* doc/install: update for new versions of Mercurial. -* encoding/line: fix line returned after EOF. -* flag: allow hexadecimal (0xFF) and octal (0377) input for integer flags. -* fmt.Scan: scan binary-exponent floating format, 2.4p-3, - hexadecimal (0xFF) and octal (0377) integers. -* fmt: document %%; also %b for floating point. -* gc, ld: detect stale or incompatible object files, - package name main no longer reserved. -* gc: correct receiver in method missing error (thanks Lorenzo Stoakes), - correct rounding of denormal constants (thanks Eoghan Sherry), - select receive bug fix. -* go/printer, gofmt: smarter handling of multi-line raw strings. -* go/printer: line comments must always end in a newline, - remove notion of "Styler", remove HTML mode. -* gob: allow Decode(nil) and have it just discard the next value. -* godoc: use IsAbs to test for absolute paths (fix for win32) (thanks Yasuhiro Matsumoto), - don't hide package lookup error if there's no command with the same name. -* gotest: enable unit tests for main programs. -* http: add Server type supporting timeouts, - add pipelining to ClientConn, ServerConn (thanks Petar Maymounkov), - handle unchunked, un-lengthed HTTP/1.1 responses. -* io: add RuneReader. -* json: correct Marshal documentation. -* netchan: graceful handling of closed connection (thanks Graham Miller). -* os: implement new Process API (thanks Alex Brainman). -* regexp tests: make some benchmarks more meaningful. -* regexp: add support for matching against text read from RuneReader interface. -* rpc: make more tolerant of errors, properly discard values (thanks Roger Peppe). -* runtime: detect failed thread creation on Windows, - faster allocator, garbage collector, - fix virtual memory exhaustion, - implemented windows console ctrl handler (SIGINT) (thanks Hector Chu), - more detailed panic traces, line number work, - improved Windows callback handling (thanks Hector Chu). -* spec: adjust notion of Assignability, - allow import of packages named main, - clarification re: method sets of newly declared pointer types, - fix a few typos (thanks Anthony Martin), - fix Typeof() return type (thanks Gustavo Niemeyer), - move to Unicode 6.0. -* sync: diagnose Unlock of unlocked Mutex, - new Waitgroup type (thanks Gustavo Niemeyer). -* syscall: add SetsockoptIpMreq (thanks Dave Cheney), - add sockaddr_dl, sysctl with routing message support for darwin, freebsd (thanks Mikio Hara), - do not use NULL for zero-length read, write, - implement windows version of Fsync (thanks Alex Brainman), - make ForkExec acquire the ForkLock under windows (thanks Hector Chu), - make windows API return errno instead of bool (thanks Alex Brainman), - remove obsolete socket IO control (thanks Mikio Hara). -* template: add simple formatter chaining (thanks Kyle Consalus), - allow a leading '*' to indirect through a pointer. -* testing: include elapsed time in test output -* windows: replace remaining __MINGW32__ instances with _WIN32 (thanks Joe Poirier). -- -
-This release includes significant changes to channel operations and minor -changes to the log package. Your code will require modification if it uses -channels in non-blocking communications or the log package's Exit functions. - -Non-blocking channel operations have been removed from the language. -The equivalent operations have always been possible using a select statement -with a default clause. If a default clause is present in a select, that clause -will execute (only) if no other is ready, which allows one to avoid blocking on -a communication. - -For example, the old non-blocking send operation, - - if ch <- v { - // sent - } else { - // not sent - } - -should be rewritten as, - - select { - case ch <- v: - // sent - default: - // not sent - } - -Similarly, this receive, - - v, ok := <-ch - if ok { - // received - } else { - // not received - } - -should be rewritten as, - - select { - case v := <-ch: - // received - default: - // not received - } - -This change is a prelude to redefining the 'comma-ok' syntax for a receive. -In a later release, a receive expression will return the received value and an -optional boolean indicating whether the channel has been closed. These changes -are being made in two stages to prevent this semantic change from silently -breaking code that uses 'comma-ok' with receives. -There are no plans to have a boolean expression form for sends. - -Sends to a closed channel will panic immediately. Previously, an unspecified -number of sends would fail silently before causing a panic. - -The log package's Exit, Exitf, and Exitln functions have been renamed Fatal, -Fatalf, and Fatalln respectively. This brings them in line with the naming of -the testing package. - -The port to the "tiny" operating system has been removed. It is unmaintained -and untested. It was a toy to show that Go can run on raw hardware and it -served its purpose. The source code will of course remain in the repository -history, so it could be brought back if needed later. - -This release also changes some of the internal structure of the memory -allocator in preparation for other garbage collector changes. -If you run into problems, please let us know. -There is one known issue that we are aware of but have not debugged yet: - http://code.google.com/p/go/issues/detail?id=1464&. - -Other changes in this release: -* 5l: document -F, force it on old ARMs (software floating point emulation) -* 6g: fix registerization of temporaries (thanks Eoghan Sherry), - fix uint64(uintptr(unsafe.Pointer(&x))). -* 6l: Relocate CMOV* instructions (thanks Gustavo Niemeyer), - windows/amd64 port (thanks Wei Guangjing). -* 8l: add PE dynexport, emit DWARF in Windows PE, and - code generation fixes (thanks Wei Guangjing). -* bufio: make Flush a no-op when the buffer is empty. -* bytes: Add Buffer.ReadBytes, Buffer.ReadString (thanks Evan Shaw). -* cc: mode to generate go-code for types and variables. -* cgo: define CGO_CFLAGS and CGO_LDFLAGS in Go files (thanks Gustavo Niemeyer), - windows/386 port (thanks Wei Guangjing). -* codereview: fix windows (thanks Hector Chu), - handle file patterns better, - more ASCII vs. Unicode nonsense. -* crypto/dsa: add support for DSA. -* crypto/openpgp: add s2k. -* crypto/rand: use defer to unlock mutex (thanks Anschel Schaffer-Cohen). -* crypto/rsa: correct docstring for SignPKCS1v15. -* crypto: add package, a common place to store identifiers for hash functions. -* doc/codelab/wiki: update to work with template changes, add to run.bash. -* doc/spec: clarify address operators. -* ebnflint: exit with non-zero status on error. -* encoding/base32: new package (thanks Miek Gieben). -* encoding/line: make it an io.Reader too. -* exec: use custom error for LookPath (thanks Gustavo Niemeyer). -* fmt/doc: define width and precision for strings. -* gc: clearer error for struct == struct, - fix send precedence, - handle invalid name in type switch, - special case code for single-op blocking and non-blocking selects. -* go/scanner: fix build (adjust scanner EOF linecount). -* gob: better debugging, commentary, - make nested interfaces work, - report an error when encoding a non-empty struct with no public fields. -* godoc: full text index for whitelisted non-Go files, - show line numbers for non-go files (bug fix). -* gofmt -r: match(...) arguments may be nil; add missing guards. -* govet: add Panic to the list of functions. -* http: add host patterns (thanks Jose Luis Vázquez González), - follow relative redirect in Get. -* json: handle capital floating point exponent (1E100) (thanks Pieter Droogendijk). -* ld: add -I option to set ELF interpreter, - more robust decoding of reflection type info in generating dwarf. -* lib9: update to Unicode 6.0.0. -* make.bash: stricter selinux test (don't complain unless it is enabled). -* misc/vim: Import/Drop commands (thanks Gustavo Niemeyer), - set 'syntax sync' to a large value (thanks Yasuhiro Matsumoto). -* net: fix race condition in test, - return cname in LookupHost. -* netchan: avoid race condition in test, - fixed documentation for import (thanks Anschel Schaffer-Cohen). -* os: add ETIMEDOUT (thanks Albert Strasheim). -* runtime: generate Go defs for C types, - implementation of callback functions for windows (thanks Alex Brainman), - make Walk web browser example work (thanks Hector Chu), - make select fairer, - prefer fixed stack allocator over general memory allocator, - simpler heap map, memory allocation. -* scanner: fix Position returned by Scan, Pos, - don't read ahead in Init. -* suffixarray: use binary search for both ends of Lookup (thanks Eric Eisner). -* syscall: add missing network interface constants (thanks Mikio Hara). -* template: treat map keys as zero, not non-existent (thanks Roger Peppe). -* time: allow canceling of After events (thanks Roger Peppe), - support Solaris zoneinfo directory. -* token/position: added SetLinesForContent. -* unicode: update to unicode 6.0.0. -* unsafe: add missing case to doc for Pointer. -- -
-This release removes the float and complex types from the language. - -The default type for a floating point literal is now float64, and -the default type for a complex literal is now complex128. - -Existing code that uses float or complex must be rewritten to -use explicitly sized types. - -The two-argument constructor cmplx is now spelled complex. -- -
-The 5g (ARM) compiler now has registerization enabled. If you discover it -causes bugs, use 5g -N to disable the registerizer and please let us know. - -The xml package now allows the extraction of nested XML tags by specifying -struct tags of the form "parent>child". See the XML documentation for an -example: http://golang.org/pkg/xml/ - -* 5a, 5l, 6a, 6l, 8a, 8l: handle out of memory, large allocations (thanks Jeff R. Allen). -* 8l: pe changes (thanks Alex Brainman). -* arm: fixes and improvements. -* cc: fix vlong condition. -* cgo: add complex float, complex double (thanks Sebastien Binet), - in _cgo_main.c define all provided symbols as functions. -* codereview: don't mail change lists with no files (thanks Ryan Hitchman). -* crypto/cipher: add OFB mode. -* expvar: add Float. -* fmt: document %X of string, []byte. -* gc, runtime: make range on channel safe for multiple goroutines. -* gc: fix typed constant declarations (thanks Anthony Martin). -* go spec: adjust language for constant typing. -* go/scanner: Make Init take a *token.File instead of a *token.FileSet. -* godoc: bring back "indexing in progress" message, - don't double HTML-escape search result snippets, - enable qualified identifiers ("math.Sin") as query strings again, - peephole optimization for generated HTML, - remove tab before formatted section. -* gofmt, go/printer: do not insert extra line breaks where they may break the code. -* http: fix Content-Range and Content-Length in response (thanks Clement Skau), - fix scheme-relative URL parsing; add ParseRequestURL, - handle HEAD requests correctly, - support for relative URLs. -* math: handle denormalized numbers in Frexp, Ilogb, Ldexp, and Logb (thanks Eoghan Sherry). -* net, syscall: return source address in Recvmsg (thanks Albert Strasheim). -* net: add LookupAddr (thanks Kyle Lemons), - add unixpacket (thanks Albert Strasheim), - avoid nil dereference if /etc/services can't be opened (thanks Corey Thomasson), - implement windows timeout (thanks Wei Guangjing). -* netchan: do not block sends; implement flow control (thanks Roger Peppe). -* regexp: reject bare '?'. (thanks Ben Lynn) -* runtime/cgo: don't define crosscall2 in dummy _cgo_main.c. -* runtime/debug: new package for printing stack traces from a running goroutine. -* runtime: add per-pause gc stats, - fix arm reflect.call boundary case, - print signal information during panic. -* spec: specify that int and uint have the same size. -* syscall: correct WSTOPPED on OS X, - correct length of GNU/Linux abstract Unix domain sockaddr, - correct length of SockaddrUnix. -* tutorial: make stdin, stdout, stderr work on Windows. -* windows: implement exception handling (thanks Hector Chu). -- -
-The json, gob, and template packages have changed, and code that uses them -may need to be updated after this release. They will no longer read or write -unexported struct fields. When marshaling a struct with json or gob the -unexported fields will be silently ignored. Attempting to unmarshal json or -gob data into an unexported field will generate an error. Accessing an -unexported field from a template will cause the Execute function to return -an error. - -Godoc now supports regular expression full text search, and this -functionality is now available on golang.org. - -Other changes: -* arm: initial cut at arm optimizer. -* bytes.Buffer: Fix bug in UnreadByte. -* cgo: export unsafe.Pointer as void*, fix enum const conflict, - output alignment fix (thanks Gustavo Niemeyer). -* crypto/block: mark as deprecated. -* crypto/openpgp: add error and armor. -* crypto: add twofish package (thanks Berengar Lehr). -* doc/spec: remove Maxalign from spec. -* encoding/line: new package for reading lines from an io.Reader. -* go/ast: correct end position for Index and TypeAssert expressions. -* gob: make (en|dec)code(Ui|I)nt methods rather than functions. -* godefs: better handling of enums. -* gofmt: don't attempt certain illegal rewrites, - rewriter matches apply to expressions only. -* goinstall: preliminary support for cgo packages (thanks Gustavo Niemeyer). -* hg: add cgo/_cgo_* to .hgignore. -* http: fix text displayed in Redirect. -* ld: fix exported dynamic symbols on Mach-O, - permit a Mach-O symbol to be exported in the dynamic symbol table. -* log: add methods for exit and panic. -* net: use closesocket api instead of CloseHandle on Windows (thanks Alex Brainman). -* netchan: make fields exported for gob change. -* os: add Sync to *File, wraps syscall.Fsync. -* runtime/cgo: Add callbacks to support SWIG. -* runtime: Restore scheduler stack position if cgo callback panics. -* suffixarray: faster creation algorithm (thanks Eric Eisner). -* syscall: fix mksysnum_linux.sh (thanks Anthony Martin). -* time.NewTicker: panic for intervals <= 0. -* time: add AfterFunc to call a function after a duration (thanks Roger Peppe), - fix tick accuracy when using multiple Tickers (thanks Eoghan Sherry).- -
-This release includes several fixes and changes: - -* build: Make.pkg: use installed runtime.h for cgo. -* cgo: disallow use of C.errno. -* crypto/cipher: fix OCFB, - make NewCBCEncrypter return BlockMode. -* doc: 6l: fix documentation of -L flag, - add golanguage.ru to foreign-language doc list, - effective go: explain the effect of repanicking better, - update Effective Go for template API change, - update contribution guidelines to prefix the change description. -* encoding/binary: reject types with implementation-dependent sizes (thanks Patrick Gavlin). -* exp/evalsimple fix handling of slices like s[:2] (thanks Sebastien Binet). -* fmt: made format string handling more efficient, - normalize processing of format string. -* gc: return constant floats for parts of complex constants (thanks Anthony Martin), - rewrite complex /= to l = l / r (thanks Patrick Gavlin), - fix &^=. -* go/ast: provide complete node text range info. -* gob: generate a better error message in one confusing place. -* godoc: fix godoc -src (thanks Icarus Sparry). -* goinstall: add -clean flag (thanks Kyle Lemons), - add checkout concept (thanks Caine Tighe), - fix -u for bzr (thanks Gustavo Niemeyer). -* http: permit empty Reason-Phrase in response Status-Line. -* io: fix Copyn EOF handling. -* net: fix close of Listener (thanks Michael Hoisie). -* regexp: fix performance bug, make anchored searches fail fast, - fix prefix bug. -* runtime/cgo: fix stackguard on FreeBSD/amd64 (thanks Anthony Martin). -* strconv: atof: added 'E' as valid token for exponent (thanks Stefan Nilsson), - update ftoa comment for 'E' and 'G'. -* strings: fix description of FieldsFunc (thanks Roger Peppe). -* syscall: correct Linux Splice definition, - make Access second argument consistently uint32. -- -
-A small release this week. The most significant change is that some -outstanding cgo issues were resolved. - -* cgo: handle references to symbols in shared libraries. -* crypto/elliptic: add serialisation and key pair generation. -* crypto/hmac: add HMAC-SHA256 (thanks Anthony Martin). -* crypto/tls: add ECDHE support ("Elliptic Curve Diffie Hellman Ephemeral"), - add support code for generating handshake scripts for testing. -* darwin, freebsd: ignore write failure (during print, panic). -* exp/draw: remove Border function. -* expvar: quote StringFunc output, same as String output. -* hash/crc64: fix typo in Sum. -* ld: allow relocations pointing at ELF .bss symbols, ignore stab symbols. -* misc/cgo/life: fix, add to build. -* regexp: add HasMeta, HasOperator, and String methods to Regexp. -* suffixarray: implemented FindAllIndex regexp search. -* test/bench: update numbers for regex-dna after speedup to regexp. -* time: explain the formats a little better. -- -
-Package crypto/cipher has been started, to replace crypto/block. -As part of the changes, rc4.Cipher's XORKeyStream method signature has changed from - XORKeyStream(buf []byte) -to - XORKeyStream(dst, src []byte) -to implement the cipher.Stream interface. If you use crypto/block, you'll need -to switch to crypto/cipher once it is complete. - -Package smtp's StartTLS now takes a *tls.Config argument. - -Package reflect's ArrayCopy has been renamed to Copy. There are new functions -Append and AppendSlice. - -The print/println bootstrapping functions now write to standard error. -To write to standard output, use fmt.Print[ln]. - -A new tool, govet, has been added to the Go distribution. Govet is a static -checker for Go programs. At the moment, and for the foreseeable future, -it only checks arguments to print calls. - -The cgo tool for writing Go bindings for C code has changed so that it no -longer uses stub .so files (like cgo_stdio.so). Cgo-based packages using the -standard Makefiles should build without any changes. Any alternate build -mechanisms will need to be updated. - -The C and Go compilers (6g, 6c, 8g, 8c, 5g, 5c) now align structs according to -the maximum alignment of the fields they contain; previously they aligned -structs to word boundaries. This may break non-cgo-based code that attempts to -mix C and Go. - -NaCl support has been removed. The recent linker changes broke NaCl support -a month ago, and there are no known users of it. -If necessary, the NaCl code can be recovered from the repository history. - -* 5g/8g, 8l, ld, prof: fix output of 32-bit values (thanks Eoghan Sherry). -* [68]l and runtime: GDB support for interfaces and goroutines. -* 6l, 8l: support for linking ELF and Mach-O .o files. -* all: simplify two-variable ranges with unused second variable (thanks Ryan Hitchman). -* arm: updated soft float support. -* codereview: keep quiet when not in use (thanks Eoghan Sherry). -* compress/flate: implement Flush, equivalent to zlib's Z_SYNC_FLUSH. -* crypto/tls: use rand.Reader in cert generation example (thanks Anthony Martin). -* dashboard: fix project tag filter. -* debug/elf, debug/macho: add ImportedLibraries, ImportedSymbols. -* doc/go_mem: goroutine exit is not special. -* event.go: another print glitch from gocheck. -* gc: bug fixes, - syntax error for incomplete chan type (thanks Ryan Hitchman). -* go/ast: fix ast.Walk. -* gob: document the byte count used in the encoding of values, - fix bug sending zero-length top-level slices and maps, - Register should use the original type, not the indirected one. -* godashboard: support submitting projects with non-ascii names (thanks Ryan Hitchman) -* godefs: guard against structs with pad fields -* godoc: added textual search, to enable use -fulltext flag. -* gofmt: simplify "x, _ = range y" to "x = range y". -* gopack: allow ELF/Mach-O objects in .a files without clearing allobj. -* go/token,scanner: fix comments so godoc aligns properly. -* govet: on error continue to the next file (thanks Christopher Wedgwood). -* html: improved parsing. -* http: ServeFile handles Range header for partial requests. -* json: check for invalid UTF-8. -* ld: allow .o files with no symbols, - reading of ELF object files, - reading of Mach-O object files. -* math: change float64 bias constant from 1022 to 1023 (thanks Eoghan Sherry), - rename the MinFloat constant to SmallestNonzeroFloat. -* nm: silently ignore .o files in .a files. -* os: fix test of RemoveAll. -* os/inotify: new package (thanks Balazs Lecz). -* os: make MkdirAll work with symlinks (thanks Ryan Hitchman). -* regexp: speed up by about 30%; also simplify code for brackets. -* runtime/linux/386: set FPU to 64-bit precision. -* runtime: remove paranoid mapping at 0. -* suffixarray: add Bytes function. -* syscall: add network interface constants for linux/386, linux/amd64 (thanks Mikio Hara). -* syscall/windows: restrict access rights param of OpenProcess(), - remove \r and \n from error messages (thanks Alex Brainman). -* test/bench: fixes to timing.sh (thanks Anthony Martin). -* time: fix bug in Ticker: shutdown using channel rather than memory. -* token/position: provide FileSet.File, provide files iterator. -* xml: disallow invalid Unicode code points (thanks Nigel Kerr). -- -
-This release includes some package changes. If you use the crypto/tls or -go/parser packages your code may require changes. - -The crypto/tls package's Dial function now takes an additional *Config -argument. Most uses will pass nil to get the same default behavior as before. -See the documentation for details: - http://golang.org/pkg/crypto/tls/#Config - http://golang.org/pkg/crypto/tls/#Dial - -The go/parser package's ParseFile function now takes a *token.FileSet as its -first argument. This is a pointer to a data structure used to store -position information. If you don't care about position information you -can pass "token.NewFileSet()". See the documentation for details: - http://golang.org/pkg/go/parser/#ParseFile - -This release also splits the patent grant text out of the LICENSE file into a -separate PATENTS file and changes it to be more like the WebM grant. -These clarifications were made at the request of the Fedora project. - -Other changes: -* [68]l: generate debug info for builtin structured types, prettyprinting in gdb. -* 8l: add dynimport to import table in Windows PE (thanks Wei Guangjing). -* 8l, runtime: fix Plan 9 386 build (thanks Yuval Pavel Zholkover). -* all: fix broken calls to Printf etc. -* bufio: make Reader.Read implement io.Reader semantics (thanks Roger Peppe). -* build: allow archiver to be specified by HOST_AR (thanks Albert Strasheim). -* bytes: add Buffer.UnreadRune, Buffer.UnreadByte (thanks Roger Peppe). -* crypto/tls: fix build of certificate generation example (thanks Christian Himpel). -* doc/install: describe GOHOSTOS and GOHOSTARCH. -* errchk: accept multiple source files (thanks Eoghan Sherry). -* exec.LookPath: return os.PathError instad of os.ENOENT (thanks Michael Hoisie).. -* flag: fix format error in boolean error report, - handle multiple calls to flag.Parse. -* fmt: add %U format for standard Unicode representation of code point values. -* gc: fix method offsets of anonymous interfaces (thanks Eoghan Sherry), - skip undefined symbols in import . (thanks Eoghan Sherry). -* go/scanner: remove Tokenize - was only used in tests -* gobuilder: add buildroot command-line flag (thanks Devon H. O'Dell). -* html: unescape numeric entities (thanks Ryan Hitchman). -* http: Add EncodeQuery, helper for constructing query strings. -* ld: fix dwarf decoding of 64-bit reflect values (thanks Eoghan Sherry). -* math: improve accuracy of Exp2 (thanks Eoghan Sherry). -* runtime: add Goroutines (thanks Keith Rarick). -* sync: small naming fix for armv5 (thanks Dean Prichard). -* syscall, net: Add Recvmsg and Sendmsg on Linux (thanks Albert Strasheim). -* time: make After use fewer goroutines and host processes (thanks Roger Peppe). -- -
-Several package changes in this release may require you to update your code if -you use the bytes, template, or utf8 packages. In all cases, any outdated code -will fail to compile rather than behave erroneously. - -The bytes package has changed. Its Add and AddByte functions have been removed, -as their functionality is provided by the recently-introduced built-in function -"append". Any code that uses them will need to be changed: -s = bytes.Add(s, b) -> s = append(s, b...) -s = bytes.AddByte(b, c) -> s = append(s, b) -s = bytes.Add(nil, c) -> append([]byte(nil), c) - -The template package has changed. Your code will need to be updated if it calls -the HTMLFormatter or StringFormatter functions, or implements its own formatter -functions. The function signature for formatter types has changed to: - func(wr io.Writer, formatter string, data ...interface{}) -to allow multiple arguments to the formatter. No templates will need updating. -See the change for examples: - http://code.google.com/p/go/source/detail?r=2c2be793120e - -The template change permits the implementation of multi-word variable -instantiation for formatters. Before one could say - {field} -or - {field|formatter} -Now one can also say - {field1 field2 field3} -or - {field1 field2 field3|formatter} -and the fields are passed as successive arguments to the formatter, -by analogy to fmt.Print. - -The utf8 package has changed. The order of EncodeRune's arguments has been -reversed to satisfy the convention of "destination first". -Any code that uses EncodeRune will need to be updated. - -Other changes: -* [68]l: correct dwarf location for globals and ranges for arrays. -* big: fix (*Rat) SetFrac64(a, b) when b < 0 (thanks Eoghan Sherry). -* compress/flate: fix typo in comment (thanks Mathieu Lonjaret). -* crypto/elliptic: use a Jacobian transform for better performance. -* doc/code.html: fix reference to "gomake build" (thanks Anschel Schaffer-Cohen). -* doc/roadmap: update gdb status. -* doc/spec: fixed some omissions and type errors. -* doc: some typo fixes (thanks Peter Mundy). -* exp/eval: build fix for parser.ParseFile API change (thanks Anschel Schaffer-Cohen). -* fmt: Scan accepts Inf and NaN, - allow "% X" as well as "% x". -* go/printer: preserve newlines in func parameter lists (thanks Jamie Gennis). -* http: consume request body before next request. -* log: ensure writes are atomic (thanks Roger Peppe). -* path: Windows support for Split (thanks Benny Siegert). -* runtime: fix SysFree to really free memory on Windows (thanks Alex Brainman), - parallel definitions in Go for all C structs. -* sort: avoid overflow in pivot calculation, - reduced stack depth to lg(n) in quickSort (thanks Stefan Nilsson). -* strconv: Atof on Infs and NaNs. -- -
-This release includes a backwards-incompatible package change to the -sort.Search function (introduced in the last release). -See the change for details and examples of how you might change your code: - http://code.google.com/p/go/source/detail?r=102866c369 - -* build: automatically #define _64BIT in 6c. -* cgo: print required space after parameter name in wrapper function. -* crypto/cipher: new package to replace crypto/block (thanks Adam Langley). -* crypto/elliptic: new package, implements elliptic curves over prime fields (thanks Adam Langley). -* crypto/x509: policy OID support and fixes (thanks Adam Langley). -* doc: add link to codewalks, - fix recover() documentation (thanks Anschel Schaffer-Cohen), - explain how to write Makefiles for commands. -* exec: enable more tests on windows (thanks Alex Brainman). -* gc: adjustable hash code in typecheck of composite literals - (thanks to vskrap, Andrey Mirtchovski, and Eoghan Sherry). -* gc: better error message for bad type in channel send (thanks Anthony Martin). -* godoc: bug fix in relativePath, - compute search index for all file systems under godoc's observation, - use correct time stamp to indicate accuracy of search result. -* index/suffixarray: use sort.Search. -* net: add ReadFrom and WriteTo windows version (thanks Wei Guangjing). -* reflect: remove unnecessary casts in Get methods. -* rpc: add RegisterName to allow override of default type name. -* runtime: free memory allocated by windows CommandLineToArgv (thanks Alex Brainman). -* sort: simplify Search (thanks Roger Peppe). -* strings: add LastIndexAny (thanks Benny Siegert). -- -
-The birthday release includes a new Search capability inside the sort package. -It takes an unusual but very general and easy-to-use approach to searching -arbitrary indexable sorted data. See the documentation for details: - http://golang.org/pkg/sort/#Search - -The ARM port now uses the hardware floating point unit (VFP). It still has a -few bugs, mostly around conversions between unsigned integer and floating-point -values, but it's stabilizing. - -In addition, there have been many smaller fixes and updates: - -* 6l: generate dwarf variable names with disambiguating suffix. -* container/list: make Remove return Value of removed element. - makes it easier to remove first or last item. -* crypto: add cast5 (default PGP cipher), - switch block cipher methods to be destination first. -* crypto/tls: use pool building for certificate checking -* go/ast: change embedded token.Position fields to named fields - (preparation for a different position representation) -* net: provide public access to file descriptors (thanks Keith Rarick) -* os: add Expand function to evaluate environment variables. -* path: add Glob (thanks Benny Siegert) -* runtime: memequal optimization (thanks Graham Miller) - prefix all external symbols with "runtime·" to avoid - conflicts linking with external C libraries. -- -
-This release includes a language change: the new built-in function, append. -Append makes growing slices much simpler. See the spec for details: - http://golang.org/doc/go_spec.html#Appending_and_copying_slices - -Other changes: -* 8l: pe generation fixes (thanks Alex Brainman). -* doc: Effective Go: append and a few words about "..." args. -* build: fiddle with make variables. -* codereview: fix sync and download in Python 2.7 (thanks Fazlul Shahriar). -* debug/pe, cgo: add windows support (thanks Wei Guangjing). -* go/ast: add Inspect function for easy AST inspection w/o a visitor. -* go/printer: do not remove parens around composite literals starting with - a type name in control clauses. -* go/scanner: bug fixes, revisions, and more tests. -* gob: several fixes and documentation updates. -* godoc: bug fix (bug introduced with revision 3ee58453e961). -* gotest: print empty benchmark list in a way that gofmt will leave alone. -* http server: correctly respond with 304 NotModified (thanks Michael Hoisie). -* kate: update list of builtins (thanks Evan Shaw). -* libutf: update to Unicode 5.2.0 to match pkg/unicode (thanks Anthony Martin). -* misc/bbedit: update list of builtins (thanks Anthony Starks). -* misc/vim: update list of builtins. -* mkrunetype: install a Makefile and tweak it slightly so it can be built. -* netchan: fix locking bug. -* pidigits: minor improvements (thanks Evan Shaw). -* rpc: fix client deadlock bug. -* src: use append where appropriate (often instead of vector). -* strings: add Contains helper function (thanks Brad Fitzpatrick). -* syscall: SIO constants for Linux (thanks Albert Strasheim), - Stat(path) on windows (thanks Alex Brainman). -* test/ken/convert.go: add conversion torture test. -* testing: add Benchmark (thanks Roger Peppe). -- -
-*** This release changes the encoding used by package gob. - If you store gobs on disk, see below. *** - -The ARM port (5g) now passes all tests. The optimizer is not yet enabled, and -floating point arithmetic is performed entirely in software. Work is underway -to address both of these deficiencies. - -The syntax for arrays, slices, and maps of composite literals has been -simplified. Within a composite literal of array, slice, or map type, elements -that are themselves composite literals may elide the type if it is identical to -the outer literal's element type. For example, these expressions: - [][]int{[]int{1, 2, 3}, []int{4, 5}} - map[string]Point{"x": Point{1.5, -3.5}, "y": Point{0, 0}} -can be simplified to: - [][]int{{1, 2, 3}, {4, 5}} - map[string]Point{"x": {1.5, -3.5}, "y": {0, 0}} -Gofmt can make these simplifications mechanically when invoked with the -new -s flag. - -The built-in copy function can now copy bytes from a string value to a []byte. -Code like this (for []byte b and string s): - for i := 0; i < len(s); i++ { - b[i] = s[i] - } -can be rewritten as: - copy(b, s) - -The gob package can now encode and decode interface values containing types -registered ahead of time with the new Register function. These changes required -a backwards-incompatible change to the wire format. Data written with the old -version of the package will not be readable with the new one, and vice versa. -(Steps were made in this change to make sure this doesn't happen again.) -We don't know of anyone using gobs to create permanent data, but if you do this -and need help converting, please let us know, and do not update to this release -yet. We will help you convert your data. - -Other changes: -* 5g, 6g, 8g: generate code for string index instead of calling function. -* 5l, 6l, 8l: introduce sub-symbols. -* 6l/8l: global and local variables and type info. -* Make.inc: delete unnecessary -fno-inline flag to quietgcc. -* arm: precise float64 software floating point, bug fixes. -* big: arm assembly, faster software mulWW, divWW. -* build: only print "You need to add foo to PATH" when needed. -* container/list: fix Remove bug and use pointer to self as identifier. -* doc: show page title in browser title bar, - update roadmap. -* encoding/binary: give LittleEndian, BigEndian specific types. -* go/parser: consume auto-inserted semi when calling ParseExpr(). -* gobuilder: pass GOHOSTOS and GOHOSTARCH to build, - write build and benchmarking logs to disk. -* goinstall: display helpful message when encountering a cgo package, - fix test for multiple package names (thanks Fazlul Shahriar). -* gotest: generate correct gofmt-formatted _testmain.go. -* image/png: speed up paletted encoding ~25% (thanks Brad Fitzpatrick). -* misc: update python scripts to specify python2 as python3 is now "python". -* net: fix comment on Dial to mention unix/unixgram. -* rpc: expose Server type to allow multiple RPC Server instances. -* runtime: print unknown types in panic. -* spec: append built-in (not yet implemented). -* src: gofmt -s -w src misc. - update code to use copy-from-string. -* test/bench: update numbers. -* websocket: fix short Read. -- -
-This release removes the log package's deprecated functions. -Code that has not been updated to use the new interface will break. -See the previous release notes for details: - http://golang.org/doc/devel/release.html#2010-10-13 - -Also included are major improvements to the linker. It is now faster, -uses less memory, and more parallelizable (but not yet parallel). - -The nntp package has been removed from the standard library. -Its new home is the nntp-go project at Google Code: - http://code.google.com/p/nntp-go -You can install it with goinstall: - goinstall nntp-go.googlecode.com/hg/nntp -And import it in your code like so: - import "nntp-go.googlecode.com/hg/nntp" - -Other changes: -* 6g: avoid too-large immediate constants. -* 8l, runtime: initial support for Plan 9 (thanks Yuval Pavel Zholkover). -* 6l, 8l: more improvements on exporting debug information (DWARF). -* arm: code gen fixes. Most tests now pass, except for floating point code. -* big: add random number generation (thanks Florian Uekermann). -* gc: keep track of real actual type of identifiers, - report that shift must be unsigned integer, - select receive with implicit conversion. -* goplay: fix to run under windows (thanks Yasuhiro Matsumoto). -* http: do not close connection after sending HTTP/1.0 request. -* netchan: add new method Hangup to terminate transmission on a channel. -* os: change TestForkExec so it can run on windows (thanks Yasuhiro Matsumoto). -* runtime: don't let select split stack. -* syscall/arm: correct 64-bit system call arguments. -- -
-This release includes changes to the log package, the removal of exp/iterable, -two new tools (gotry and goplay), one small language change, and many other -changes and fixes. If you use the log or iterable packages, you need to make -changes to your code. - -The log package has changed. Loggers now have only one output, and output to -standard error by default. The names have also changed, although the old names -are still supported. They will be deleted in the next release, though, so it -would be good to update now if you can. For most purposes all you need to do -is make these substitutions: - log.Stderr -> log.Println or log.Print - log.Stderrf -> log.Printf - log.Crash -> log.Panicln or log.Panic - log.Crashf -> log.Panicf - log.Exit -> log.Exitln or log.Exit - log.Exitf -> log.Exitf (no change) -Calls to log.New() must drop the second argument. -Also, custom loggers with exit or panic properties will need to be reworked. -For full details, see the change description: - http://code.google.com/p/go/source/detail?r=d8a3c7563d - -The language change is that uses of pointers to interface values no longer -automatically dereference the pointer. A pointer to an interface value is more -often a beginner's bug than correct code. - -The package exp/iterable has been removed. It was an interesting experiment, -but it encourages writing inefficient code and has outlived its utility. - -The new tools: -* gotry: an exercise in reflection and an unusual tool. Run 'gotry' for details. -* goplay: a stand-alone version of the Go Playground. See misc/goplay. - -Other changes: -* 6l: Mach-O fixes, and fix to work with OS X nm/otool (thanks Jim McGrath). -* [568]a: correct line numbers for statements. -* arm: code generation and runtime fixes, - adjust recover for new reflect.call, - enable 6 more tests after net fix. -* big: fix panic and round correctly in Rat.FloatString (thanks Anthony Martin). -* build: Make.cmd: remove $(OFILES) (thanks Eric Clark), - Make.pkg: remove .so before installing new one, - add GOHOSTOS and GOHOSTARCH environment variables. -* crypto/tls: better error messages for certificate issues, - make SetReadTimeout work. -* doc: add Sydney University video, - add The Expressiveness of Go talk. -* exp/draw/x11: support X11 vendors other than "The X.Org Foundation". -* expvar: add (*Int).Set (thanks Sam Thorogood). -* fmt: add Errorf helper function, - allow %d on []byte. -* gc: O(1) string comparison when lengths differ, - various bug fixes. -* http: return the correct error if a header line is too long. -* image: add image.Tiled type, the Go equivalent of Plan 9's repl bit. -* ld: be less picky about bad line number info. -* misc/cgo/life: fix for new slice rules (thanks Graham Miller). -* net: allow _ in DNS names. -* netchan: export before import when testing, and - zero out request to ensure correct gob decoding. (thanks Roger Peppe). -* os: make tests work on windows (thanks Alex Brainman). -* runtime: bug fix: serialize mcache allocation, - correct iteration of large map values, - faster strequal, memequal (thanks Graham Miller), - fix argument dump in traceback, - fix tiny build. -* smtp: new package (thanks Evan Shaw). -* syscall: add sockaddr_ll support for linux/386, linux/amd64 (thanks Mikio Hara), - add ucred structure for SCM_CREDENTIALS over UNIX sockets. (thanks Albert Strasheim). -* syscall: implement WaitStatus and Wait4() for windows (thanks Wei Guangjing). -* time: add After. -* websocket: enable tests on windows (thanks Alex Brainman). -- -
-This release includes some minor language changes and some significant package -changes. You may need to change your code if you use ...T parameters or the -http package. - -The semantics and syntax of forwarding ...T parameters have changed. - func message(f string, s ...interface{}) { fmt.Printf(f, s) } -Here, s has type []interface{} and contains the parameters passed to message. -Before this language change, the compiler recognized when a function call -passed a ... parameter to another ... parameter of the same type, and just -passed it as though it was a list of arguments. But this meant that you -couldn't control whether to pass the slice as a single argument and you -couldn't pass a regular slice as a ... parameter, which can be handy. This -change gives you that control at the cost of a few characters in the call. -If you want the promotion to ..., append ... to the argument: - func message(f string, s ...interface{}) { fmt.Printf(f, s...) } -Without the ..., s would be passed to Printf as a single argument of type -[]interface{}. The bad news is you might need to fix up some of your code, -but the compiler will detect the situation and warn you. - -Also, the http.Handler and http.HandlerFunc types have changed. Where http -handler functions previously accepted an *http.Conn, they now take an interface -type http.ResponseWriter. ResponseWriter implements the same methods as *Conn, -so in most cases the only change required will be changing the type signature -of your handler function's first parameter. See: - http://golang.org/pkg/http/#Handler - -The utf8 package has a new type, String, that provides efficient indexing -into utf8 strings by rune (previously an expensive conversion to []int -was required). See: - http://golang.org/pkg/utf8/#String - -The compiler will now automatically insert a semicolon at the end of a file if -one is not found. This effect of this is that Go source files are no longer -required to have a trailing newline. - -Other changes: -* 6prof: more accurate usage message. -* archive/zip: new package for reading Zip files. -* arm: fix code generation, 10 more package tests pass. -* asn1: make interface consistent with json. -* bufio.UnreadRune: fix bug at EOF. -* build: clear custom variables like GREP_OPTIONS, - silence warnings generated by ubuntu gcc, - use full path when compiling libraries. -* bytes, strings: change lastIndexFunc to use DecodeLastRune (thanks Roger Peppe). -* doc: add to and consolidate non-english doc references, - consolidate FAQs into a single file, go_faq.html, - updates for new http interface. -* fmt/Printf: document and tweak error messages produced for bad formats. -* gc: allow select case expr = <-c, - eliminate duplicates in method table, - fix reflect table method receiver, - improve error message for x \= 0. -* go/scanner: treat EOF like a newline for purposes of semicolon insertion. -* gofmt: stability improvements. -* gotest: leave _testmain.go for "make clean" to clean up. -* http: correct escaping of different parts of URL, - support HTTP/1.0 Keep-Alive. -* json: do not write to unexported fields. -* libcgo: don't build for NaCl, - set g, m in thread local storage for windows 386 (thanks Wei Guangjing). -* math: Fix off-by-one error in Ilogb and Logb. (thanks Charles L. Dorian). -* misc/dashboard/builder: remove build files after benchmarking. -* nacl: update instructions for new SDK. -* net: enable v4-over-v6 on ip sockets, - fix crash in DialIP. -* os: check for valid arguments in windows Readdir (thanks Peter Mundy). -* runtime: add mmap of null page just in case, - correct stats in SysFree, - fix unwindstack crash. -* syscall: add IPPROTO_IPV6 and IPV6_V6ONLY const to fix nacl and windows build, - add inotify on Linux (thanks Balazs Lecz), - fix socketpair in syscall_bsd, - fix windows value of IPV6_V6ONLY (thanks Alex Brainman), - implement windows version of Utimes (thanks Alex Brainman), - make mkall.sh work for nacl. -* test: Add test that causes incorrect error from gccgo. -* utf8: add DecodeLastRune and DecodeLastRuneInString (thanks Roger Peppe). -* xml: Allow entities inside CDATA tags (thanks Dan Sinclair). -- -
-This release includes new package functionality, and many bug fixes and changes. -It also improves support for the arm and nacl platforms. - -* 5l: avoid fixed buffers in list. -* 6l, 8l: clean up ELF code, fix NaCl. -* 6l/8l: emit DWARF frame info. -* Make.inc: make GOOS detection work on windows (thanks Alex Brainman). -* build: fixes for native arn build, - make all.bash run on Ubuntu ARM. -* cgo: bug fixes, - show preamble gcc errors (thanks Eric Clark). -* crypto/x509, crypto/tls: improve root matching and observe CA flag. -* crypto: Fix certificate validation. -* doc: variable-width layout. -* env.bash: fix building in directory with spaces in the path (thanks Alex Brainman). -* exp/4s, exp/nacl/av: sync to recent exp/draw changes. -* exp/draw/x11: mouse location is a signed integer. -* exp/nacl/av: update color to max out at 1<<16-1 instead of 1<<32-1. -* fmt: support '*' for width or precision (thanks Anthony Martin). -* gc: improvements to static initialization, - make sure path names are canonical. -* gob: make robust when decoding a struct with non-struct data. -* gobuilder: add -cmd for user-specified build command, - add -rev= flag to build specific revision and exit, - fix bug that caused old revisions to be rebuilt. -* godoc: change default filter file name to "", - don't use quadratic algorithm to filter paths, - show "Last update" info for directory listings. -* http: new redirect test, - URLEscape now escapes all reserved characters as per the RFC. -* nacl: fix zero-length writes. -* net/dict: parse response correctly (thanks Fazlul Shahriar). -* netchan: add a cross-connect test, - handle closing of channels, - provide a method (Importer.Errors()) to recover protocol errors. -* os: make Open() O_APPEND flag work on windows (thanks Alex Brainman), - make RemoveAll() work on windows (thanks Alex Brainman). -* pkg/Makefile: disable netchan test to fix windows build (thanks Alex Brainman). -* regexp: delete Iter methods. -* runtime: better panic for send to nil channel. -* strings: fix minor bug in LastIndexFunc (thanks Roger Peppe). -* suffixarray: a package for creating suffixarray-based indexes. -* syscall: Use vsyscall for syscall.Gettimeofday and .Time on linux amd64. -* test: fix NaCl build. -* windows: fix netchan test by using 127.0.0.1. -- -
-This release includes a language change: the lower bound of a subslice may -now be omitted, in which case the value will default to 0. -For example, s[0:10] may now be written as s[:10], and s[0:] as s[:]. - -The release also includes important bug fixes for the ARM architecture, -as well as the following fixes and changes: - -* 5g: register allocation bugs -* 6c, 8c: show line numbers in -S output -* 6g, 6l, 8g, 8l: move read-only data to text segment -* 6l, 8l: make etext accurate; introduce rodata, erodata. -* arm: fix build bugs. - make libcgo build during OS X cross-compile - remove reference to deleted file syntax/slice.go - use the correct stat syscalls - work around reg allocator bug in 5g -* bufio: add UnreadRune. -* build: avoid bad environment interactions - fix build for tiny - generate, clean .exe files on Windows (thanks Joe Poirier) - test for _WIN32, not _MINGW32 (thanks Joe Poirier) - work with GNU Make 3.82 (thanks Jukka-Pekka Kekkonen) -* cgo: add typedef for uintptr in generated headers - silence warning for C call returning const pointer -* codereview: convert email address to lower case before checking CONTRIBUTORS -* crypto/tls: don't return an error from Close() -* doc/tutorial: update for slice changes. -* exec: separate LookPath implementations for unix/windows (thanks Joe Poirier) -* exp/draw/x11: allow clean shutdown when the user closes the window. -* exp/draw: clip destination rectangle to the image bounds. - fast path for drawing overlapping image.RGBAs. - fix double-counting of pt.Min for the src and mask points. - reintroduce the MouseEvent.Nsec timestamp. - rename Context to Window, and add a Close method. -* exp/debug: preliminary support for 'copy' function (thanks Sebastien Binet) -* fmt.Fscan: use UnreadRune to preserve data across calls. -* gc: better printing of named constants, func literals in errors - many bug fixes - fix line number printing with //line directives - fix symbol table generation on windows (thanks Alex Brainman) - implement comparison rule from spec change 33abb649cb63 - implement new slice spec (thanks Scott Lawrence) - make string x + y + z + ... + w efficient - more accurate line numbers for ATEXT - remove &[10]int -> []int conversion -* go-mode.el: fix highlighting for 'chan' type (thanks Scott Lawrence) -* godoc: better support for directory trees for user-supplied paths - use correct delay time (bug fix) -* gofmt, go/printer: update internal estimated position correctly -* goinstall: warn when package name starts with http:// (thanks Scott Lawrence) -* http: check https certificate against host name - do not cache CanonicalHeaderKey (thanks Jukka-Pekka Kekkonen) -* image: change a ColorImage's minimum point from (0, 0) to (-1e9, -1e9). - introduce Intersect and Union rectangle methods. -* ld: handle quoted spaces in package path (thanks Dan Sinclair) -* libcgo: fix NaCl build. -* libmach: fix build on arm host - fix new thread race with Linux -* math: make portable Tan(Pi/2) return NaN -* misc/dashboard/builder: gobuilder, a continuous build client -* net: disable tests for functions not available on windows (thanks Alex Brainman) -* netchan: make -1 unlimited, as advertised. -* os, exec: rename argv0 to name -* path: add IsAbs (thanks Ivan Krasin) -* runtime: fix bug in tracebacks - fix crash trace on amd64 - fix windows build (thanks Alex Brainman) - use manual stack for garbage collection -* spec: add examples for slices with omitted index expressions. - allow omission of low slice bound (thanks Scott Lawrence) -* syscall: fix windows Gettimeofday (thanks Alex Brainman) -* test(arm): disable zerodivide.go because compilation fails. -* test(windows): disable tests that cause the build to fail (thanks Joe Poirier) -* test/garbage/parser: sync with recent parser changes -* test: Add test for //line - Make gccgo believe that the variables can change. - Recognize gccgo error messages. - Reduce race conditions in chan/nonblock.go. - Run garbage collector before testing malloc numbers. -* websocket: Add support for secure WebSockets (thanks Jukka-Pekka Kekkonen) -* windows: disable unimplemented tests (thanks Joe Poirier) -- -
-This release includes the syntactic modernization of more than 100 files in /test, -and these additions, changes, and fixes: -* 6l/8l: emit DWARF in macho. -* 8g: use FCHS, not FMUL, for minus float. -* 8l: emit DWARF in ELF, - suppress emitting DWARF in Windows PE (thanks Alex Brainman). -* big: added RatString, some simplifications. -* build: create bin and pkg directories as needed; drop from hg, - delete Make.386 Make.amd64 Make.arm (obsoleted by Make.inc), - fix cgo with -j2, - let pkg/Makefile coordinate building of Go commands, - never use quietgcc in Make.pkg, - remove more references to GOBIN and GOROOT (thanks Christian Himpel). -* codereview: Fix uploading for Mercurial 1.6.3 (thanks Evan Shaw), - consistent indent, cut dead code, - fix hang on standard hg commands, - print status when tasks take longer than 30 seconds, - really disable codereview when not available, - upload files in parallel (5x improvement on large CLs). -* crypto/hmac: make Sum idempotent (thanks Jukka-Pekka Kekkonen). -* doc: add links to more German docs, - add round-robin flag to io2010 balance example, - fix a bug in the example in Constants subsection (thanks James Fysh), - various changes for validating HTML (thanks Scott Lawrence). -* fmt: delete erroneous sentence about return value for Sprint*. -* gc: appease bison version running on FreeBSD builder, - fix spurious syntax error. -* go/doc: use correct escaper for URL. -* go/printer: align ImportPaths in ImportDecls (thanks Scott Lawrence). -* go/typechecker: 2nd step towards augmenting AST with full type information. -* gofmt: permit omission of first index in slice expression. -* goinstall: added -a flag to mean "all remote packages" (thanks Scott Lawrence), - assume go binaries are in path (following new convention), - use https for Google Code checkouts. -* gotest: allow make test of cgo packages (without make install). -* http: add Date to server, Last-Modified and If-Modified-Since to file server, - add PostForm function to post url-encoded key/value data, - obscure passwords in return value of URL.String (thanks Scott Lawrence). -* image: introduce Config type and DecodeConfig function. -* libcgo: update Makefile to use Make.inc. -* list: update comment to state that the zero value is ready to use. -* math: amd64 version of Sincos (thanks Charles L. Dorian). -* misc/bash: add *.go completion for gofmt (thanks Scott Lawrence). -* misc/emacs: make _ a word symbol (thanks Scott Lawrence). -* misc: add zsh completion (using compctl), - syntax highlighting for Fraise.app (OS X) (thanks Vincent Ambo). -* net/textproto: Handle multi-line responses (thanks Evan Shaw). -* net: add LookupMX (thanks Corey Thomasson). -* netchan: Fix race condition in test, - rather than 0, make -1 mean infinite (a la strings.Split et al), - use acknowledgements on export send. - new methods Sync and Drain for clean teardown. -* regexp: interpret all Go characer escapes \a \b \f \n \r \t \v. -* rpc: fix bug that caused private methods to attempt to be registered. -* runtime: Correct commonType.kind values to match compiler, - add GOOS, GOARCH; fix FuncLine, - special case copy, equal for one-word interface values (thanks Kyle Consalus). -* scanner: fix incorrect reporting of error in Next (thanks Kyle Consalus). -* spec: clarify that arrays must be addressable to be sliceable. -* template: fix space handling around actions. -* test/solitaire: an exercise in backtracking and string conversions. -* test: Recognize gccgo error messages and other fixes. -* time: do not crash in String on nil Time. -* tutorial: regenerate HTML to pick up change to progs/file.go. -* websocket: fix missing Sec-WebSocket-Protocol on server response (thanks Jukka-Pekka Kekkonen). -- -
-This release includes changes to the build system that will likely require you -to make changes to your environment variables and Makefiles. - -All environment variables are now optional: - - $GOOS and $GOARCH are now optional; their values should now be inferred - automatically by the build system, - - $GOROOT is now optional, but if you choose not to set it you must run - 'gomake' instead of 'make' or 'gmake' when developing Go programs - using the conventional Makefiles, - - $GOBIN remains optional and now defaults to $GOROOT/bin; - if you wish to use this new default, make sure it is in your $PATH - and that you have removed the existing binaries from $HOME/bin. - -As a result of these changes, the Go Makefiles have changed. If your Makefiles -inherit from the Go Makefiles, you must change this line: - include ../../Make.$(GOARCH) -to this: - include ../../Make.inc - -This release also removes the deprecated functions in regexp and the -once package. Any code that still uses them will break. -See the notes from the last release for details: - http://golang.org/doc/devel/release.html#2010-08-11 - -Other changes: -* 6g: better registerization for slices, strings, interface values -* 6l: line number information in DWARF format -* build: $GOBIN defaults to $GOROOT/bin, - no required environment variables -* cgo: add C.GoStringN (thanks Eric Clark). -* codereview: fix issues with leading tabs in CL descriptions, - do not send "Abandoned" mail if the CL has not been mailed. -* crypto/ocsp: add missing Makefile. -* crypto/tls: client certificate support (thanks Mikkel Krautz). -* doc: update gccgo information for recent changes. - fix errors in Effective Go. -* fmt/print: give %p priority, analogous to %T, - honor Formatter in Print, Println. -* gc: fix parenthesization check. -* go/ast: facility for printing AST nodes, - first step towards augmenting AST with full type information. -* go/printer: do not modify tabwriter.Escape'd text. -* gofmt: do not modify multi-line string literals, - print AST nodes by setting -ast flag. -* http: fix typo in http.Request documentation (thanks Scott Lawrence) - parse query string always, not just in GET -* image/png: support 16-bit color. -* io: ReadAtLeast now errors if min > len(buf). -* jsonrpc: use `error: null` for success, not `error: ""`. -* libmach: implement register fetch for 32-bit x86 kernel. -* net: make IPv6 String method standards-compliant (thanks Mikio Hara). -* os: FileInfo.Permission() now returns uint32 (thanks Scott Lawrence), - implement env using native Windows API (thanks Alex Brainman). -* reflect: allow PtrValue.PointTo(nil). -* runtime: correct line numbers for .goc files, - fix another stack split bug, - fix freebsd/386 mmap. -* syscall: regenerate syscall/z* files for linux/386, linux/amd64, linux/arm. -* tabwriter: Introduce a new flag StripEscape. -* template: fix handling of space around actions, - vars preceded by white space parse correctly (thanks Roger Peppe). -* test: add test case that crashes gccgo. -* time: parse no longer requires minutes for time zone (thanks Jan H. Hosang) -* yacc: fix bounds check in error recovery. -- -
-This release introduces some package changes. You may need to change your -code if you use the once, regexp, image, or exp/draw packages. - -The type Once has been added to the sync package. The new sync.Once will -supersede the functionality provided by the once package. We intend to remove -the once package after this release. See: - http://golang.org/pkg/sync/#Once -All instances of once in the standard library have been replaced with -sync.Once. Reviewing these changes may help you modify your existing code. -The relevant changeset: - http://code.google.com/p/go/source/detail?r=fa2c43595119 - -A new set of methods has been added to the regular expression package, regexp. -These provide a uniformly named approach to discovering the matches of an -expression within a piece of text; see the package documentation for details: - http://golang.org/pkg/regexp/ -These new methods will, in a later release, replace the old methods for -matching substrings. The following methods are deprecated: - Execute (use FindSubmatchIndex) - ExecuteString (use FindStringSubmatchIndex) - MatchStrings(use FindStringSubmatch) - MatchSlices (use FindSubmatch) - AllMatches (use FindAll; note that n<0 means 'all matches'; was n<=0) - AllMatchesString (use FindAllString; note that n<0 means 'all matches'; was n<=0) -(Plus there are ten new methods you didn't know you wanted.) -Please update your code to use the new routines before the next release. - -An image.Image now has a Bounds rectangle, where previously it ranged -from (0, 0) to (Width, Height). Loops that previously looked like: - for y := 0; y < img.Height(); y++ { - for x := 0; x < img.Width(); x++ { - // Do something with img.At(x, y) - } - } -should instead be: - b := img.Bounds() - for y := b.Min.Y; y < b.Max.Y; y++ { - for x := b.Min.X; x < b.Max.X; x++ { - // Do something with img.At(x, y) - } - } -The Point and Rectangle types have also moved from exp/draw to image. - -Other changes: -* arm: bugfixes and syscall (thanks Kai Backman). -* asn1: fix incorrect encoding of signed integers (thanks Nicholas Waples). -* big: fixes to bitwise functions (thanks Evan Shaw). -* bytes: add IndexRune, FieldsFunc and To*Special (thanks Christian Himpel). -* encoding/binary: add complex (thanks Roger Peppe). -* exp/iterable: add UintArray (thanks Anschel Schaffer-Cohen). -* godoc: report Status 404 if a pkg or file is not found. -* gofmt: better reporting for unexpected semicolon errors. -* html: new package, an HTML tokenizer. -* image: change image representation from slice-of-slices to linear buffer, - introduce Decode and RegisterFormat, - introduce Transparent and Opaque, - replace Width and Height by Bounds, add the Point and Rect types. -* libbio: fix Bprint to address 6g issues with large data structures. -* math: fix amd64 Hypot (thanks Charles L. Dorian). -* net/textproto: new package, with example net/dict. -* os: fix ForkExec() handling of envv == nil (thanks Alex Brainman). -* png: grayscale support (thanks Mathieu Lonjaret). -* regexp: document that backslashes are the escape character. -* rpc: catch errors from ReadResponseBody. -* runtime: memory free fix (thanks Alex Brainman). -* template: add ParseFile method to template.Template. -* test/peano: use directly recursive type def. -- -
-This release includes a change to os.Open (and co.). The file permission -argument has been changed to a uint32. Your code may require changes - a simple -conversion operation at most. - -Other changes: -* amd64: use segment memory for thread-local storage. -* arm: add gdb support to android launcher script, - bugfixes (stack clobbering, indices), - disable another flaky test, - remove old qemu dependency from gotest. -* bufio: introduce Peek. -* bytes: added test case for explode with blank string (thanks Scott Lawrence). -* cgo: correct multiple return value function invocations (thanks Christian Himpel). -* crypto/x509: unwrap Subject Key Identifier (thanks Adam Langley). -* gc: index bounds tests and other fixes. -* gofmt/go/parser: strengthen syntax checks. -* goinstall: check for error from exec.*Cmd.Wait() (thanks Alex Brainman). -* image/png: use image-specific methods for checking opacity. -* image: introduce Gray and Gray16 types, - remove the named colors except for Black and White. -* json: object members must have a value (thanks Anthony Martin). -* misc/vim: highlight misspelled words only in comments (thanks Christian Himpel). -* os: Null device (thanks Peter Mundy). -* runtime: do not fall through in SIGBUS/SIGSEGV. -* strings: fix Split("", "", -1) (thanks Scott Lawrence). -* syscall: make go errors not clash with windows errors (thanks Alex Brainman). -* test/run: diff old new, -* websocket: correct challenge response (thanks Tarmigan Casebolt), - fix bug involving spaces in header keys (thanks Bill Neubauer). -- -
-* 5g: more soft float support and several bugfixes. -* asn1: Enumerated, Flag and GeneralizedTime support. -* build: clean.bash to check that GOOS and GOARCH are set. -* bytes: add IndexFunc and LastIndexFunc (thanks Fazlul Shahriar), - add Title. -* cgo: If CC is set in environment, use it rather than "gcc", - use new command line syntax: -- separates cgo flags from gcc flags. -* codereview: avoid crash if no config, - don't run gofmt with an empty file list, - make 'hg submit' work with Mercurial 1.6. -* crypto/ocsp: add package to parse OCSP responses. -* crypto/tls: add client-side SNI support and PeerCertificates. -* exp/bignum: delete package - functionality subsumed by package big. -* fmt.Print: fix bug in placement of spaces introduced when ...T went in. -* fmt.Scanf: handle trailing spaces. -* gc: fix smaller-than-pointer-sized receivers in interfaces, - floating point precision/normalization fixes, - graceful exit on seg fault, - import dot shadowing bug, - many fixes including better handling of invalid input, - print error detail about failure to open import. -* gccgo_install.html: add description of the port to RTEMS (thanks Vinu Rajashekhar). -* gobs: fix bug in singleton arrays. -* godoc: display synopses for all packages that have some kind of documentation.. -* gofmt: fix some linebreak issues. -* http: add https client support (thanks Fazlul Shahriar), - write body when content length unknown (thanks James Whitehead). -* io: MultiReader and MultiWriter (thanks Brad Fitzpatrick), - fix another race condition in Pipes. -* ld: many fixes including better handling of invalid input. -* libmach: correct handling of .5 files with D_REGREG addresses. -* linux/386: use Xen-friendly ELF TLS instruction sequence. -* mime: add AddExtensionType (thanks Yuusei Kuwana). -* misc/vim: syntax file recognizes constants like 1e9 (thanks Petar Maymounkov). -* net: TCPConn.SetNoDelay, back by popular demand. -* net(windows): fix crashing Read/Write when passed empty slice on (thanks Alex Brainman), - implement LookupHost/Port/SRV (thanks Wei Guangjing), - properly handle EOF in (*netFD).Read() (thanks Alex Brainman). -* runtime: fix bug introduced in revision 4a01b8d28570 (thanks Alex Brainman), - rename cgo2c, *.cgo to goc2c, *.goc (thanks Peter Mundy). -* scanner: better comment. -* strings: add Title. -* syscall: add ForkExec, Syscall12 on Windows (thanks Daniel Theophanes), - improve windows errno handling (thanks Alex Brainman). -* syscall(windows): fix FormatMessage (thanks Peter Mundy), - implement Pipe() (thanks Wei Guangjing). -* time: fix parsing of minutes in time zones. -* utf16(windows): fix cyclic dependency when testing (thanks Peter Mundy). -- -
-This release includes a package change. In container/vector, the Iter method -has been removed from the Vector, IntVector, and StringVector types. Also, the -Data method has been renamed to Copy to better express its actual behavior. -Now that Vector is just a slice, any for loops ranging over v.Iter() or -v.Data() can be changed to range over v instead. - -Other changes: -* big: Improvements to Rat.SetString (thanks Evan Shaw), - add sign, abs, Rat.IsInt. -* cgo: various bug fixes. -* codereview: Fix for Mercurial >= 1.6 (thanks Evan Shaw). -* crypto/rand: add Windows implementation (thanks Peter Mundy). -* crypto/tls: make HTTPS servers easier, - add client OCSP stapling support. -* exp/eval: converted from bignum to big (thanks Evan Shaw). -* gc: implement new len spec, range bug fix, optimization. -* go/parser: require that '...' parameters are followed by a type. -* http: fix ParseURL to handle //relative_path properly. -* io: fix SectionReader Seek to seek backwards (thanks Peter Mundy). -* json: Add HTMLEscape (thanks Micah Stetson). -* ld: bug fixes. -* math: amd64 version of log (thanks Charles L. Dorian). -* mime/multipart: new package to parse multipart MIME messages - and HTTP multipart/form-data support. -* os: use TempFile with default TempDir for test files (thanks Peter Mundy). -* runtime/tiny: add docs for additional VMs, fix build (thanks Markus Duft). -* runtime: better error for send/recv on nil channel. -* spec: clarification of channel close(), - lock down some details about channels and select, - restrict when len(x) is constant, - specify len/cap for nil slices, maps, and channels. -* windows: append .exe to binary names (thanks Joe Poirier). -- -
-This release includes some package changes that may require changes to -client code. - -The Split function in the bytes and strings packages has been changed. -The count argument, which limits the size of the return, previously treated -zero as unbounded. It now treats 0 as 0, and will return an empty slice. -To request unbounded results, use -1 (or some other negative value). -The new Replace functions in bytes and strings share this behavior. -This may require you change your existing code. - -The gob package now allows the transmission of non-struct values at the -top-level. As a result, the rpc and netchan packages have fewer restrictions -on the types they can handle. For example, netchan can now share a chan int. - -The release also includes a Code Walk: "Share Memory By Communicating". -It describes an idiomatic Go program that uses goroutines and channels: - http://golang.org/doc/codewalk/sharemem/ - -There is now a Projects page on the Go Dashboard that lists Go programs, -tools, and libraries: - http://godashboard.appspot.com/project - -Other changes: -* 6a, 6l: bug fixes. -* bytes, strings: add Replace. -* cgo: use slash-free relative paths for .so references. -* cmath: correct IsNaN for argument cmplx(Inf, NaN) (thanks Charles L. Dorian). -* codereview: allow multiple email addresses in CONTRIBUTORS. -* doc/codewalk: add Share Memory By Communicating. -* exp/draw/x11: implement the mapping from keycodes to keysyms. -* fmt: Printf: fix bug in handling of %#v, allow other verbs for slices - Scan: fix handling of EOFs. -* gc: bug fixes and optimizations. -* gob: add DecodeValue and EncodeValue, - add support for complex numbers. -* goinstall: support for Bazaar+Launchpad (thanks Gustavo Niemeyer). -* io/ioutil: add TempFile for Windows (thanks Peter Mundy). -* ld: add -u flag to check safe bits; discard old -u, -x flags. -* math: amd64 versions of Exp and Fabs (thanks Charles L. Dorian). -* misc/vim: always override filetype detection for .go files. -* net: add support for DNS SRV requests (thanks Kirklin McDonald), - initial attempt to implement Windows version (thanks Alex Brainman). -* netchan: allow chan of basic types now that gob can handle such, - eliminate the need for a pointer value in Import and Export. -* os/signal: only catch all signals if os/signal package imported. -* regexp: bug fix: need to track whether match begins with fixed prefix. -* rpc: allow non-struct args and reply (they must still be pointers). -* runtime: bug fixes and reorganization. -* strconv: fix bugs in floating-point and base 2 conversions -* syscall: add syscall_bsd.go to zsycall_freebsd_386.go (thanks Peter Mundy), - add socketpair (thanks Ivan Krasin). -* time: implement time zones for Windows (thanks Alex Brainman). -* x509: support non-self-signed certs. -- -
-This release includes a language change. The "..." function parameter form is -gone; "...T" remains. Typically, "...interface{}" can be used instead of "...". - -The implementation of Printf has changed in a way that subtly affects its -handling of the fmt.Stringer interface. You may need to make changes to your -code. For details, see: - https://groups.google.com/group/golang-nuts/msg/6fffba90a3e3dc06 - -The reflect package has been changed. If you have code that uses reflect, -it will need to be updated. For details, see: - https://groups.google.com/group/golang-nuts/msg/7a93d07c590e7beb - -Other changes: -* 8l: correct test for sp == top of stack in 8l -K code. -* asn1: allow '*' in PrintableString. -* bytes.Buffer.ReadFrom: fix bug. -* codereview: avoid exception in match (thanks Paolo Giarrusso). -* complex divide: match C99 implementation. -* exp/draw: small draw.drawGlyphOver optimization. -* fmt: Print*: reimplement to switch on type first, - Scanf: improve error message when input does not match format. -* gc: better error messages for interface failures, conversions, undefined symbols. -* go/scanner: report illegal escape sequences. -* gob: substitute slice for map. -* goinstall: process dependencies for package main (thanks Roger Peppe). -* gopack: add S flag to force marking a package as safe, - simplify go metadata code. -* html: sync testdata/webkit to match WebKit tip. -* http: reply to Expect 100-continue requests automatically (thanks Brad Fitzpatrick). -* image: add an Alpha16 type. -* ld: pad Go symbol table out to page boundary (fixes cgo crash). -* misc/vim: reorganize plugin to be easier to use (thanks James Whitehead). -* path: add Base, analogous to Unix basename. -* pkg/Makefile: allow DISABLE_NET_TESTS=1 to disable network tests. -* reflect: add Kind, Type.Bits, remove Int8Type, Int8Value, etc. -* runtime: additional Windows support (thanks Alex Brainman), - correct fault for 16-bit divide on Leopard, - fix 386 signal handler bug. -* strconv: add AtofN, FtoaN. -* string: add IndexFunc and LastIndexFunc (thanks Roger Peppe). -* syslog: use local network for tests. -- -
-This release contains many fixes and improvements, including several -clarifications and consolidations to the Language Specification. - -The type checking rules around assignments and conversions are simpler but more -restrictive: assignments no longer convert implicitly from *[10]int to []int -(write x[0:] instead of &x), and conversions can no longer change the names of -types inside composite types. - -The fmt package now includes flexible type-driven (fmt.Scan) and -format-driven (fmt.Scanf) scanners for all basic types. - -* big: bug fix for Quo aliasing problem. -* bufio: change ReadSlice to match description. -* cgo: bug fixes. -* doc: add Google I/O talk and programs, - codereview + Mercurial Queues info (thanks Peter Williams). -* exp/draw: Draw fast paths for the Over operator, - add Rectangle.Eq and Point.In, fix Rectangle.Clip (thanks Roger Peppe). -* fmt: Scan fixes and improvements. -* gc: backslash newline is not a legal escape sequence in strings, - better error message when ~ operator is found, - fix export of complex types, - new typechecking rules. -* go/parser: correct position of empty statement ';'. -* gofmt: fix test script. -* goinstall: use 'git pull' instead of 'git checkout' (thanks Michael Hoisie). -* http: add Head function for making HTTP HEAD requests, - handle status 304 correctly. -* image: add Opaque method to the image types. - make Color.RGBA return 16 bit color instead of 32 bit color. -* io/ioutil: add TempFile. -* math: Pow special cases and additional tests (thanks Charles L. Dorian). -* netchan: improve closing and shutdown. -* os: implement os.FileInfo.*time_ns for windows (thanks Alex Brainman). -* os/signal: correct the regexp for finding Unix signal names (thanks Vinu Rajashekhar). -* regexp: optimizations (thanks Kyle Consalus). -* runtime: fix printing -Inf (thanks Evan Shaw), - finish pchw -> tiny, added gettime for tiny (thanks Daniel Theophanes). -* spec: clean-ups and consolidation. -* syscall: additional Windows compatibility fixes (thanks Alex Brainman). -* test/bench: added regex-dna-parallel.go (thanks Kyle Consalus). -* vector: type-specific Do functions now take f(type) (thanks Michael Hoisie). -- -
-A sizeable release, including standard library improvements and a slew of -compiler bug fixes. The three-week interval was largely caused by the team -preparing for Google I/O. - -* big: add Rat type (thanks Evan Shaw), - new features, much performance tuning, cleanups, and more tests. -* bignum: deprecate by moving into exp directory. -* build: allow MAKEFLAGS to be set outside the build scripts (thanks Christopher Wedgwood). -* bytes: add Trim, TrimLeft, TrimRight, and generic functions (thanks Michael Hoisie). -* cgo: fix to permit cgo callbacks from init code. -* cmath: update range of Phase and Polar due to signed zero (thanks Charles L. Dorian). -* codereview: work better with mq (thanks Peter Williams). -* compress: renamings - NewDeflater -> NewWriter - NewInflater -> NewReader - Deflater -> Compressor - Inflater -> Decompressor -* exp/draw/x11: respect $XAUTHORITY, - treat $DISPLAY the same way x-go-bindings does. -* exp/draw: fast path for glyph images, other optimizations, - fix Rectangle.Canon (thanks Roger Peppe). -* fmt: Scan, Scanln: Start of a simple scanning API in the fmt package, - fix Printf crash when given an extra nil argument (thanks Roger Peppe). -* gc: better error when computing remainder of non-int (thanks Evan Shaw), - disallow middot in Go programs, - distinguish array, slice literal in error messages, - fix shift/reduce conflict in go.y export syntax, - fix unsafe.Sizeof on ideal constants, - handle use of builtin function outside function call, - many other bug fixes. -* gob: add support for maps, - add test for indirect maps, slices, arrays. -* godoc: collect package comments from all package files. -* gofmt: don't lose mandatory semicolons, - exclude test w/ illegal syntax from test cases, - fix printing of labels. -* http: prevent crash if remote server is not responding with "HTTP/". -* json: accept escaped slash in string scanner (thanks Michael Hoisie), - fix array -> non-array decoding. -* libmach: skip __nl_symbol_ptr section on OS X. -* math: amd64 versions of Fdim, Fmax, Fmin, - signed zero Sqrt special case (thanks Charles L. Dorian). -* misc/kate: convert isn't a built in function (thanks Evan Shaw). -* net: implement BindToDevice, - implement raw sockets (thanks Christopher Wedgwood). -* netFD: fix race between Close and Read/Write (thanks Michael Hoisie). -* os: add Chtimes function (thanks Brad Fitzpatrick). -* pkg/Makefile: add netchan to standard package list. -* runtime: GOMAXPROCS returns previous value, - allow large map values, - avoid allocation for fixed strings, - correct tracebacks for nascent goroutines, even closures, - free old hashmap pieces during resizing. -* spec: added imaginary literal to semicolon rules (was missing), - fix and clarify syntax of conversions, - simplify section on channel types, - other minor tweaks. -* strconv: Btoui64 optimizations (thanks Kyle Consalus). -* strings: use copy instead of for loop in Map (thanks Kyle Consalus). -* syscall: implement BindToDevice (thanks Christopher Wedgwood), - add Utimes on Darwin/FreeBSD, add Futimes everywhere, - regenerate syscalls for some platforms. -* template: regularize name lookups of interfaces, pointers, and methods. -- -
-In this release we renamed the Windows OS target from 'mingw' to 'windows'. -If you are currently building for 'mingw' you should set GOOS=windows instead. - -* 5l, 6l, 8l, runtime: make -s binaries work. -* 5l, 6l, 8l: change ELF header so that strip doesn't destroy binary. -* 8l: fix absolute path detection on Windows. -* big: new functions, optimizations, and cleanups, - add bitwise methods for Int (thanks Evan Shaw). -* bytes: Change IndexAny to look for UTF-8 encoded characters. -* darwin: bsdthread_create can fail; print good error. -* fmt: %T missing print <nil> for nil (thanks Christopher Wedgwood). -* gc: many fixes. -* misc/cgo/gmp: fix bug in SetString. -* net: fix resolv.conf EOF without newline bug (thanks Christopher Wedgwood). -* spec: some small clarifications (no language changes). -* syscall: add EWOULDBLOCK to sycall_nacl.go, - force O_LARGEFILE in Linux open system call, - handle EOF on pipe - special case on Windows (thanks Alex Brainman), - mingw Sleep (thanks Joe Poirier). -* test/bench: import new fasta C reference, update Go, optimizations. -* test: test of static initialization (fails). -* vector: use correct capacity in call to make. -* xml: allow text segments to end at EOF. -- -
-This release includes a new Codelab that illustrates the construction of a -simple wiki web application: - http://golang.org/doc/codelab/wiki/ - -It also includes a Codewalk framework for documenting code. See: - http://golang.org/doc/codewalk/ - -Other changes: -* 6g: fix need for parens around array index expression. -* 6l, 8l: include ELF header in PT_LOAD mapping for text segment. -* arm: add android runner script, - support for printing floats. -* big: implemented Karatsuba multiplication, - many fixes and improvements (thanks Evan Shaw). -* bytes: add Next method to Buffer, simplify Read, - shuffle implementation, making WriteByte 50% faster. -* crypto/tls: simpler implementation of record layer. -* exp/eval: fixes (thanks Evan Shaw). -* flag: eliminate unnecessary structs. -* gc: better windows support, - cmplx typecheck bug fix, - more specific error for statements at top level. -* go/parser: don't require unnecessary parens. -* godoc: exclude duplicate entries (thanks Andrei Vieru), - use int64 for timestamps (thanks Christopher Wedgwood). -* gofmt: fine-tune stripping of parentheses, -* json: Marshal, Unmarshal using new scanner, - preserve field name case by default, - scanner, Compact, Indent, and tests, - support for streaming. -* libmach: disassemble MOVLQZX correctly. -* math: more special cases for signed zero (thanks Charles L. Dorian). -* net: add Pipe, - fix bugs in packStructValue (thanks Michael Hoisie), - introduce net.Error interface. -* os: FileInfo: regularize the types of some fields, - create sys_bsd.go (thanks Giles Lean), - mingw bug fixes (thanks Alex Brainman). -* reflect: add FieldByNameFunc (thanks Raif S. Naffah), - implement Set(nil), SetValue(nil) for PtrValue and MapValue. -* regexp: allow escaping of any punctuation. -* rpc/jsonrpc: support for jsonrpc wire encoding. -* rpc: abstract client and server encodings, - add Close() method to rpc.Client. -* runtime: closures, defer bug fix for Native Client, - rename cgo2c, *.cgo to goc2c, *.goc to avoid confusion with real cgo. - several other fixes. -* scanner: implement Peek() to look at the next char w/o advancing. -* strings: add ReadRune to Reader, add FieldsFunc (thanks Kyle Consalus). -* syscall: match linux Setsid function signature to darwin, - mingw bug fixes (thanks Alex Brainman). -* template: fix handling of pointer inside interface. -* test/bench: add fannkuch-parallel.go (thanks Kyle Consalus), - pidigits ~10% performance win by using adds instead of shifts. -* time: remove incorrect time.ISO8601 and add time.RFC3339 (thanks Micah Stetson). -* utf16: add DecodeRune, EncodeRune. -* xml: add support for XML marshaling embedded structs (thanks Raif S. Naffah), - new "innerxml" tag to collect inner XML. -- -
-This release contains many changes: - -* 8l: add DOS stub to PE binaries (thanks Evan Shaw). -* cgo: add //export. -* cmath: new complex math library (thanks Charles L. Dorian). -* docs: update to match current coding style (thanks Christopher Wedgwood). -* exp/eval: fix example and add target to Makefile (thanks Evan Shaw). -* fmt: change behavior of format verb %b to match %x when negative (thanks Andrei Vieru). -* gc: compile s == "" as len(s) == 0, - distinguish fatal compiler bug from error+exit, - fix alignment on non-amd64, - good syntax error for defer func() {} - missing fina (), - implement panic and recover, - zero unnamed return values on entry if func has defer. -* goyacc: change to be reentrant (thanks Roger Peppe). -* io/ioutil: fix bug in ReadFile when Open succeeds but Stat fails. -* kate: update for recent language changes (thanks Evan Shaw). -* libcgo: initial mingw port work - builds but untested (thanks Joe Poirier). -* math: new functions and special cases (thanks Charles L. Dorian) -* net: use chan bool instead of chan *netFD to avoid cycle. -* netchan: allow client to send as well as receive. -* nntp: new package, NNTP client (thanks Conrad Meyer). -* os: rename os.Dir to os.FileInfo. -* rpc: don't log normal EOF, - fix ServeConn to block as documented. -* runtime: many bug fixes, better ARM support. -* strings: add IndexRune, Trim, TrimLeft, TrimRight, etc (thanks Michael Hoisie). -* syscall: implement some mingw syscalls required by os (thanks Alex Brainman). -* test/bench: add k-nucleotide-parallel (thanks Kyle Consalus). -* Unicode: add support for Turkish case mapping. -* xgb: move from the main repository to http://code.google.com/p/x-go-binding/ -- -
-This release contains three language changes: - -1. Accessing a non-existent key in a map is no longer a run-time error. -It now evaluates to the zero value for that type. For example: - x := myMap[i] is now equivalent to: x, _ := myMap[i] - -2. It is now legal to take the address of a function's return value. -The return values are copied back to the caller only after deferred -functions have run. - -3. The functions panic and recover, intended for reporting and recovering from -failure, have been added to the spec: - http://golang.org/doc/go_spec.html#Handling_panics -In a related change, panicln is gone, and panic is now a single-argument -function. Panic and recover are recognized by the gc compilers but the new -behavior is not yet implemented. - -The ARM build is broken in this release; ARM users should stay at release.2010-03-22. - -Other changes: -* bytes, strings: add IndexAny. -* cc/ld: Add support for #pragma dynexport, - Rename dynld to dynimport throughout. Cgo users will need to rerun cgo. -* expvar: default publishings for cmdline, memstats -* flag: add user-defined flag types. -* gc: usual bug fixes -* go/ast: generalized ast filtering. -* go/printer: avoid reflect in print. -* godefs: fix handling of negative constants. -* godoc: export pprof debug information, exported variables, - support for filtering of command-line output in -src mode, - use http GET for remote search instead of rpc. -* gofmt: don't convert multi-line functions into one-liners, - preserve newlines in multiline selector expressions (thanks Risto Jaakko Saarelma). -* goinstall: include command name in error reporting (thanks Andrey Mirtchovski) -* http: add HandleFunc as shortcut to Handle(path, HandlerFunc(func)) -* make: use actual dependency for install -* math: add J1, Y1, Jn, Yn, J0, Y0 (Bessel functions) (thanks Charles L. Dorian) -* prof: add pprof from google-perftools -* regexp: don't return non-nil *Regexp if there is an error. -* runtime: add Callers, - add malloc sampling, pprof interface, - add memory profiling, more statistics to runtime.MemStats, - implement missing destroylock() (thanks Alex Brainman), - more malloc statistics, - run all finalizers in a single goroutine, - Goexit runs deferred calls. -* strconv: add Atob and Btoa, - Unquote could wrongly return a nil error on error (thanks Roger Peppe). -* syscall: add IPV6 constants, - add syscall_bsd.go for Darwin and other *BSDs (thanks Giles Lean), - implement SetsockoptString (thanks Christopher Wedgwood). -* websocket: implement new protocol (thanks Fumitoshi Ukai). -* xgb: fix request length and request size (thanks Firmansyah Adiputra). -* xml: add CopyToken (thanks Kyle Consalus), - add line numbers to syntax errors (thanks Kyle Consalus), - use io.ReadByter in place of local readByter (thanks Raif S. Naffah). -- -
-With this release we announce the launch of the Go Blog: - http://blog.golang.org/ -The first post is a brief update covering what has happened since the launch. - -This release contains some new packages and functionality, and many fixes: -* 6g/8g: fix issues with complex data types, other bug fixes. -* Makefiles: refactored to make writing external Makefiles easier. -* crypto/rand: new package. -* godoc: implemented command-line search via RPC, - improved comment formatting: recognize URLs. -* gofmt: more consistent formatting of const/var decls. -* http: add Error helper function, - add ParseQuery (thanks Petar Maymounkov), - change RawPath to mean raw path, not raw everything-after-scheme. -* image/jpeg: fix typos. -* json: add MarshalIndent (accepts user-specified indent string). -* math: add Gamma function (thanks Charles L. Dorian). -* misc/bbedit: support for cmplx, real, imag (thanks Anthony Starks). -* misc/vim: add new complex types, functions and literals. -* net: fix IPMask.String not to crash on all-0xff mask. -* os: drop File finalizer after normal Close. -* runtime: add GOROOT and Version, - lock finalizer table accesses. -* sha512: add sha384 (truncated version) (thanks Conrad Meyer). -* syscall: add const ARCH, analogous to OS. -* syscall: further additions to mingw port (thanks Alex Brainman). -* template: fixed html formatter []byte input bug. -* utf16: new package. -* version.bash: cope with ancient Mercurial. -* websocket: use URL.RawPath to construct WebSocket-Location: header. -- -
-This release includes a language change: support for complex numbers. - http://golang.org/doc/go_spec.html#Imaginary_literals - http://golang.org/doc/go_spec.html#Complex_numbers -There is no library support as yet. - -This release also includes the goinstall command-line tool. - http://golang.org/cmd/goinstall/ - http://groups.google.com/group/golang-nuts/t/f091704771128e32 - -* 5g/6g/8g: fix double function call in slice. -* arm: cleanup build warnings. (thanks Dean Prichard) -* big: fix mistakes with probablyPrime. -* bufio: add WriteRune. -* bytes: add ReadRune and WriteRune to bytes.Buffer. -* cc: stack split bug fix. -* crypto: add SHA-224 to sha256, add sha512 package. (thanks Conrad Meyer) -* crypto/ripemd160: new package. (thanks Raif S. Naffah) -* crypto/rsa: don't use safe primes. -* gc: avoid fixed length buffer cleanbuf. (thanks Dean Prichard) - better compilation of floating point += - fix crash on complicated arg to make slice. - remove duplicate errors, give better error for I.(T) -* godoc: support for multiple packages in a directory, other fixes. -* gofmt: bug fixes. -* hash: add Sum64 interface. -* hash/crc32: add Update function. -* hash/crc64: new package implementing 64-bit CRC. -* math: add ilogb, logb, remainder. (thanks Charles L. Dorian) -* regexp: add ReplaceAllFunc, ReplaceAllStringFunc. -* runtime: clock garbage collection on bytes allocated, not pages in use. -* strings: make Split(s, "", n) faster. (thanks Spring Mc) -* syscall: minimal mingw version of syscall. (thanks Alex Brainman) -* template: add ParseFile, MustParseFile. -- -
-There is one language change: the ability to convert a string to []byte or -[]int. This deprecates the strings.Bytes and strings.Runes functions. -You can convert your existing sources using these gofmt commands: - gofmt -r 'strings.Bytes(x) -> []byte(x)' -w file-or-directory-list - gofmt -r 'strings.Runes(x) -> []int(x)' -w file-or-directory-list -After running these you might need to delete unused imports of the "strings" -package. - -Other changes and fixes: -* 6l/8l/5l: add -r option -* 8g: make a[byte(x)] truncate x -* codereview.py: fix for compatibility with hg >=1.4.3 -* crypto/blowfish: new package (thanks Raif S. Naffah) -* dashboard: more performance tuning -* fmt: use String method in %q to get the value to quote. -* gofmt: several cosmetic changes -* http: fix handling of Connection: close, bug in http.Post -* net: correct DNS configuration, - fix network timeout boundary condition, - put [ ] around IPv6 addresses for Dial. -* path: add Match, - fix bug in Match with non-greedy stars (thanks Kevin Ballard) -* strings: delete Bytes, Runes (see above) -* tests: an Eratosthenesque concurrent prime sieve (thanks Anh Hai Trinh) -- -
-This release is mainly bug fixes and a little new code. -There are no language changes. - -6g/5g/8g: bug fixes -8a/8l: Added FCMOVcc instructions (thanks Evan Shaw and Charles Dorian) -crypto/x509: support certificate creation -dashboard: caching to avoid datastore queries -exec: add dir argument to Run -godoc: bug fixes and code cleanups -http: continued implementation and bug fixes (thanks Petar Maymounkov) -json: fix quoted strings in Marshal (thanks Sergei Skorobogatov) -math: more functions, test cases, and benchmarks (thanks Charles L. Dorian) -misc/bbedit: treat predeclared identifiers as "keywords" (thanks Anthony Starks) -net: disable UDP server test (flaky on various architectures) -runtime: work around Linux kernel bug in futex, - pchw is now tiny -sync: fix to work on armv5 (thanks Dean Prichard) -websocket: fix binary frame size decoding (thanks Timo Savola) -xml: allow unquoted attribute values in non-Strict mode (thanks Amrut Joshi) - treat bool as value in Unmarshal (thanks Michael Hoisie) -- -
-There are two small language changes: -* NUL bytes may be rejected in souce files, and the tools do reject them. -* Conversions from string to []int and []byte are defined but not yet implemented. - -Other changes and fixes: -* 5a/6a/8a/5c/6c/8c: remove fixed-size arrays for -I and -D options (thanks Dean Prichard) -* 5c/6c/8c/5l/6l/8l: add -V flag to display version number -* 5c/6c/8c: use "cpp" not "/bin/cpp" for external preprocessor (thanks Giles Lean) -* 8a/8l: Added CMOVcc instructions (thanks Evan Shaw) -* 8l: pe executable building code changed to include import table for kernel32.dll functions (thanks Alex Brainman) -* 5g/6g/8g: bug fixes -* asn1: bug fixes and additions (incl marshaling) -* build: fix build for Native Client, Linux/ARM -* dashboard: show benchmarks, add garbage collector benchmarks -* encoding/pem: add marshaling support -* exp/draw: fast paths for a nil mask -* godoc: support for directories outside $GOROOT -* http: sort header keys when writing Response or Request to wire (thanks Petar Maymounkov) -* math: special cases and new functions (thanks Charles Dorian) -* mime: new package, used in http (thanks Michael Hoisie) -* net: dns bug fix - use random request id -* os: finalize File, to close fd. -* path: make Join variadic (thanks Stephen Weinberg) -* regexp: optimization bug fix -* runtime: misc fixes and optimizations -* syscall: make signature of Umask on OS X, FreeBSD match Linux. (thanks Giles Lean) -- -
-There is one language change: support for ...T parameters: - http://golang.org/doc/go_spec.html#Function_types - -You can now check build status on various platforms at the Go Dashboard: - http://godashboard.appspot.com - -* 5l/6l/8l: several minor fixes -* 5a/6a/8a/5l/6l/8l: avoid overflow of symb buffer (thanks Dean Prichard) -* compress/gzip: gzip deflater (i.e., writer) -* debug/proc: add mingw specific build stubs (thanks Joe Poirier) -* exp/draw: separate the source-point and mask-point in Draw -* fmt: handle nils safely in Printf -* gccgo: error messages now match those of gc -* godoc: several fixes -* http: bug fixes, revision of Request/Response (thanks Petar Maymounkov) -* image: new image.A type to represent anti-aliased font glyphs - add named colors (e.g. image.Blue), suitable for exp/draw -* io: fixed bugs in Pipe -* malloc: merge into package runtime -* math: fix tests on FreeBSD (thanks Devon H. O'Dell) - add functions; update tests and special cases (thanks Charles L. Dorian) -* os/signal: send SIGCHLDs to Incoming (thanks Chris Wedgwood) -* reflect: add StringHeader to reflect -* runtime: add SetFinalizer -* time: Sleep through interruptions (thanks Chris Wedgwood) - add RFC822 formats - experimental implementation of Ticker using two goroutines for all tickers -* xml: allow underscores in XML element names (thanks Michael Hoisie) - allow any scalar type in xml.Unmarshal -- -
-There are two small language changes: the meaning of chan <- chan int -is now defined, and functions returning functions do not need to -parenthesize the result type. - -There is one significant implementation change: the compilers can -handle multiple packages using the same name in a single binary. -In the gc compilers, this comes at the cost of ensuring that you -always import a particular package using a consistent import path. -In the gccgo compiler, the cost is that you must use the -fgo-prefix -flag to pass a unique prefix (like the eventual import path). - -5a/6a/8a: avoid use of fixed-size buffers (thanks Dean Prichard) -5g, 6g, 8g: many minor bug fixes -bufio: give Writer.WriteString same signature as bytes.Buffer.WriteString. -container/list: PushFrontList, PushBackList (thanks Jan Hosang) -godoc: trim spaces from search query (thanks Christopher Wedgwood) -hash: document that Sum does not change state, fix crypto hashes -http: bug fixes, revision of Request/Response (thanks Petar Maymounkov) -math: more handling of IEEE 754 special cases (thanks Charles Dorian) -misc/dashboard: new build dashboard -net: allow UDP broadcast, - use /etc/hosts to resolve names (thanks Yves Junqueira, Michael Hoisie) -netchan: beginnings of new package for connecting channels across a network -os: allow FQDN in Hostname test (thanks Icarus Sparry) -reflect: garbage collection bug in Call -runtime: demo of Go on raw (emulated) hw in runtime/pchw, - performance fix on OS X -spec: clarify meaning of chan <- chan int, - func() func() int is allowed now, - define ... T (not yet implemented) -template: can use interface values -time: fix for +0000 time zone, - more robust tick.Stop. -xgb: support for authenticated connections (thanks Firmansyah Adiputra) -xml: add Escape (thanks Stephen Weinberg) -- -
-This release is mainly bug fixes with a little new code. -There are no language changes. - -build: $GOBIN should no longer be required in $PATH (thanks Devon H. O'Dell), - new package target "make bench" to run benchmarks -8g: faster float -> uint64 conversion (thanks Evan Shaw) -5g, 6g, 8g: - clean opnames.h to avoid stale errors (thanks Yongjian Xu), - a handful of small compiler fixes -5g, 6g, 8g, 5l, 6l, 8l: ignore $GOARCH, which is implied by name of tool -6prof: support for writing input files for google-perftools's pprof -asn1: fix a few structure-handling bugs -cgo: many bug fixes (thanks Devon H. O'Dell) -codereview: repeated "hg mail" sends "please take another look" -gob: reserve ids for future expansion -godoc: distinguish HTML generation from plain text HTML escaping (thanks Roger Peppe) -gofmt: minor bug fixes, removed -oldprinter flag -http: add CanonicalPath (thanks Ivan Krasin), - avoid header duplication in Response.Write, - correctly escape/unescape URL sections -io: new interface ReadByter -json: better error, pointer handling in Marshal (thanks Ivan Krasin) -libmach: disassembly of FUCOMI, etc (thanks Evan Shaw) -math: special cases for most functions and 386 hardware Sqrt (thanks Charles Dorian) -misc/dashboard: beginning of a build dashboard at godashboard.appspot.com. -misc/emacs: handling of new semicolon rules (thanks Austin Clements), - empty buffer bug fix (thanks Kevin Ballard) -misc/kate: highlighting improvements (tahnks Evan Shaw) -os/signal: add signal names: signal.SIGHUP, etc (thanks David Symonds) -runtime: preliminary Windows support (thanks Hector Chu), - preemption polling to reduce garbage collector pauses -scanner: new lightweight scanner package -template: bug fix involving spaces before a delimited block -test/bench: updated timings -time: new Format, Parse functions -- -
-This release is mainly bug fixes. There are no language changes. - -6prof: now works on 386 -8a, 8l: add FCOMI, FCOMIP, FUCOMI, and FUCOMIP (thanks Evan Shaw) -big: fix ProbablyPrime on small numbers -container/vector: faster []-based implementation (thanks Jan Mercl) -crypto/tls: extensions and Next Protocol Negotiation -gob: one encoding bug fix, one decoding bug fix -image/jpeg: support for RST markers -image/png: support for transparent paletted images -misc/xcode: improved support (thanks Ken Friedenbach) -net: return nil Conn on error from Dial (thanks Roger Peppe) -regexp: add Regexp.NumSubexp (thanks Peter Froehlich) -syscall: add Nanosleep on FreeBSD (thanks Devon H. O'Dell) -template: can use map in .repeated section - -There is now a public road map, in the repository and online -at http://golang.org/doc/devel/roadmap.html. -- -
-Since the last release there has been one large syntactic change to -the language, already discussed extensively on this list: semicolons -are now implied between statement-ending tokens and newline characters. -See http://groups.google.com/group/golang-nuts/t/5ee32b588d10f2e9 for -details. - -By default, gofmt now parses and prints the new lighter weight syntax. -To convert programs written in the old syntax, you can use: - - gofmt -oldparser -w *.go - -Since everything was being reformatted anyway, we took the opportunity to -change the way gofmt does alignment. Now gofmt uses tabs at the start -of a line for basic code alignment, but it uses spaces for alignment of -interior columns. Thus, in an editor with a fixed-width font, you can -choose your own tab size to change the indentation, and no matter what -tab size you choose, columns will be aligned properly. - - -In addition to the syntax and formatting changes, there have been many -smaller fixes and updates: - -6g,8g,5g: many bug fixes, better registerization, - build process fix involving mkbuiltin (thanks Yongjian Xu), - method expressions for concrete types -8l: support for Windows PE files (thanks Hector Chu) -bytes: more efficient Buffer handling -bytes, strings: new function Fields (thanks Andrey Mirtchovski) -cgo: handling of enums (thanks Moriyoshi Koizumi), - handling of structs with bit fields, multiple files (thanks Devon H. O'Dell), - installation of .so to non-standard locations -crypto/sha256: new package for SHA 256 (thanks Andy Davis) -encoding/binary: support for slices of fixed-size values (thanks Maxim Ushakov) -exp/vector: experimental alternate vector representation (thanks Jan Mercl) -fmt: %p for chan, map, slice types -gob: a couple more bug fixes -http: support for basic authentication (thanks Ivan Krasin) -image/jpeg: basic JPEG decoder -math: correct handling of Inf and NaN in Pow (thanks Charles Dorian) -misc/bash: completion file for bash (thanks Alex Ray) -os/signal: support for handling Unix signals (thanks David Symonds) -rand: Zipf-distributed random values (thanks William Josephson) -syscall: correct error return bug on 32-bit machines (thanks Christopher Wedgwood) -syslog: new package for writing to Unix syslog daemon (thanks Yves Junqueira) -template: will automatically invoke niladic methods -time: new ISO8601 format generator (thanks Ben Olive) -xgb: converted generator to new syntax (thanks Tor Andersson) -xml: better mapping of tag names to Go identifiers (thanks Kei Son), - better handling of unexpected EOF (thanks Arvindh Rajesh Tamilmani) -- -
-Since the last release there are two changes to the language: - -* new builtin copy(dst, src) copies n = min(len(dst), len(src)) - elements to dst from src and returns n. It works correctly - even if dst and src overlap. bytes.Copy is gone. - Convert your programs using: - gofmt -w -r 'bytes.Copy(d, s) -> copy(d, s)' *.go - -* new syntax x[lo:] is shorthand for x[lo:len(x)]. - Convert your programs using: - gofmt -w -r 'a[b:len(a)] -> a[b:]' *.go - -In addition, there have been many smaller fixes and updates: - -* 6g/8g/5g: many bug fixes -* 8g: fix 386 floating point stack bug (thanks Charles Dorian) -* all.bash: now works even when $GOROOT has spaces (thanks Sergio Luis O. B. Correia), - starting to make build work with mingw (thanks Hector Chu), - FreeBSD support (thanks Devon O'Dell) -* big: much faster on 386. -* bytes: new function IndexByte, implemented in assembly - new function Runes (thanks Peter Froehlich), - performance tuning in bytes.Buffer. -* codereview: various bugs fixed -* container/vector: New is gone; just declare a Vector instead. - call Resize to set len and cap. -* cgo: many bug fixes (thanks Eden Li) -* crypto: added MD4 (thanks Chris Lennert), - added XTEA (thanks Adrian O'Grady). -* crypto/tls: basic client -* exp/iterable: new functions (thanks Michael Elkins) -* exp/nacl: native client tree builds again -* fmt: preliminary performance tuning -* go/ast: more powerful Visitor (thanks Roger Peppe) -* gob: a few bug fixes -* gofmt: better handling of standard input, error reporting (thanks Fazlul Shahriar) - new -r flag for rewriting programs -* gotest: support for Benchmark functions (thanks Trevor Strohman) -* io: ReadFile, WriteFile, ReadDir now in separate package io/ioutil. -* json: new Marshal function (thanks Michael Hoisie), - better white space handling (thanks Andrew Skiba), - decoding into native data structures (thanks Sergey Gromov), - handling of nil interface values (thanks Ross Light). -* math: correct handling of sin/cos of large angles -* net: better handling of Close (thanks Devon O'Dell and Christopher Wedgwood) - support for UDP broadcast (thanks Jonathan Wills), - support for empty packets -* rand: top-level functions now safe to call from multiple goroutines -(thanks Roger Peppe). -* regexp: a few easy optimizations -* rpc: better error handling, a few bug fixes -* runtime: better signal handling on OS X, malloc fixes, - global channel lock is gone. -* sync: RWMutex now allows concurrent readers (thanks Péter Szabó) -* template: can use maps as data (thanks James Meneghello) -* unicode: updated to Unicode 5.2. -* websocket: new package (thanks Fumitoshi Ukai) -* xgb: preliminary X Go Bindings (thanks Tor Andersson) -* xml: fixed crash (thanks Vish Subramanian) -* misc: bbedit config (thanks Anthony Starks), - kate config (thanks Evan Shaw) -diff --git a/content/doc/diagnostics.html b/content/doc/diagnostics.html deleted file mode 100644 index 478611c1..00000000 --- a/content/doc/diagnostics.html +++ /dev/null @@ -1,470 +0,0 @@ - - - - -
-The Go ecosystem provides a large suite of APIs and tools to -diagnose logic and performance problems in Go programs. This page -summarizes the available tools and helps Go users pick the right one -for their specific problem. -
- --Diagnostics solutions can be categorized into the following groups: -
- --Note: Some diagnostics tools may interfere with each other. For example, precise -memory profiling skews CPU profiles and goroutine blocking profiling affects scheduler -trace. Use tools in isolation to get more precise info. -
- -
-Profiling is useful for identifying expensive or frequently called sections
-of code. The Go runtime provides
-profiling data in the format expected by the
-pprof visualization tool.
-The profiling data can be collected during testing
-via go
test
or endpoints made available from the
-net/http/pprof package. Users need to collect the profiling data and use pprof tools to filter
-and visualize the top code paths.
-
Predefined profiles provided by the runtime/pprof package:
- -runtime.SetBlockProfileRate
to enable it.
-runtime.SetMutexProfileFraction
to enable it.
-What other profilers can I use to profile Go programs?
- --On Linux, perf tools -can be used for profiling Go programs. Perf can profile -and unwind cgo/SWIG code and kernel, so it can be useful to get insights into -native/kernel performance bottlenecks. On macOS, -Instruments -suite can be used profile Go programs. -
- -Can I profile my production services?
- -Yes. It is safe to profile programs in production, but enabling -some profiles (e.g. the CPU profile) adds cost. You should expect to -see performance downgrade. The performance penalty can be estimated -by measuring the overhead of the profiler before turning it on in -production. -
- --You may want to periodically profile your production services. -Especially in a system with many replicas of a single process, selecting -a random replica periodically is a safe option. -Select a production process, profile it for -X seconds for every Y seconds and save the results for visualization and -analysis; then repeat periodically. Results may be manually and/or automatically -reviewed to find problems. -Collection of profiles can interfere with each other, -so it is recommended to collect only a single profile at a time. -
- --What are the best ways to visualize the profiling data? -
- -
-The Go tools provide text, graph, and callgrind
-visualization of the profile data using
-go tool pprof
.
-Read Profiling Go programs
-to see them in action.
-
-
-
-Listing of the most expensive calls as text.
-
-
-
-Visualization of the most expensive calls as a graph.
-
Weblist view displays the expensive parts of the source line by line in
-an HTML page. In the following example, 530ms is spent in the
-runtime.concatstrings
and cost of each line is presented
-in the listing.
-
-
-Visualization of the most expensive calls as weblist.
-
-Another way to visualize profile data is a flame graph. -Flame graphs allow you to move in a specific ancestry path, so you can zoom -in/out of specific sections of code. -The upstream pprof -has support for flame graphs. -
- -
-
-
-Flame graphs offers visualization to spot the most expensive code-paths.
-
Am I restricted to the built-in profiles?
- --Additionally to what is provided by the runtime, Go users can create -their custom profiles via pprof.Profile -and use the existing tools to examine them. -
- -Can I serve the profiler handlers (/debug/pprof/...) on a different path and port?
- -
-Yes. The net/http/pprof
package registers its handlers to the default
-mux by default, but you can also register them yourself by using the handlers
-exported from the package.
-
-For example, the following example will serve the pprof.Profile -handler on :7777 at /custom_debug_path/profile: -
- --
-package main - -import ( - "log" - "net/http" - "net/http/pprof" -) - -func main() { - mux := http.NewServeMux() - mux.HandleFunc("/custom_debug_path/profile", pprof.Profile) - log.Fatal(http.ListenAndServe(":7777", mux)) -} -- - -
-Tracing is a way to instrument code to analyze latency throughout the -lifecycle of a chain of calls. Go provides -golang.org/x/net/trace -package as a minimal tracing backend per Go node and provides a minimal -instrumentation library with a simple dashboard. Go also provides -an execution tracer to trace the runtime events within an interval. -
- -Tracing enables us to:
- --In monolithic systems, it's relatively easy to collect diagnostic data -from the building blocks of a program. All modules live within one -process and share common resources to report logs, errors, and other -diagnostic information. Once your system grows beyond a single process and -starts to become distributed, it becomes harder to follow a call starting -from the front-end web server to all of its back-ends until a response is -returned back to the user. This is where distributed tracing plays a big -role to instrument and analyze your production systems. -
- --Distributed tracing is a way to instrument code to analyze latency throughout -the lifecycle of a user request. When a system is distributed and when -conventional profiling and debugging tools don’t scale, you might want -to use distributed tracing tools to analyze the performance of your user -requests and RPCs. -
- -Distributed tracing enables us to:
- -The Go ecosystem provides various distributed tracing libraries per tracing system -and backend-agnostic ones.
- - -Is there a way to automatically intercept each function call and create traces?
- --Go doesn’t provide a way to automatically intercept every function call and create -trace spans. You need to manually instrument your code to create, end, and annotate spans. -
- -How should I propagate trace headers in Go libraries?
- -
-You can propagate trace identifiers and tags in the
-context.Context
.
-There is no canonical trace key or common representation of trace headers
-in the industry yet. Each tracing provider is responsible for providing propagation
-utilities in their Go libraries.
-
-What other low-level events from the standard library or -runtime can be included in a trace? -
- -
-The standard library and runtime are trying to expose several additional APIs
-to notify on low level internal events. For example,
-httptrace.ClientTrace
-provides APIs to follow low-level events in the life cycle of an outgoing request.
-There is an ongoing effort to retrieve low-level runtime events from
-the runtime execution tracer and allow users to define and record their user events.
-
-Debugging is the process of identifying why a program misbehaves. -Debuggers allow us to understand a program’s execution flow and current state. -There are several styles of debugging; this section will only focus on attaching -a debugger to a program and core dump debugging. -
- -Go users mostly use the following debuggers:
- -How well do debuggers work with Go programs?
- -
-The gc
compiler performs optimizations such as
-function inlining and variable registerization. These optimizations
-sometimes make debugging with debuggers harder. There is an ongoing
-effort to improve the quality of the DWARF information generated for
-optimized binaries. Until those improvements are available, we recommend
-disabling optimizations when building the code being debugged. The following
-command builds a package with no compiler optimizations:
-
-
-
-$ go build -gcflags=all="-N -l" -- - -As part of the improvement effort, Go 1.10 introduced a new compiler -flag
-dwarflocationlists
. The flag causes the compiler to
-add location lists that helps debuggers work with optimized binaries.
-The following command builds a package with optimizations but with
-the DWARF location lists:
-
--
-$ go build -gcflags="-dwarflocationlists=true" -- - -
What’s the recommended debugger user interface?
- --Even though both delve and gdb provides CLIs, most editor integrations -and IDEs provides debugging-specific user interfaces. -
- -Is it possible to do postmortem debugging with Go programs?
- --A core dump file is a file that contains the memory dump of a running -process and its process status. It is primarily used for post-mortem -debugging of a program and to understand its state -while it is still running. These two cases make debugging of core -dumps a good diagnostic aid to postmortem and analyze production -services. It is possible to obtain core files from Go programs and -use delve or gdb to debug, see the -core dump debugging -page for a step-by-step guide. -
- --The runtime provides stats and reporting of internal events for -users to diagnose performance and utilization problems at the -runtime level. -
- --Users can monitor these stats to better understand the overall -health and performance of Go programs. -Some frequently monitored stats and states: -
- -runtime.ReadMemStats
-reports the metrics related to heap
-allocation and garbage collection. Memory stats are useful for
-monitoring how much memory resources a process is consuming,
-whether the process can utilize memory well, and to catch
-memory leaks.debug.ReadGCStats
-reads statistics about garbage collection.
-It is useful to see how much of the resources are spent on GC pauses.
-It also reports a timeline of garbage collector pauses and pause time percentiles.debug.Stack
-returns the current stack trace. Stack trace
-is useful to see how many goroutines are currently running,
-what they are doing, and whether they are blocked or not.debug.WriteHeapDump
-suspends the execution of all goroutines
-and allows you to dump the heap to a file. A heap dump is a
-snapshot of a Go process' memory at a given time. It contains all
-allocated objects as well as goroutines, finalizers, and more.runtime.NumGoroutine
-returns the number of current goroutines.
-The value can be monitored to see whether enough goroutines are
-utilized, or to detect goroutine leaks.Go comes with a runtime execution tracer to capture a wide range -of runtime events. Scheduling, syscall, garbage collections, -heap size, and other events are collected by runtime and available -for visualization by the go tool trace. Execution tracer is a tool -to detect latency and utilization problems. You can examine how well -the CPU is utilized, and when networking or syscalls are a cause of -preemption for the goroutines.
- -Tracer is useful to:
-However, it is not great for identifying hot spots such as -analyzing the cause of excessive memory or CPU usage. -Use profiling tools instead first to address them.
- -- -
- -Above, the go tool trace visualization shows the execution started -fine, and then it became serialized. It suggests that there might -be lock contention for a shared resource that creates a bottleneck.
- -See go
tool
trace
-to collect and analyze runtime traces.
-
Runtime also emits events and information if -GODEBUG -environmental variable is set accordingly.
- -The GODEBUG environmental variable can be used to disable use of -instruction set extensions in the standard library and runtime.
- --The Go programming language is an open source project to make programmers more -productive. -
- --Go is expressive, concise, clean, and efficient. Its concurrency -mechanisms make it easy to write programs that get the most out of multicore -and networked machines, while its novel type system enables flexible and -modular program construction. Go compiles quickly to machine code yet has the -convenience of garbage collection and the power of run-time reflection. It's a -fast, statically typed, compiled language that feels like a dynamically typed, -interpreted language. -
- - - --Instructions for downloading and installing the Go compilers, tools, and -libraries. -
- - --An interactive introduction to Go in three sections. -The first section covers basic syntax and data structures; the second discusses -methods and interfaces; and the third introduces Go's concurrency primitives. -Each section concludes with a few exercises so you can practice what you've -learned. You can {{if not $.GoogleCN}}take the tour -online or{{end}} install it locally with: -
--$ go get golang.org/x/tour --
-This will place the tour
binary in your workspace's bin
directory.
-
-{{if not $.GoogleCN}} -Also available as a screencast, this -{{else}} -This -{{end}} -doc explains how to use the go command -to fetch, build, and install packages, commands, and run tests. -
- --A document that summarizes commonly used editor plugins and IDEs with -Go support. -
- --A document that gives tips for writing clear, idiomatic Go code. -A must read for any new Go programmer. It augments the tour and -the language specification, both of which should be read first. -
- --Summarizes tools and methodologies to diagnose problems in Go programs. -
- --Answers to common questions about Go. -
- -A wiki maintained by the Go community.
- --See the Learn page at the Wiki -for more Go learning resources. -
- - --The documentation for the Go standard library. -
- --The documentation for the Go tools. -
- --The official Go Language specification. -
- --A document that specifies the conditions under which reads of a variable in -one goroutine can be guaranteed to observe values produced by writes to the -same variable in a different goroutine. -
- -A summary of the changes between Go releases.
- - -The official blog of the Go project, featuring news and in-depth articles by -the Go team and guests.
-{{end}} - --Guided tours of Go programs. -
--See the Articles page at the -Wiki for more Go articles. -
- -{{if not $.GoogleCN}} --Three things that make Go fast, fun, and productive: -interfaces, reflection, and concurrency. Builds a toy web crawler to -demonstrate these. -
- --One of Go's key design goals is code adaptability; that it should be easy to take a simple design and build upon it in a clean and natural way. In this talk Andrew Gerrand describes a simple "chat roulette" server that matches pairs of incoming TCP connections, and then use Go's concurrency mechanisms, interfaces, and standard library to extend it with a web interface and other features. While the function of the program changes dramatically, Go's flexibility preserves the original design as it grows. -
- --Concurrency is the key to designing high performance network services. Go's concurrency primitives (goroutines and channels) provide a simple and efficient means of expressing concurrent execution. In this talk we see how tricky concurrency problems can be solved gracefully with simple Go code. -
- --This talk expands on the Go Concurrency Patterns talk to dive deeper into Go's concurrency primitives. -
- --See the Go Talks site and wiki page for more Go talks. -
-{{end}} - --See the NonEnglish page -at the Wiki for localized -documentation. -
diff --git a/content/doc/editors.html b/content/doc/editors.html deleted file mode 100644 index 4ff35a58..00000000 --- a/content/doc/editors.html +++ /dev/null @@ -1,35 +0,0 @@ - - -- This document lists commonly used editor plugins and IDEs from the Go ecosystem - that make Go development more productive and seamless. - A comprehensive list of editor support and IDEs for Go development is available at - the wiki. -
- --The Go ecosystem provides a variety of editor plugins and IDEs to enhance your day-to-day -editing, navigation, testing, and debugging experience. -
- --Note that these are only a few top solutions; a more comprehensive -community-maintained list of -IDEs and text editor plugins -is available at the Wiki. -
diff --git a/content/doc/effective_go.html b/content/doc/effective_go.html deleted file mode 100644 index ddfea76d..00000000 --- a/content/doc/effective_go.html +++ /dev/null @@ -1,3668 +0,0 @@ - - --Go is a new language. Although it borrows ideas from -existing languages, -it has unusual properties that make effective Go programs -different in character from programs written in its relatives. -A straightforward translation of a C++ or Java program into Go -is unlikely to produce a satisfactory result—Java programs -are written in Java, not Go. -On the other hand, thinking about the problem from a Go -perspective could produce a successful but quite different -program. -In other words, -to write Go well, it's important to understand its properties -and idioms. -It's also important to know the established conventions for -programming in Go, such as naming, formatting, program -construction, and so on, so that programs you write -will be easy for other Go programmers to understand. -
- --This document gives tips for writing clear, idiomatic Go code. -It augments the language specification, -the Tour of Go, -and How to Write Go Code, -all of which you -should read first. -
- --The Go package sources -are intended to serve not -only as the core library but also as examples of how to -use the language. -Moreover, many of the packages contain working, self-contained -executable examples you can run directly from the -golang.org web site, such as -this one (if -necessary, click on the word "Example" to open it up). -If you have a question about how to approach a problem or how something -might be implemented, the documentation, code and examples in the -library can provide answers, ideas and -background. -
- - --Formatting issues are the most contentious -but the least consequential. -People can adapt to different formatting styles -but it's better if they don't have to, and -less time is devoted to the topic -if everyone adheres to the same style. -The problem is how to approach this Utopia without a long -prescriptive style guide. -
- -
-With Go we take an unusual
-approach and let the machine
-take care of most formatting issues.
-The gofmt
program
-(also available as go fmt
, which
-operates at the package level rather than source file level)
-reads a Go program
-and emits the source in a standard style of indentation
-and vertical alignment, retaining and if necessary
-reformatting comments.
-If you want to know how to handle some new layout
-situation, run gofmt
; if the answer doesn't
-seem right, rearrange your program (or file a bug about gofmt
),
-don't work around it.
-
-As an example, there's no need to spend time lining up
-the comments on the fields of a structure.
-Gofmt
will do that for you. Given the
-declaration
-
-type T struct { - name string // name of the object - value int // its value -} -- -
-gofmt
will line up the columns:
-
-type T struct { - name string // name of the object - value int // its value -} -- -
-All Go code in the standard packages has been formatted with gofmt
.
-
-Some formatting details remain. Very briefly: -
- -gofmt
emits them by default.
- Use spaces only if you must.
- if
,
- for
, switch
) do not have parentheses in
- their syntax.
- Also, the operator precedence hierarchy is shorter and clearer, so
--x<<8 + y<<16 -- means what the spacing implies, unlike in the other languages. -
-Go provides C-style /* */
block comments
-and C++-style //
line comments.
-Line comments are the norm;
-block comments appear mostly as package comments, but
-are useful within an expression or to disable large swaths of code.
-
-The program—and web server—godoc
processes
-Go source files to extract documentation about the contents of the
-package.
-Comments that appear before top-level declarations, with no intervening newlines,
-are extracted along with the declaration to serve as explanatory text for the item.
-The nature and style of these comments determines the
-quality of the documentation godoc
produces.
-
-Every package should have a package comment, a block
-comment preceding the package clause.
-For multi-file packages, the package comment only needs to be
-present in one file, and any one will do.
-The package comment should introduce the package and
-provide information relevant to the package as a whole.
-It will appear first on the godoc
page and
-should set up the detailed documentation that follows.
-
-/* -Package regexp implements a simple library for regular expressions. - -The syntax of the regular expressions accepted is: - - regexp: - concatenation { '|' concatenation } - concatenation: - { closure } - closure: - term [ '*' | '+' | '?' ] - term: - '^' - '$' - '.' - character - '[' [ '^' ] character-ranges ']' - '(' regexp ')' -*/ -package regexp -- -
-If the package is simple, the package comment can be brief. -
- --// Package path implements utility routines for -// manipulating slash-separated filename paths. -- -
-Comments do not need extra formatting such as banners of stars.
-The generated output may not even be presented in a fixed-width font, so don't depend
-on spacing for alignment—godoc
, like gofmt
,
-takes care of that.
-The comments are uninterpreted plain text, so HTML and other
-annotations such as _this_
will reproduce verbatim and should
-not be used.
-One adjustment godoc
does do is to display indented
-text in a fixed-width font, suitable for program snippets.
-The package comment for the
-fmt
package uses this to good effect.
-
-Depending on the context, godoc
might not even
-reformat comments, so make sure they look good straight up:
-use correct spelling, punctuation, and sentence structure,
-fold long lines, and so on.
-
-Inside a package, any comment immediately preceding a top-level declaration -serves as a doc comment for that declaration. -Every exported (capitalized) name in a program should -have a doc comment. -
- --Doc comments work best as complete sentences, which allow -a wide variety of automated presentations. -The first sentence should be a one-sentence summary that -starts with the name being declared. -
- --// Compile parses a regular expression and returns, if successful, -// a Regexp that can be used to match against text. -func Compile(str string) (*Regexp, error) { -- -
-If every doc comment begins with the name of the item it describes,
-you can use the doc
-subcommand of the go tool
-and run the output through grep
.
-Imagine you couldn't remember the name "Compile" but were looking for
-the parsing function for regular expressions, so you ran
-the command,
-
-$ go doc -all regexp | grep -i parse -- -
-If all the doc comments in the package began, "This function...", grep
-wouldn't help you remember the name. But because the package starts each
-doc comment with the name, you'd see something like this,
-which recalls the word you're looking for.
-
-$ go doc -all regexp | grep -i parse - Compile parses a regular expression and returns, if successful, a Regexp - MustCompile is like Compile but panics if the expression cannot be parsed. - parsed. It simplifies safe initialization of global variables holding -$ -- -
-Go's declaration syntax allows grouping of declarations. -A single doc comment can introduce a group of related constants or variables. -Since the whole declaration is presented, such a comment can often be perfunctory. -
- --// Error codes returned by failures to parse an expression. -var ( - ErrInternal = errors.New("regexp: internal error") - ErrUnmatchedLpar = errors.New("regexp: unmatched '('") - ErrUnmatchedRpar = errors.New("regexp: unmatched ')'") - ... -) -- -
-Grouping can also indicate relationships between items, -such as the fact that a set of variables is protected by a mutex. -
- --var ( - countLock sync.Mutex - inputCount uint32 - outputCount uint32 - errorCount uint32 -) -- -
-Names are as important in Go as in any other language. -They even have semantic effect: -the visibility of a name outside a package is determined by whether its -first character is upper case. -It's therefore worth spending a little time talking about naming conventions -in Go programs. -
- - --When a package is imported, the package name becomes an accessor for the -contents. After -
- --import "bytes" -- -
-the importing package can talk about bytes.Buffer
. It's
-helpful if everyone using the package can use the same name to refer to
-its contents, which implies that the package name should be good:
-short, concise, evocative. By convention, packages are given
-lower case, single-word names; there should be no need for underscores
-or mixedCaps.
-Err on the side of brevity, since everyone using your
-package will be typing that name.
-And don't worry about collisions a priori.
-The package name is only the default name for imports; it need not be unique
-across all source code, and in the rare case of a collision the
-importing package can choose a different name to use locally.
-In any case, confusion is rare because the file name in the import
-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/encoding/base64
-is imported as "encoding/base64"
but has name base64
,
-not encoding_base64
and not encodingBase64
.
-
-The importer of a package will use the name to refer to its contents,
-so exported names in the package can use that fact
-to avoid stutter.
-(Don't use the import .
notation, which can simplify
-tests that must run outside the package they are testing, but should otherwise be avoided.)
-For instance, the buffered reader type in the bufio
package is called Reader
,
-not BufReader
, because users see it as bufio.Reader
,
-which is a clear, concise name.
-Moreover,
-because imported entities are always addressed with their package name, bufio.Reader
-does not conflict with io.Reader
.
-Similarly, the function to make new instances of ring.Ring
—which
-is the definition of a constructor in Go—would
-normally be called NewRing
, but since
-Ring
is the only type exported by the package, and since the
-package is called ring
, it's called just New
,
-which clients of the package see as ring.New
.
-Use the package structure to help you choose good names.
-
-Another short example is once.Do
;
-once.Do(setup)
reads well and would not be improved by
-writing once.DoOrWaitUntilDone(setup)
.
-Long names don't automatically make things more readable.
-A helpful doc comment can often be more valuable than an extra long name.
-
-Go doesn't provide automatic support for getters and setters.
-There's nothing wrong with providing getters and setters yourself,
-and it's often appropriate to do so, but it's neither idiomatic nor necessary
-to put Get
into the getter's name. If you have a field called
-owner
(lower case, unexported), the getter method should be
-called Owner
(upper case, exported), not GetOwner
.
-The use of upper-case names for export provides the hook to discriminate
-the field from the method.
-A setter function, if needed, will likely be called SetOwner
.
-Both names read well in practice:
-
-owner := obj.Owner() -if owner != user { - obj.SetOwner(user) -} -- -
-By convention, one-method interfaces are named by
-the method name plus an -er suffix or similar modification
-to construct an agent noun: Reader
,
-Writer
, Formatter
,
-CloseNotifier
etc.
-
-There are a number of such names and it's productive to honor them and the function
-names they capture.
-Read
, Write
, Close
, Flush
,
-String
and so on have
-canonical signatures and meanings. To avoid confusion,
-don't give your method one of those names unless it
-has the same signature and meaning.
-Conversely, if your type implements a method with the
-same meaning as a method on a well-known type,
-give it the same name and signature;
-call your string-converter method String
not ToString
.
-
-Finally, the convention in Go is to use MixedCaps
-or mixedCaps
rather than underscores to write
-multiword names.
-
-Like C, Go's formal grammar uses semicolons to terminate statements, -but unlike in C, those semicolons do not appear in the source. -Instead the lexer uses a simple rule to insert semicolons automatically -as it scans, so the input text is mostly free of them. -
- -
-The rule is this. If the last token before a newline is an identifier
-(which includes words like int
and float64
),
-a basic literal such as a number or string constant, or one of the
-tokens
-
-break continue fallthrough return ++ -- ) } --
-the lexer always inserts a semicolon after the token. -This could be summarized as, “if the newline comes -after a token that could end a statement, insert a semicolon”. -
- --A semicolon can also be omitted immediately before a closing brace, -so a statement such as -
-- go func() { for { dst <- <-src } }() --
-needs no semicolons.
-Idiomatic Go programs have semicolons only in places such as
-for
loop clauses, to separate the initializer, condition, and
-continuation elements. They are also necessary to separate multiple
-statements on a line, should you write code that way.
-
-One consequence of the semicolon insertion rules
-is that you cannot put the opening brace of a
-control structure (if
, for
, switch
,
-or select
) on the next line. If you do, a semicolon
-will be inserted before the brace, which could cause unwanted
-effects. Write them like this
-
-if i < f() { - g() -} --
-not like this -
--if i < f() // wrong! -{ // wrong! - g() -} -- - -
-The control structures of Go are related to those of C but differ
-in important ways.
-There is no do
or while
loop, only a
-slightly generalized
-for
;
-switch
is more flexible;
-if
and switch
accept an optional
-initialization statement like that of for
;
-break
and continue
statements
-take an optional label to identify what to break or continue;
-and there are new control structures including a type switch and a
-multiway communications multiplexer, select
.
-The syntax is also slightly different:
-there are no parentheses
-and the bodies must always be brace-delimited.
-
-In Go a simple if
looks like this:
-
-if x > 0 { - return y -} -- -
-Mandatory braces encourage writing simple if
statements
-on multiple lines. It's good style to do so anyway,
-especially when the body contains a control statement such as a
-return
or break
.
-
-Since if
and switch
accept an initialization
-statement, it's common to see one used to set up a local variable.
-
-if err := file.Chmod(0664); err != nil { - log.Print(err) - return err -} -- -
-In the Go libraries, you'll find that
-when an if
statement doesn't flow into the next statement—that is,
-the body ends in break
, continue
,
-goto
, or return
—the unnecessary
-else
is omitted.
-
-f, err := os.Open(name) -if err != nil { - return err -} -codeUsing(f) -- -
-This is an example of a common situation where code must guard against a
-sequence of error conditions. The code reads well if the
-successful flow of control runs down the page, eliminating error cases
-as they arise. Since error cases tend to end in return
-statements, the resulting code needs no else
statements.
-
-f, err := os.Open(name) -if err != nil { - return err -} -d, err := f.Stat() -if err != nil { - f.Close() - return err -} -codeUsing(f, d) -- - -
-An aside: The last example in the previous section demonstrates a detail of how the
-:=
short declaration form works.
-The declaration that calls os.Open
reads,
-
-f, err := os.Open(name) -- -
-This statement declares two variables, f
and err
.
-A few lines later, the call to f.Stat
reads,
-
-d, err := f.Stat() -- -
-which looks as if it declares d
and err
.
-Notice, though, that err
appears in both statements.
-This duplication is legal: err
is declared by the first statement,
-but only re-assigned in the second.
-This means that the call to f.Stat
uses the existing
-err
variable declared above, and just gives it a new value.
-
-In a :=
declaration a variable v
may appear even
-if it has already been declared, provided:
-
v
-(if v
is already declared in an outer scope, the declaration will create a new variable §),v
, and
-This unusual property is pure pragmatism,
-making it easy to use a single err
value, for example,
-in a long if-else
chain.
-You'll see it used often.
-
-§ It's worth noting here that in Go the scope of function parameters and return values -is the same as the function body, even though they appear lexically outside the braces -that enclose the body. -
- -
-The Go for
loop is similar to—but not the same as—C's.
-It unifies for
-and while
and there is no do-while
.
-There are three forms, only one of which has semicolons.
-
-// Like a C for -for init; condition; post { } - -// Like a C while -for condition { } - -// Like a C for(;;) -for { } -- -
-Short declarations make it easy to declare the index variable right in the loop. -
--sum := 0 -for i := 0; i < 10; i++ { - sum += i -} -- -
-If you're looping over an array, slice, string, or map,
-or reading from a channel, a range
clause can
-manage the loop.
-
-for key, value := range oldMap { - newMap[key] = value -} -- -
-If you only need the first item in the range (the key or index), drop the second: -
--for key := range m { - if key.expired() { - delete(m, key) - } -} -- -
-If you only need the second item in the range (the value), use the blank identifier, an underscore, to discard the first: -
--sum := 0 -for _, value := range array { - sum += value -} -- -
-The blank identifier has many uses, as described in a later section. -
- -
-For strings, the range
does more work for you, breaking out individual
-Unicode code points by parsing the UTF-8.
-Erroneous encodings consume one byte and produce the
-replacement rune U+FFFD.
-(The name (with associated builtin type) rune
is Go terminology for a
-single Unicode code point.
-See the language specification
-for details.)
-The loop
-
-for pos, char := range "日本\x80語" { // \x80 is an illegal UTF-8 encoding - fmt.Printf("character %#U starts at byte position %d\n", char, pos) -} --
-prints -
--character U+65E5 '日' starts at byte position 0 -character U+672C '本' starts at byte position 3 -character U+FFFD '�' starts at byte position 6 -character U+8A9E '語' starts at byte position 7 -- -
-Finally, Go has no comma operator and ++
and --
-are statements not expressions.
-Thus if you want to run multiple variables in a for
-you should use parallel assignment (although that precludes ++
and --
).
-
-// Reverse a -for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 { - a[i], a[j] = a[j], a[i] -} -- -
-Go's switch
is more general than C's.
-The expressions need not be constants or even integers,
-the cases are evaluated top to bottom until a match is found,
-and if the switch
has no expression it switches on
-true
.
-It's therefore possible—and idiomatic—to write an
-if
-else
-if
-else
-chain as a switch
.
-
-func unhex(c byte) byte { - switch { - case '0' <= c && c <= '9': - return c - '0' - case 'a' <= c && c <= 'f': - return c - 'a' + 10 - case 'A' <= c && c <= 'F': - return c - 'A' + 10 - } - return 0 -} -- -
-There is no automatic fall through, but cases can be presented -in comma-separated lists. -
--func shouldEscape(c byte) bool { - switch c { - case ' ', '?', '&', '=', '#', '+', '%': - return true - } - return false -} -- -
-Although they are not nearly as common in Go as some other C-like
-languages, break
statements can be used to terminate
-a switch
early.
-Sometimes, though, it's necessary to break out of a surrounding loop,
-not the switch, and in Go that can be accomplished by putting a label
-on the loop and "breaking" to that label.
-This example shows both uses.
-
-Loop: - for n := 0; n < len(src); n += size { - switch { - case src[n] < sizeOne: - if validateOnly { - break - } - size = 1 - update(src[n]) - - case src[n] < sizeTwo: - if n+1 >= len(src) { - err = errShortInput - break Loop - } - if validateOnly { - break - } - size = 2 - update(src[n] + src[n+1]<<shift) - } - } -- -
-Of course, the continue
statement also accepts an optional label
-but it applies only to loops.
-
-To close this section, here's a comparison routine for byte slices that uses two
-switch
statements:
-
-// Compare returns an integer comparing the two byte slices, -// lexicographically. -// The result will be 0 if a == b, -1 if a < b, and +1 if a > b -func Compare(a, b []byte) int { - for i := 0; i < len(a) && i < len(b); i++ { - switch { - case a[i] > b[i]: - return 1 - case a[i] < b[i]: - return -1 - } - } - switch { - case len(a) > len(b): - return 1 - case len(a) < len(b): - return -1 - } - return 0 -} -- -
-A switch can also be used to discover the dynamic type of an interface
-variable. Such a type switch uses the syntax of a type
-assertion with the keyword type
inside the parentheses.
-If the switch declares a variable in the expression, the variable will
-have the corresponding type in each clause.
-It's also idiomatic to reuse the name in such cases, in effect declaring
-a new variable with the same name but a different type in each case.
-
-var t interface{} -t = functionOfSomeType() -switch t := t.(type) { -default: - fmt.Printf("unexpected type %T\n", t) // %T prints whatever type t has -case bool: - fmt.Printf("boolean %t\n", t) // t has type bool -case int: - fmt.Printf("integer %d\n", t) // t has type int -case *bool: - fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool -case *int: - fmt.Printf("pointer to integer %d\n", *t) // t has type *int -} -- -
-One of Go's unusual features is that functions and methods
-can return multiple values. This form can be used to
-improve on a couple of clumsy idioms in C programs: in-band
-error returns such as -1
for EOF
-and modifying an argument passed by address.
-
-In C, a write error is signaled by a negative count with the
-error code secreted away in a volatile location.
-In Go, Write
-can return a count and an error: “Yes, you wrote some
-bytes but not all of them because you filled the device”.
-The signature of the Write
method on files from
-package os
is:
-
-func (file *File) Write(b []byte) (n int, err error) -- -
-and as the documentation says, it returns the number of bytes
-written and a non-nil error
when n
-!=
len(b)
.
-This is a common style; see the section on error handling for more examples.
-
-A similar approach obviates the need to pass a pointer to a return -value to simulate a reference parameter. -Here's a simple-minded function to -grab a number from a position in a byte slice, returning the number -and the next position. -
- --func nextInt(b []byte, i int) (int, int) { - for ; i < len(b) && !isDigit(b[i]); i++ { - } - x := 0 - for ; i < len(b) && isDigit(b[i]); i++ { - x = x*10 + int(b[i]) - '0' - } - return x, i -} -- -
-You could use it to scan the numbers in an input slice b
like this:
-
- for i := 0; i < len(b); { - x, i = nextInt(b, i) - fmt.Println(x) - } -- -
-The return or result "parameters" of a Go function can be given names and
-used as regular variables, just like the incoming parameters.
-When named, they are initialized to the zero values for their types when
-the function begins; if the function executes a return
statement
-with no arguments, the current values of the result parameters are
-used as the returned values.
-
-The names are not mandatory but they can make code shorter and clearer:
-they're documentation.
-If we name the results of nextInt
it becomes
-obvious which returned int
-is which.
-
-func nextInt(b []byte, pos int) (value, nextPos int) { -- -
-Because named results are initialized and tied to an unadorned return, they can simplify
-as well as clarify. Here's a version
-of io.ReadFull
that uses them well:
-
-func ReadFull(r Reader, buf []byte) (n int, err error) { - for len(buf) > 0 && err == nil { - var nr int - nr, err = r.Read(buf) - n += nr - buf = buf[nr:] - } - return -} -- -
-Go's defer
statement schedules a function call (the
-deferred function) to be run immediately before the function
-executing the defer
returns. It's an unusual but
-effective way to deal with situations such as resources that must be
-released regardless of which path a function takes to return. The
-canonical examples are unlocking a mutex or closing a file.
-
-// Contents returns the file's contents as a string. -func Contents(filename string) (string, error) { - f, err := os.Open(filename) - if err != nil { - return "", err - } - defer f.Close() // f.Close will run when we're finished. - - var result []byte - buf := make([]byte, 100) - for { - n, err := f.Read(buf[0:]) - result = append(result, buf[0:n]...) // append is discussed later. - if err != nil { - if err == io.EOF { - break - } - return "", err // f will be closed if we return here. - } - } - return string(result), nil // f will be closed if we return here. -} -- -
-Deferring a call to a function such as Close
has two advantages. First, it
-guarantees that you will never forget to close the file, a mistake
-that's easy to make if you later edit the function to add a new return
-path. Second, it means that the close sits near the open,
-which is much clearer than placing it at the end of the function.
-
-The arguments to the deferred function (which include the receiver if -the function is a method) are evaluated when the defer -executes, not when the call executes. Besides avoiding worries -about variables changing values as the function executes, this means -that a single deferred call site can defer multiple function -executions. Here's a silly example. -
- --for i := 0; i < 5; i++ { - defer fmt.Printf("%d ", i) -} -- -
-Deferred functions are executed in LIFO order, so this code will cause
-4 3 2 1 0
to be printed when the function returns. A
-more plausible example is a simple way to trace function execution
-through the program. We could write a couple of simple tracing
-routines like this:
-
-func trace(s string) { fmt.Println("entering:", s) } -func untrace(s string) { fmt.Println("leaving:", s) } - -// Use them like this: -func a() { - trace("a") - defer untrace("a") - // do something.... -} -- -
-We can do better by exploiting the fact that arguments to deferred
-functions are evaluated when the defer
executes. The
-tracing routine can set up the argument to the untracing routine.
-This example:
-
-func trace(s string) string { - fmt.Println("entering:", s) - return s -} - -func un(s string) { - fmt.Println("leaving:", s) -} - -func a() { - defer un(trace("a")) - fmt.Println("in a") -} - -func b() { - defer un(trace("b")) - fmt.Println("in b") - a() -} - -func main() { - b() -} -- -
-prints -
- --entering: b -in b -entering: a -in a -leaving: a -leaving: b -- -
-For programmers accustomed to block-level resource management from
-other languages, defer
may seem peculiar, but its most
-interesting and powerful applications come precisely from the fact
-that it's not block-based but function-based. In the section on
-panic
and recover
we'll see another
-example of its possibilities.
-
new
-Go has two allocation primitives, the built-in functions
-new
and make
.
-They do different things and apply to different types, which can be confusing,
-but the rules are simple.
-Let's talk about new
first.
-It's a built-in function that allocates memory, but unlike its namesakes
-in some other languages it does not initialize the memory,
-it only zeros it.
-That is,
-new(T)
allocates zeroed storage for a new item of type
-T
and returns its address, a value of type *T
.
-In Go terminology, it returns a pointer to a newly allocated zero value of type
-T
.
-
-Since the memory returned by new
is zeroed, it's helpful to arrange
-when designing your data structures that the
-zero value of each type can be used without further initialization. This means a user of
-the data structure can create one with new
and get right to
-work.
-For example, the documentation for bytes.Buffer
states that
-"the zero value for Buffer
is an empty buffer ready to use."
-Similarly, sync.Mutex
does not
-have an explicit constructor or Init
method.
-Instead, the zero value for a sync.Mutex
-is defined to be an unlocked mutex.
-
-The zero-value-is-useful property works transitively. Consider this type declaration. -
- --type SyncedBuffer struct { - lock sync.Mutex - buffer bytes.Buffer -} -- -
-Values of type SyncedBuffer
are also ready to use immediately upon allocation
-or just declaration. In the next snippet, both p
and v
will work
-correctly without further arrangement.
-
-p := new(SyncedBuffer) // type *SyncedBuffer -var v SyncedBuffer // type SyncedBuffer -- -
-Sometimes the zero value isn't good enough and an initializing
-constructor is necessary, as in this example derived from
-package os
.
-
-func NewFile(fd int, name string) *File { - if fd < 0 { - return nil - } - f := new(File) - f.fd = fd - f.name = name - f.dirinfo = nil - f.nepipe = 0 - return f -} -- -
-There's a lot of boiler plate in there. We can simplify it -using a composite literal, which is -an expression that creates a -new instance each time it is evaluated. -
- --func NewFile(fd int, name string) *File { - if fd < 0 { - return nil - } - f := File{fd, name, nil, 0} - return &f -} -- -
-Note that, unlike in C, it's perfectly OK to return the address of a local variable; -the storage associated with the variable survives after the function -returns. -In fact, taking the address of a composite literal -allocates a fresh instance each time it is evaluated, -so we can combine these last two lines. -
- -- return &File{fd, name, nil, 0} -- -
-The fields of a composite literal are laid out in order and must all be present.
-However, by labeling the elements explicitly as field:
value
-pairs, the initializers can appear in any
-order, with the missing ones left as their respective zero values. Thus we could say
-
- return &File{fd: fd, name: name} -- -
-As a limiting case, if a composite literal contains no fields at all, it creates
-a zero value for the type. The expressions new(File)
and &File{}
are equivalent.
-
-Composite literals can also be created for arrays, slices, and maps,
-with the field labels being indices or map keys as appropriate.
-In these examples, the initializations work regardless of the values of Enone
,
-Eio
, and Einval
, as long as they are distinct.
-
-a := [...]string {Enone: "no error", Eio: "Eio", Einval: "invalid argument"} -s := []string {Enone: "no error", Eio: "Eio", Einval: "invalid argument"} -m := map[int]string{Enone: "no error", Eio: "Eio", Einval: "invalid argument"} -- -
make
-Back to allocation.
-The built-in function make(T,
args)
serves
-a purpose different from new(T)
.
-It creates slices, maps, and channels only, and it returns an initialized
-(not zeroed)
-value of type T
(not *T
).
-The reason for the distinction
-is that these three types represent, under the covers, references to data structures that
-must be initialized before use.
-A slice, for example, is a three-item descriptor
-containing a pointer to the data (inside an array), the length, and the
-capacity, and until those items are initialized, the slice is nil
.
-For slices, maps, and channels,
-make
initializes the internal data structure and prepares
-the value for use.
-For instance,
-
-make([]int, 10, 100) -- -
-allocates an array of 100 ints and then creates a slice
-structure with length 10 and a capacity of 100 pointing at the first
-10 elements of the array.
-(When making a slice, the capacity can be omitted; see the section on slices
-for more information.)
-In contrast, new([]int)
returns a pointer to a newly allocated, zeroed slice
-structure, that is, a pointer to a nil
slice value.
-
-These examples illustrate the difference between new
and
-make
.
-
-var p *[]int = new([]int) // allocates slice structure; *p == nil; rarely useful -var v []int = make([]int, 100) // the slice v now refers to a new array of 100 ints - -// Unnecessarily complex: -var p *[]int = new([]int) -*p = make([]int, 100, 100) - -// Idiomatic: -v := make([]int, 100) -- -
-Remember that make
applies only to maps, slices and channels
-and does not return a pointer.
-To obtain an explicit pointer allocate with new
or take the address
-of a variable explicitly.
-
-Arrays are useful when planning the detailed layout of memory and sometimes -can help avoid allocation, but primarily -they are a building block for slices, the subject of the next section. -To lay the foundation for that topic, here are a few words about arrays. -
- --There are major differences between the ways arrays work in Go and C. -In Go, -
-[10]int
-and [20]int
are distinct.
--The value property can be useful but also expensive; if you want C-like behavior and efficiency, -you can pass a pointer to the array. -
- --func Sum(a *[3]float64) (sum float64) { - for _, v := range *a { - sum += v - } - return -} - -array := [...]float64{7.0, 8.5, 9.1} -x := Sum(&array) // Note the explicit address-of operator -- -
-But even this style isn't idiomatic Go. -Use slices instead. -
- --Slices wrap arrays to give a more general, powerful, and convenient -interface to sequences of data. Except for items with explicit -dimension such as transformation matrices, most array programming in -Go is done with slices rather than simple arrays. -
-
-Slices hold references to an underlying array, and if you assign one
-slice to another, both refer to the same array.
-If a function takes a slice argument, changes it makes to
-the elements of the slice will be visible to the caller, analogous to
-passing a pointer to the underlying array. A Read
-function can therefore accept a slice argument rather than a pointer
-and a count; the length within the slice sets an upper
-limit of how much data to read. Here is the signature of the
-Read
method of the File
type in package
-os
:
-
-func (f *File) Read(buf []byte) (n int, err error) --
-The method returns the number of bytes read and an error value, if
-any.
-To read into the first 32 bytes of a larger buffer
-buf
, slice (here used as a verb) the buffer.
-
- n, err := f.Read(buf[0:32]) --
-Such slicing is common and efficient. In fact, leaving efficiency aside for -the moment, the following snippet would also read the first 32 bytes of the buffer. -
-- var n int - var err error - for i := 0; i < 32; i++ { - nbytes, e := f.Read(buf[i:i+1]) // Read one byte. - n += nbytes - if nbytes == 0 || e != nil { - err = e - break - } - } --
-The length of a slice may be changed as long as it still fits within
-the limits of the underlying array; just assign it to a slice of
-itself. The capacity of a slice, accessible by the built-in
-function cap
, reports the maximum length the slice may
-assume. Here is a function to append data to a slice. If the data
-exceeds the capacity, the slice is reallocated. The
-resulting slice is returned. The function uses the fact that
-len
and cap
are legal when applied to the
-nil
slice, and return 0.
-
-func Append(slice, data []byte) []byte { - l := len(slice) - if l + len(data) > cap(slice) { // reallocate - // Allocate double what's needed, for future growth. - newSlice := make([]byte, (l+len(data))*2) - // The copy function is predeclared and works for any slice type. - copy(newSlice, slice) - slice = newSlice - } - slice = slice[0:l+len(data)] - copy(slice[l:], data) - return slice -} --
-We must return the slice afterwards because, although Append
-can modify the elements of slice
, the slice itself (the run-time data
-structure holding the pointer, length, and capacity) is passed by value.
-
-The idea of appending to a slice is so useful it's captured by the
-append
built-in function. To understand that function's
-design, though, we need a little more information, so we'll return
-to it later.
-
-Go's arrays and slices are one-dimensional. -To create the equivalent of a 2D array or slice, it is necessary to define an array-of-arrays -or slice-of-slices, like this: -
- --type Transform [3][3]float64 // A 3x3 array, really an array of arrays. -type LinesOfText [][]byte // A slice of byte slices. -- -
-Because slices are variable-length, it is possible to have each inner
-slice be a different length.
-That can be a common situation, as in our LinesOfText
-example: each line has an independent length.
-
-text := LinesOfText{ - []byte("Now is the time"), - []byte("for all good gophers"), - []byte("to bring some fun to the party."), -} -- -
-Sometimes it's necessary to allocate a 2D slice, a situation that can arise when -processing scan lines of pixels, for instance. -There are two ways to achieve this. -One is to allocate each slice independently; the other -is to allocate a single array and point the individual slices into it. -Which to use depends on your application. -If the slices might grow or shrink, they should be allocated independently -to avoid overwriting the next line; if not, it can be more efficient to construct -the object with a single allocation. -For reference, here are sketches of the two methods. -First, a line at a time: -
- --// Allocate the top-level slice. -picture := make([][]uint8, YSize) // One row per unit of y. -// Loop over the rows, allocating the slice for each row. -for i := range picture { - picture[i] = make([]uint8, XSize) -} -- -
-And now as one allocation, sliced into lines: -
- --// Allocate the top-level slice, the same as before. -picture := make([][]uint8, YSize) // One row per unit of y. -// Allocate one large slice to hold all the pixels. -pixels := make([]uint8, XSize*YSize) // Has type []uint8 even though picture is [][]uint8. -// Loop over the rows, slicing each row from the front of the remaining pixels slice. -for i := range picture { - picture[i], pixels = pixels[:XSize], pixels[XSize:] -} -- -
-Maps are a convenient and powerful built-in data structure that associate -values of one type (the key) with values of another type -(the element or value). -The key can be of any type for which the equality operator is defined, -such as integers, -floating point and complex numbers, -strings, pointers, interfaces (as long as the dynamic type -supports equality), structs and arrays. -Slices cannot be used as map keys, -because equality is not defined on them. -Like slices, maps hold references to an underlying data structure. -If you pass a map to a function -that changes the contents of the map, the changes will be visible -in the caller. -
--Maps can be constructed using the usual composite literal syntax -with colon-separated key-value pairs, -so it's easy to build them during initialization. -
--var timeZone = map[string]int{ - "UTC": 0*60*60, - "EST": -5*60*60, - "CST": -6*60*60, - "MST": -7*60*60, - "PST": -8*60*60, -} --
-Assigning and fetching map values looks syntactically just like -doing the same for arrays and slices except that the index doesn't -need to be an integer. -
--offset := timeZone["EST"] --
-An attempt to fetch a map value with a key that
-is not present in the map will return the zero value for the type
-of the entries
-in the map. For instance, if the map contains integers, looking
-up a non-existent key will return 0
.
-A set can be implemented as a map with value type bool
.
-Set the map entry to true
to put the value in the set, and then
-test it by simple indexing.
-
-attended := map[string]bool{ - "Ann": true, - "Joe": true, - ... -} - -if attended[person] { // will be false if person is not in the map - fmt.Println(person, "was at the meeting") -} --
-Sometimes you need to distinguish a missing entry from
-a zero value. Is there an entry for "UTC"
-or is that 0 because it's not in the map at all?
-You can discriminate with a form of multiple assignment.
-
-var seconds int -var ok bool -seconds, ok = timeZone[tz] --
-For obvious reasons this is called the “comma ok” idiom.
-In this example, if tz
is present, seconds
-will be set appropriately and ok
will be true; if not,
-seconds
will be set to zero and ok
will
-be false.
-Here's a function that puts it together with a nice error report:
-
-func offset(tz string) int { - if seconds, ok := timeZone[tz]; ok { - return seconds - } - log.Println("unknown time zone:", tz) - return 0 -} --
-To test for presence in the map without worrying about the actual value,
-you can use the blank identifier (_
)
-in place of the usual variable for the value.
-
-_, present := timeZone[tz] --
-To delete a map entry, use the delete
-built-in function, whose arguments are the map and the key to be deleted.
-It's safe to do this even if the key is already absent
-from the map.
-
-delete(timeZone, "PDT") // Now on Standard Time -- -
-Formatted printing in Go uses a style similar to C's printf
-family but is richer and more general. The functions live in the fmt
-package and have capitalized names: fmt.Printf
, fmt.Fprintf
,
-fmt.Sprintf
and so on. The string functions (Sprintf
etc.)
-return a string rather than filling in a provided buffer.
-
-You don't need to provide a format string. For each of Printf
,
-Fprintf
and Sprintf
there is another pair
-of functions, for instance Print
and Println
.
-These functions do not take a format string but instead generate a default
-format for each argument. The Println
versions also insert a blank
-between arguments and append a newline to the output while
-the Print
versions add blanks only if the operand on neither side is a string.
-In this example each line produces the same output.
-
-fmt.Printf("Hello %d\n", 23) -fmt.Fprint(os.Stdout, "Hello ", 23, "\n") -fmt.Println("Hello", 23) -fmt.Println(fmt.Sprint("Hello ", 23)) --
-The formatted print functions fmt.Fprint
-and friends take as a first argument any object
-that implements the io.Writer
interface; the variables os.Stdout
-and os.Stderr
are familiar instances.
-
-Here things start to diverge from C. First, the numeric formats such as %d
-do not take flags for signedness or size; instead, the printing routines use the
-type of the argument to decide these properties.
-
-var x uint64 = 1<<64 - 1 -fmt.Printf("%d %x; %d %x\n", x, x, int64(x), int64(x)) --
-prints -
--18446744073709551615 ffffffffffffffff; -1 -1 --
-If you just want the default conversion, such as decimal for integers, you can use
-the catchall format %v
(for “value”); the result is exactly
-what Print
and Println
would produce.
-Moreover, that format can print any value, even arrays, slices, structs, and
-maps. Here is a print statement for the time zone map defined in the previous section.
-
-fmt.Printf("%v\n", timeZone) // or just fmt.Println(timeZone) --
-which gives output -
--map[CST:-21600 PST:-28800 EST:-18000 UTC:0 MST:-25200] --
-For maps the keys may be output in any order, of course.
-When printing a struct, the modified format %+v
annotates the
-fields of the structure with their names, and for any value the alternate
-format %#v
prints the value in full Go syntax.
-
-type T struct { - a int - b float64 - c string -} -t := &T{ 7, -2.35, "abc\tdef" } -fmt.Printf("%v\n", t) -fmt.Printf("%+v\n", t) -fmt.Printf("%#v\n", t) -fmt.Printf("%#v\n", timeZone) --
-prints -
--&{7 -2.35 abc def} -&{a:7 b:-2.35 c:abc def} -&main.T{a:7, b:-2.35, c:"abc\tdef"} -map[string] int{"CST":-21600, "PST":-28800, "EST":-18000, "UTC":0, "MST":-25200} --
-(Note the ampersands.)
-That quoted string format is also available through %q
when
-applied to a value of type string
or []byte
.
-The alternate format %#q
will use backquotes instead if possible.
-(The %q
format also applies to integers and runes, producing a
-single-quoted rune constant.)
-Also, %x
works on strings, byte arrays and byte slices as well as
-on integers, generating a long hexadecimal string, and with
-a space in the format (% x
) it puts spaces between the bytes.
-
-Another handy format is %T
, which prints the type of a value.
-
-fmt.Printf("%T\n", timeZone) --
-prints -
--map[string] int --
-If you want to control the default format for a custom type, all that's required is to define
-a method with the signature String() string
on the type.
-For our simple type T
, that might look like this.
-
-func (t *T) String() string { - return fmt.Sprintf("%d/%g/%q", t.a, t.b, t.c) -} -fmt.Printf("%v\n", t) --
-to print in the format -
--7/-2.35/"abc\tdef" --
-(If you need to print values of type T
as well as pointers to T
,
-the receiver for String
must be of value type; this example used a pointer because
-that's more efficient and idiomatic for struct types.
-See the section below on pointers vs. value receivers for more information.)
-
-Our String
method is able to call Sprintf
because the
-print routines are fully reentrant and can be wrapped this way.
-There is one important detail to understand about this approach,
-however: don't construct a String
method by calling
-Sprintf
in a way that will recur into your String
-method indefinitely. This can happen if the Sprintf
-call attempts to print the receiver directly as a string, which in
-turn will invoke the method again. It's a common and easy mistake
-to make, as this example shows.
-
-type MyString string - -func (m MyString) String() string { - return fmt.Sprintf("MyString=%s", m) // Error: will recur forever. -} -- -
-It's also easy to fix: convert the argument to the basic string type, which does not have the -method. -
- --type MyString string -func (m MyString) String() string { - return fmt.Sprintf("MyString=%s", string(m)) // OK: note conversion. -} -- -
-In the initialization section we'll see another technique that avoids this recursion. -
- -
-Another printing technique is to pass a print routine's arguments directly to another such routine.
-The signature of Printf
uses the type ...interface{}
-for its final argument to specify that an arbitrary number of parameters (of arbitrary type)
-can appear after the format.
-
-func Printf(format string, v ...interface{}) (n int, err error) { --
-Within the function Printf
, v
acts like a variable of type
-[]interface{}
but if it is passed to another variadic function, it acts like
-a regular list of arguments.
-Here is the implementation of the
-function log.Println
we used above. It passes its arguments directly to
-fmt.Sprintln
for the actual formatting.
-
-// Println prints to the standard logger in the manner of fmt.Println. -func Println(v ...interface{}) { - std.Output(2, fmt.Sprintln(v...)) // Output takes parameters (int, string) -} --
-We write ...
after v
in the nested call to Sprintln
to tell the
-compiler to treat v
as a list of arguments; otherwise it would just pass
-v
as a single slice argument.
-
-There's even more to printing than we've covered here. See the godoc
documentation
-for package fmt
for the details.
-
-By the way, a ...
parameter can be of a specific type, for instance ...int
-for a min function that chooses the least of a list of integers:
-
-func Min(a ...int) int { - min := int(^uint(0) >> 1) // largest int - for _, i := range a { - if i < min { - min = i - } - } - return min -} -- -
-Now we have the missing piece we needed to explain the design of
-the append
built-in function. The signature of append
-is different from our custom Append
function above.
-Schematically, it's like this:
-
-func append(slice []T, elements ...T) []T --
-where T is a placeholder for any given type. You can't
-actually write a function in Go where the type T
-is determined by the caller.
-That's why append
is built in: it needs support from the
-compiler.
-
-What append
does is append the elements to the end of
-the slice and return the result. The result needs to be returned
-because, as with our hand-written Append
, the underlying
-array may change. This simple example
-
-x := []int{1,2,3} -x = append(x, 4, 5, 6) -fmt.Println(x) --
-prints [1 2 3 4 5 6]
. So append
works a
-little like Printf
, collecting an arbitrary number of
-arguments.
-
-But what if we wanted to do what our Append
does and
-append a slice to a slice? Easy: use ...
at the call
-site, just as we did in the call to Output
above. This
-snippet produces identical output to the one above.
-
-x := []int{1,2,3} -y := []int{4,5,6} -x = append(x, y...) -fmt.Println(x) --
-Without that ...
, it wouldn't compile because the types
-would be wrong; y
is not of type int
.
-
-Although it doesn't look superficially very different from -initialization in C or C++, initialization in Go is more powerful. -Complex structures can be built during initialization and the ordering -issues among initialized objects, even among different packages, are handled -correctly. -
- -
-Constants in Go are just that—constant.
-They are created at compile time, even when defined as
-locals in functions,
-and can only be numbers, characters (runes), strings or booleans.
-Because of the compile-time restriction, the expressions
-that define them must be constant expressions,
-evaluatable by the compiler. For instance,
-1<<3
is a constant expression, while
-math.Sin(math.Pi/4)
is not because
-the function call to math.Sin
needs
-to happen at run time.
-
-In Go, enumerated constants are created using the iota
-enumerator. Since iota
can be part of an expression and
-expressions can be implicitly repeated, it is easy to build intricate
-sets of values.
-
-The ability to attach a method such as String
to any
-user-defined type makes it possible for arbitrary values to format themselves
-automatically for printing.
-Although you'll see it most often applied to structs, this technique is also useful for
-scalar types such as floating-point types like ByteSize
.
-
-The expression YB
prints as 1.00YB
,
-while ByteSize(1e13)
prints as 9.09TB
.
-
-The use here of Sprintf
-to implement ByteSize
's String
method is safe
-(avoids recurring indefinitely) not because of a conversion but
-because it calls Sprintf
with %f
,
-which is not a string format: Sprintf
will only call
-the String
method when it wants a string, and %f
-wants a floating-point value.
-
-Variables can be initialized just like constants but the -initializer can be a general expression computed at run time. -
--var ( - home = os.Getenv("HOME") - user = os.Getenv("USER") - gopath = os.Getenv("GOPATH") -) -- -
-Finally, each source file can define its own niladic init
function to
-set up whatever state is required. (Actually each file can have multiple
-init
functions.)
-And finally means finally: init
is called after all the
-variable declarations in the package have evaluated their initializers,
-and those are evaluated only after all the imported packages have been
-initialized.
-
-Besides initializations that cannot be expressed as declarations,
-a common use of init
functions is to verify or repair
-correctness of the program state before real execution begins.
-
-func init() { - if user == "" { - log.Fatal("$USER not set") - } - if home == "" { - home = "/home/" + user - } - if gopath == "" { - gopath = home + "/go" - } - // gopath may be overridden by --gopath flag on command line. - flag.StringVar(&gopath, "gopath", gopath, "override default GOPATH") -} -- -
-As we saw with ByteSize
,
-methods can be defined for any named type (except a pointer or an interface);
-the receiver does not have to be a struct.
-
-In the discussion of slices above, we wrote an Append
-function. We can define it as a method on slices instead. To do
-this, we first declare a named type to which we can bind the method, and
-then make the receiver for the method a value of that type.
-
-type ByteSlice []byte - -func (slice ByteSlice) Append(data []byte) []byte { - // Body exactly the same as the Append function defined above. -} --
-This still requires the method to return the updated slice. We can
-eliminate that clumsiness by redefining the method to take a
-pointer to a ByteSlice
as its receiver, so the
-method can overwrite the caller's slice.
-
-func (p *ByteSlice) Append(data []byte) { - slice := *p - // Body as above, without the return. - *p = slice -} --
-In fact, we can do even better. If we modify our function so it looks
-like a standard Write
method, like this,
-
-func (p *ByteSlice) Write(data []byte) (n int, err error) { - slice := *p - // Again as above. - *p = slice - return len(data), nil -} --
-then the type *ByteSlice
satisfies the standard interface
-io.Writer
, which is handy. For instance, we can
-print into one.
-
- var b ByteSlice - fmt.Fprintf(&b, "This hour has %d days\n", 7) --
-We pass the address of a ByteSlice
-because only *ByteSlice
satisfies io.Writer
.
-The rule about pointers vs. values for receivers is that value methods
-can be invoked on pointers and values, but pointer methods can only be
-invoked on pointers.
-
-This rule arises because pointer methods can modify the receiver; invoking
-them on a value would cause the method to receive a copy of the value, so
-any modifications would be discarded.
-The language therefore disallows this mistake.
-There is a handy exception, though. When the value is addressable, the
-language takes care of the common case of invoking a pointer method on a
-value by inserting the address operator automatically.
-In our example, the variable b
is addressable, so we can call
-its Write
method with just b.Write
. The compiler
-will rewrite that to (&b).Write
for us.
-
-By the way, the idea of using Write
on a slice of bytes
-is central to the implementation of bytes.Buffer
.
-
-Interfaces in Go provide a way to specify the behavior of an
-object: if something can do this, then it can be used
-here. We've seen a couple of simple examples already;
-custom printers can be implemented by a String
method
-while Fprintf
can generate output to anything
-with a Write
method.
-Interfaces with only one or two methods are common in Go code, and are
-usually given a name derived from the method, such as io.Writer
-for something that implements Write
.
-
-A type can implement multiple interfaces.
-For instance, a collection can be sorted
-by the routines in package sort
if it implements
-sort.Interface
, which contains Len()
,
-Less(i, j int) bool
, and Swap(i, j int)
,
-and it could also have a custom formatter.
-In this contrived example Sequence
satisfies both.
-
-The String
method of Sequence
is recreating the
-work that Sprint
already does for slices.
-(It also has complexity O(N²), which is poor.) We can share the
-effort (and also speed it up) if we convert the Sequence
to a plain
-[]int
before calling Sprint
.
-
-func (s Sequence) String() string { - s = s.Copy() - sort.Sort(s) - return fmt.Sprint([]int(s)) -} --
-This method is another example of the conversion technique for calling
-Sprintf
safely from a String
method.
-Because the two types (Sequence
and []int
)
-are the same if we ignore the type name, it's legal to convert between them.
-The conversion doesn't create a new value, it just temporarily acts
-as though the existing value has a new type.
-(There are other legal conversions, such as from integer to floating point, that
-do create a new value.)
-
-It's an idiom in Go programs to convert the
-type of an expression to access a different
-set of methods. As an example, we could use the existing
-type sort.IntSlice
to reduce the entire example
-to this:
-
-type Sequence []int - -// Method for printing - sorts the elements before printing -func (s Sequence) String() string { - s = s.Copy() - sort.IntSlice(s).Sort() - return fmt.Sprint([]int(s)) -} --
-Now, instead of having Sequence
implement multiple
-interfaces (sorting and printing), we're using the ability of a data item to be
-converted to multiple types (Sequence
, sort.IntSlice
-and []int
), each of which does some part of the job.
-That's more unusual in practice but can be effective.
-
-Type switches are a form of conversion: they take an interface and, for
-each case in the switch, in a sense convert it to the type of that case.
-Here's a simplified version of how the code under fmt.Printf
turns a value into
-a string using a type switch.
-If it's already a string, we want the actual string value held by the interface, while if it has a
-String
method we want the result of calling the method.
-
-type Stringer interface { - String() string -} - -var value interface{} // Value provided by caller. -switch str := value.(type) { -case string: - return str -case Stringer: - return str.String() -} -- -
-The first case finds a concrete value; the second converts the interface into another interface. -It's perfectly fine to mix types this way. -
- -
-What if there's only one type we care about? If we know the value holds a string
-and we just want to extract it?
-A one-case type switch would do, but so would a type assertion.
-A type assertion takes an interface value and extracts from it a value of the specified explicit type.
-The syntax borrows from the clause opening a type switch, but with an explicit
-type rather than the type
keyword:
-
-value.(typeName) -- -
-and the result is a new value with the static type typeName
.
-That type must either be the concrete type held by the interface, or a second interface
-type that the value can be converted to.
-To extract the string we know is in the value, we could write:
-
-str := value.(string) -- -
-But if it turns out that the value does not contain a string, the program will crash with a run-time error. -To guard against that, use the "comma, ok" idiom to test, safely, whether the value is a string: -
- --str, ok := value.(string) -if ok { - fmt.Printf("string value is: %q\n", str) -} else { - fmt.Printf("value is not a string\n") -} -- -
-If the type assertion fails, str
will still exist and be of type string, but it will have
-the zero value, an empty string.
-
-As an illustration of the capability, here's an if
-else
-statement that's equivalent to the type switch that opened this section.
-
-if str, ok := value.(string); ok { - return str -} else if str, ok := value.(Stringer); ok { - return str.String() -} -- -
-If a type exists only to implement an interface and will -never have exported methods beyond that interface, there is -no need to export the type itself. -Exporting just the interface makes it clear the value has no -interesting behavior beyond what is described in the -interface. -It also avoids the need to repeat the documentation -on every instance of a common method. -
-
-In such cases, the constructor should return an interface value
-rather than the implementing type.
-As an example, in the hash libraries
-both crc32.NewIEEE
and adler32.New
-return the interface type hash.Hash32
.
-Substituting the CRC-32 algorithm for Adler-32 in a Go program
-requires only changing the constructor call;
-the rest of the code is unaffected by the change of algorithm.
-
-A similar approach allows the streaming cipher algorithms
-in the various crypto
packages to be
-separated from the block ciphers they chain together.
-The Block
interface
-in the crypto/cipher
package specifies the
-behavior of a block cipher, which provides encryption
-of a single block of data.
-Then, by analogy with the bufio
package,
-cipher packages that implement this interface
-can be used to construct streaming ciphers, represented
-by the Stream
interface, without
-knowing the details of the block encryption.
-
-The crypto/cipher
interfaces look like this:
-
-type Block interface { - BlockSize() int - Encrypt(src, dst []byte) - Decrypt(src, dst []byte) -} - -type Stream interface { - XORKeyStream(dst, src []byte) -} -- -
-Here's the definition of the counter mode (CTR) stream, -which turns a block cipher into a streaming cipher; notice -that the block cipher's details are abstracted away: -
- --// NewCTR returns a Stream that encrypts/decrypts using the given Block in -// counter mode. The length of iv must be the same as the Block's block size. -func NewCTR(block Block, iv []byte) Stream --
-NewCTR
applies not
-just to one specific encryption algorithm and data source but to any
-implementation of the Block
interface and any
-Stream
. Because they return
-interface values, replacing CTR
-encryption with other encryption modes is a localized change. The constructor
-calls must be edited, but because the surrounding code must treat the result only
-as a Stream
, it won't notice the difference.
-
-Since almost anything can have methods attached, almost anything can
-satisfy an interface. One illustrative example is in the http
-package, which defines the Handler
interface. Any object
-that implements Handler
can serve HTTP requests.
-
-type Handler interface { - ServeHTTP(ResponseWriter, *Request) -} --
-ResponseWriter
is itself an interface that provides access
-to the methods needed to return the response to the client.
-Those methods include the standard Write
method, so an
-http.ResponseWriter
can be used wherever an io.Writer
-can be used.
-Request
is a struct containing a parsed representation
-of the request from the client.
-
-For brevity, let's ignore POSTs and assume HTTP requests are always -GETs; that simplification does not affect the way the handlers are -set up. Here's a trivial but complete implementation of a handler to -count the number of times the -page is visited. -
--// Simple counter server. -type Counter struct { - n int -} - -func (ctr *Counter) ServeHTTP(w http.ResponseWriter, req *http.Request) { - ctr.n++ - fmt.Fprintf(w, "counter = %d\n", ctr.n) -} --
-(Keeping with our theme, note how Fprintf
can print to an
-http.ResponseWriter
.)
-For reference, here's how to attach such a server to a node on the URL tree.
-
-import "net/http" -... -ctr := new(Counter) -http.Handle("/counter", ctr) --
-But why make Counter
a struct? An integer is all that's needed.
-(The receiver needs to be a pointer so the increment is visible to the caller.)
-
-// Simpler counter server. -type Counter int - -func (ctr *Counter) ServeHTTP(w http.ResponseWriter, req *http.Request) { - *ctr++ - fmt.Fprintf(w, "counter = %d\n", *ctr) -} --
-What if your program has some internal state that needs to be notified that a page -has been visited? Tie a channel to the web page. -
--// A channel that sends a notification on each visit. -// (Probably want the channel to be buffered.) -type Chan chan *http.Request - -func (ch Chan) ServeHTTP(w http.ResponseWriter, req *http.Request) { - ch <- req - fmt.Fprint(w, "notification sent") -} --
-Finally, let's say we wanted to present on /args
the arguments
-used when invoking the server binary.
-It's easy to write a function to print the arguments.
-
-func ArgServer() { - fmt.Println(os.Args) -} --
-How do we turn that into an HTTP server? We could make ArgServer
-a method of some type whose value we ignore, but there's a cleaner way.
-Since we can define a method for any type except pointers and interfaces,
-we can write a method for a function.
-The http
package contains this code:
-
-// The HandlerFunc type is an adapter to allow the use of -// ordinary functions as HTTP handlers. If f is a function -// with the appropriate signature, HandlerFunc(f) is a -// Handler object that calls f. -type HandlerFunc func(ResponseWriter, *Request) - -// ServeHTTP calls f(w, req). -func (f HandlerFunc) ServeHTTP(w ResponseWriter, req *Request) { - f(w, req) -} --
-HandlerFunc
is a type with a method, ServeHTTP
,
-so values of that type can serve HTTP requests. Look at the implementation
-of the method: the receiver is a function, f
, and the method
-calls f
. That may seem odd but it's not that different from, say,
-the receiver being a channel and the method sending on the channel.
-
-To make ArgServer
into an HTTP server, we first modify it
-to have the right signature.
-
-// Argument server. -func ArgServer(w http.ResponseWriter, req *http.Request) { - fmt.Fprintln(w, os.Args) -} --
-ArgServer
now has same signature as HandlerFunc
,
-so it can be converted to that type to access its methods,
-just as we converted Sequence
to IntSlice
-to access IntSlice.Sort
.
-The code to set it up is concise:
-
-http.Handle("/args", http.HandlerFunc(ArgServer)) --
-When someone visits the page /args
,
-the handler installed at that page has value ArgServer
-and type HandlerFunc
.
-The HTTP server will invoke the method ServeHTTP
-of that type, with ArgServer
as the receiver, which will in turn call
-ArgServer
(via the invocation f(w, req)
-inside HandlerFunc.ServeHTTP
).
-The arguments will then be displayed.
-
-In this section we have made an HTTP server from a struct, an integer, -a channel, and a function, all because interfaces are just sets of -methods, which can be defined for (almost) any type. -
- -
-We've mentioned the blank identifier a couple of times now, in the context of
-for
range
loops
-and maps.
-The blank identifier can be assigned or declared with any value of any type, with the
-value discarded harmlessly.
-It's a bit like writing to the Unix /dev/null
file:
-it represents a write-only value
-to be used as a place-holder
-where a variable is needed but the actual value is irrelevant.
-It has uses beyond those we've seen already.
-
-The use of a blank identifier in a for
range
loop is a
-special case of a general situation: multiple assignment.
-
-If an assignment requires multiple values on the left side, -but one of the values will not be used by the program, -a blank identifier on the left-hand-side of -the assignment avoids the need -to create a dummy variable and makes it clear that the -value is to be discarded. -For instance, when calling a function that returns -a value and an error, but only the error is important, -use the blank identifier to discard the irrelevant value. -
- --if _, err := os.Stat(path); os.IsNotExist(err) { - fmt.Printf("%s does not exist\n", path) -} -- -
-Occasionally you'll see code that discards the error value in order -to ignore the error; this is terrible practice. Always check error returns; -they're provided for a reason. -
- --// Bad! This code will crash if path does not exist. -fi, _ := os.Stat(path) -if fi.IsDir() { - fmt.Printf("%s is a directory\n", path) -} -- -
-It is an error to import a package or to declare a variable without using it. -Unused imports bloat the program and slow compilation, -while a variable that is initialized but not used is at least -a wasted computation and perhaps indicative of a -larger bug. -When a program is under active development, however, -unused imports and variables often arise and it can -be annoying to delete them just to have the compilation proceed, -only to have them be needed again later. -The blank identifier provides a workaround. -
-
-This half-written program has two unused imports
-(fmt
and io
)
-and an unused variable (fd
),
-so it will not compile, but it would be nice to see if the
-code so far is correct.
-
-To silence complaints about the unused imports, use a
-blank identifier to refer to a symbol from the imported package.
-Similarly, assigning the unused variable fd
-to the blank identifier will silence the unused variable error.
-This version of the program does compile.
-
-By convention, the global declarations to silence import errors -should come right after the imports and be commented, -both to make them easy to find and as a reminder to clean things up later. -
- -
-An unused import like fmt
or io
in the
-previous example should eventually be used or removed:
-blank assignments identify code as a work in progress.
-But sometimes it is useful to import a package only for its
-side effects, without any explicit use.
-For example, during its init
function,
-the net/http/pprof
-package registers HTTP handlers that provide
-debugging information. It has an exported API, but
-most clients need only the handler registration and
-access the data through a web page.
-To import the package only for its side effects, rename the package
-to the blank identifier:
-
-import _ "net/http/pprof" --
-This form of import makes clear that the package is being -imported for its side effects, because there is no other possible -use of the package: in this file, it doesn't have a name. -(If it did, and we didn't use that name, the compiler would reject the program.) -
- -
-As we saw in the discussion of interfaces above,
-a type need not declare explicitly that it implements an interface.
-Instead, a type implements the interface just by implementing the interface's methods.
-In practice, most interface conversions are static and therefore checked at compile time.
-For example, passing an *os.File
to a function
-expecting an io.Reader
will not compile unless
-*os.File
implements the io.Reader
interface.
-
-Some interface checks do happen at run-time, though.
-One instance is in the encoding/json
-package, which defines a Marshaler
-interface. When the JSON encoder receives a value that implements that interface,
-the encoder invokes the value's marshaling method to convert it to JSON
-instead of doing the standard conversion.
-The encoder checks this property at run time with a type assertion like:
-
-m, ok := val.(json.Marshaler) -- -
-If it's necessary only to ask whether a type implements an interface, without -actually using the interface itself, perhaps as part of an error check, use the blank -identifier to ignore the type-asserted value: -
- --if _, ok := val.(json.Marshaler); ok { - fmt.Printf("value %v of type %T implements json.Marshaler\n", val, val) -} -- -
-One place this situation arises is when it is necessary to guarantee within the package implementing the type that
-it actually satisfies the interface.
-If a type—for example,
-json.RawMessage
—needs
-a custom JSON representation, it should implement
-json.Marshaler
, but there are no static conversions that would
-cause the compiler to verify this automatically.
-If the type inadvertently fails to satisfy the interface, the JSON encoder will still work,
-but will not use the custom implementation.
-To guarantee that the implementation is correct,
-a global declaration using the blank identifier can be used in the package:
-
-var _ json.Marshaler = (*RawMessage)(nil) --
-In this declaration, the assignment involving a conversion of a
-*RawMessage
to a Marshaler
-requires that *RawMessage
implements Marshaler
,
-and that property will be checked at compile time.
-Should the json.Marshaler
interface change, this package
-will no longer compile and we will be on notice that it needs to be updated.
-
-The appearance of the blank identifier in this construct indicates that -the declaration exists only for the type checking, -not to create a variable. -Don't do this for every type that satisfies an interface, though. -By convention, such declarations are only used -when there are no static conversions already present in the code, -which is a rare event. -
- - --Go does not provide the typical, type-driven notion of subclassing, -but it does have the ability to “borrow” pieces of an -implementation by embedding types within a struct or -interface. -
-
-Interface embedding is very simple.
-We've mentioned the io.Reader
and io.Writer
interfaces before;
-here are their definitions.
-
-type Reader interface { - Read(p []byte) (n int, err error) -} - -type Writer interface { - Write(p []byte) (n int, err error) -} --
-The io
package also exports several other interfaces
-that specify objects that can implement several such methods.
-For instance, there is io.ReadWriter
, an interface
-containing both Read
and Write
.
-We could specify io.ReadWriter
by listing the
-two methods explicitly, but it's easier and more evocative
-to embed the two interfaces to form the new one, like this:
-
-// ReadWriter is the interface that combines the Reader and Writer interfaces. -type ReadWriter interface { - Reader - Writer -} --
-This says just what it looks like: A ReadWriter
can do
-what a Reader
does and what a Writer
-does; it is a union of the embedded interfaces (which must be disjoint
-sets of methods).
-Only interfaces can be embedded within interfaces.
-
-The same basic idea applies to structs, but with more far-reaching
-implications. The bufio
package has two struct types,
-bufio.Reader
and bufio.Writer
, each of
-which of course implements the analogous interfaces from package
-io
.
-And bufio
also implements a buffered reader/writer,
-which it does by combining a reader and a writer into one struct
-using embedding: it lists the types within the struct
-but does not give them field names.
-
-// ReadWriter stores pointers to a Reader and a Writer. -// It implements io.ReadWriter. -type ReadWriter struct { - *Reader // *bufio.Reader - *Writer // *bufio.Writer -} --
-The embedded elements are pointers to structs and of course
-must be initialized to point to valid structs before they
-can be used.
-The ReadWriter
struct could be written as
-
-type ReadWriter struct { - reader *Reader - writer *Writer -} --
-but then to promote the methods of the fields and to
-satisfy the io
interfaces, we would also need
-to provide forwarding methods, like this:
-
-func (rw *ReadWriter) Read(p []byte) (n int, err error) { - return rw.reader.Read(p) -} --
-By embedding the structs directly, we avoid this bookkeeping.
-The methods of embedded types come along for free, which means that bufio.ReadWriter
-not only has the methods of bufio.Reader
and bufio.Writer
,
-it also satisfies all three interfaces:
-io.Reader
,
-io.Writer
, and
-io.ReadWriter
.
-
-There's an important way in which embedding differs from subclassing. When we embed a type,
-the methods of that type become methods of the outer type,
-but when they are invoked the receiver of the method is the inner type, not the outer one.
-In our example, when the Read
method of a bufio.ReadWriter
is
-invoked, it has exactly the same effect as the forwarding method written out above;
-the receiver is the reader
field of the ReadWriter
, not the
-ReadWriter
itself.
-
-Embedding can also be a simple convenience. -This example shows an embedded field alongside a regular, named field. -
--type Job struct { - Command string - *log.Logger -} --
-The Job
type now has the Print
, Printf
, Println
-and other
-methods of *log.Logger
. We could have given the Logger
-a field name, of course, but it's not necessary to do so. And now, once
-initialized, we can
-log to the Job
:
-
-job.Println("starting now...") --
-The Logger
is a regular field of the Job
struct,
-so we can initialize it in the usual way inside the constructor for Job
, like this,
-
-func NewJob(command string, logger *log.Logger) *Job { - return &Job{command, logger} -} --
-or with a composite literal, -
--job := &Job{command, log.New(os.Stderr, "Job: ", log.Ldate)} --
-If we need to refer to an embedded field directly, the type name of the field,
-ignoring the package qualifier, serves as a field name, as it did
-in the Read
method of our ReadWriter
struct.
-Here, if we needed to access the
-*log.Logger
of a Job
variable job
,
-we would write job.Logger
,
-which would be useful if we wanted to refine the methods of Logger
.
-
-func (job *Job) Printf(format string, args ...interface{}) { - job.Logger.Printf("%q: %s", job.Command, fmt.Sprintf(format, args...)) -} --
-Embedding types introduces the problem of name conflicts but the rules to resolve
-them are simple.
-First, a field or method X
hides any other item X
in a more deeply
-nested part of the type.
-If log.Logger
contained a field or method called Command
, the Command
field
-of Job
would dominate it.
-
-Second, if the same name appears at the same nesting level, it is usually an error;
-it would be erroneous to embed log.Logger
if the Job
struct
-contained another field or method called Logger
.
-However, if the duplicate name is never mentioned in the program outside the type definition, it is OK.
-This qualification provides some protection against changes made to types embedded from outside; there
-is no problem if a field is added that conflicts with another field in another subtype if neither field
-is ever used.
-
-Concurrent programming is a large topic and there is space only for some -Go-specific highlights here. -
--Concurrent programming in many environments is made difficult by the -subtleties required to implement correct access to shared variables. Go encourages -a different approach in which shared values are passed around on channels -and, in fact, never actively shared by separate threads of execution. -Only one goroutine has access to the value at any given time. -Data races cannot occur, by design. -To encourage this way of thinking we have reduced it to a slogan: -
--Do not communicate by sharing memory; -instead, share memory by communicating. --
-This approach can be taken too far. Reference counts may be best done -by putting a mutex around an integer variable, for instance. But as a -high-level approach, using channels to control access makes it easier -to write clear, correct programs. -
--One way to think about this model is to consider a typical single-threaded -program running on one CPU. It has no need for synchronization primitives. -Now run another such instance; it too needs no synchronization. Now let those -two communicate; if the communication is the synchronizer, there's still no need -for other synchronization. Unix pipelines, for example, fit this model -perfectly. Although Go's approach to concurrency originates in Hoare's -Communicating Sequential Processes (CSP), -it can also be seen as a type-safe generalization of Unix pipes. -
- --They're called goroutines because the existing -terms—threads, coroutines, processes, and so on—convey -inaccurate connotations. A goroutine has a simple model: it is a -function executing concurrently with other goroutines in the same -address space. It is lightweight, costing little more than the -allocation of stack space. -And the stacks start small, so they are cheap, and grow -by allocating (and freeing) heap storage as required. -
--Goroutines are multiplexed onto multiple OS threads so if one should -block, such as while waiting for I/O, others continue to run. Their -design hides many of the complexities of thread creation and -management. -
-
-Prefix a function or method call with the go
-keyword to run the call in a new goroutine.
-When the call completes, the goroutine
-exits, silently. (The effect is similar to the Unix shell's
-&
notation for running a command in the
-background.)
-
-go list.Sort() // run list.Sort concurrently; don't wait for it. --
-A function literal can be handy in a goroutine invocation. -
--func Announce(message string, delay time.Duration) { - go func() { - time.Sleep(delay) - fmt.Println(message) - }() // Note the parentheses - must call the function. -} --
-In Go, function literals are closures: the implementation makes -sure the variables referred to by the function survive as long as they are active. -
--These examples aren't too practical because the functions have no way of signaling -completion. For that, we need channels. -
- -
-Like maps, channels are allocated with make
, and
-the resulting value acts as a reference to an underlying data structure.
-If an optional integer parameter is provided, it sets the buffer size for the channel.
-The default is zero, for an unbuffered or synchronous channel.
-
-ci := make(chan int) // unbuffered channel of integers -cj := make(chan int, 0) // unbuffered channel of integers -cs := make(chan *os.File, 100) // buffered channel of pointers to Files --
-Unbuffered channels combine communication—the exchange of a value—with -synchronization—guaranteeing that two calculations (goroutines) are in -a known state. -
--There are lots of nice idioms using channels. Here's one to get us started. -In the previous section we launched a sort in the background. A channel -can allow the launching goroutine to wait for the sort to complete. -
--c := make(chan int) // Allocate a channel. -// Start the sort in a goroutine; when it completes, signal on the channel. -go func() { - list.Sort() - c <- 1 // Send a signal; value does not matter. -}() -doSomethingForAWhile() -<-c // Wait for sort to finish; discard sent value. --
-Receivers always block until there is data to receive. -If the channel is unbuffered, the sender blocks until the receiver has -received the value. -If the channel has a buffer, the sender blocks only until the -value has been copied to the buffer; if the buffer is full, this -means waiting until some receiver has retrieved a value. -
-
-A buffered channel can be used like a semaphore, for instance to
-limit throughput. In this example, incoming requests are passed
-to handle
, which sends a value into the channel, processes
-the request, and then receives a value from the channel
-to ready the “semaphore” for the next consumer.
-The capacity of the channel buffer limits the number of
-simultaneous calls to process
.
-
-var sem = make(chan int, MaxOutstanding) - -func handle(r *Request) { - sem <- 1 // Wait for active queue to drain. - process(r) // May take a long time. - <-sem // Done; enable next request to run. -} - -func Serve(queue chan *Request) { - for { - req := <-queue - go handle(req) // Don't wait for handle to finish. - } -} -- -
-Once MaxOutstanding
handlers are executing process
,
-any more will block trying to send into the filled channel buffer,
-until one of the existing handlers finishes and receives from the buffer.
-
-This design has a problem, though: Serve
-creates a new goroutine for
-every incoming request, even though only MaxOutstanding
-of them can run at any moment.
-As a result, the program can consume unlimited resources if the requests come in too fast.
-We can address that deficiency by changing Serve
to
-gate the creation of the goroutines.
-Here's an obvious solution, but beware it has a bug we'll fix subsequently:
-
-func Serve(queue chan *Request) { - for req := range queue { - sem <- 1 - go func() { - process(req) // Buggy; see explanation below. - <-sem - }() - } -}- -
-The bug is that in a Go for
loop, the loop variable
-is reused for each iteration, so the req
-variable is shared across all goroutines.
-That's not what we want.
-We need to make sure that req
is unique for each goroutine.
-Here's one way to do that, passing the value of req
as an argument
-to the closure in the goroutine:
-
-func Serve(queue chan *Request) { - for req := range queue { - sem <- 1 - go func(req *Request) { - process(req) - <-sem - }(req) - } -}- -
-Compare this version with the previous to see the difference in how -the closure is declared and run. -Another solution is just to create a new variable with the same -name, as in this example: -
- --func Serve(queue chan *Request) { - for req := range queue { - req := req // Create new instance of req for the goroutine. - sem <- 1 - go func() { - process(req) - <-sem - }() - } -}- -
-It may seem odd to write -
- --req := req -- -
-but it's legal and idiomatic in Go to do this. -You get a fresh version of the variable with the same name, deliberately -shadowing the loop variable locally but unique to each goroutine. -
- -
-Going back to the general problem of writing the server,
-another approach that manages resources well is to start a fixed
-number of handle
goroutines all reading from the request
-channel.
-The number of goroutines limits the number of simultaneous
-calls to process
.
-This Serve
function also accepts a channel on which
-it will be told to exit; after launching the goroutines it blocks
-receiving from that channel.
-
-func handle(queue chan *Request) { - for r := range queue { - process(r) - } -} - -func Serve(clientRequests chan *Request, quit chan bool) { - // Start handlers - for i := 0; i < MaxOutstanding; i++ { - go handle(clientRequests) - } - <-quit // Wait to be told to exit. -} -- -
-One of the most important properties of Go is that -a channel is a first-class value that can be allocated and passed -around like any other. A common use of this property is -to implement safe, parallel demultiplexing. -
-
-In the example in the previous section, handle
was
-an idealized handler for a request but we didn't define the
-type it was handling. If that type includes a channel on which
-to reply, each client can provide its own path for the answer.
-Here's a schematic definition of type Request
.
-
-type Request struct { - args []int - f func([]int) int - resultChan chan int -} --
-The client provides a function and its arguments, as well as -a channel inside the request object on which to receive the answer. -
--func sum(a []int) (s int) { - for _, v := range a { - s += v - } - return -} - -request := &Request{[]int{3, 4, 5}, sum, make(chan int)} -// Send request -clientRequests <- request -// Wait for response. -fmt.Printf("answer: %d\n", <-request.resultChan) --
-On the server side, the handler function is the only thing that changes. -
--func handle(queue chan *Request) { - for req := range queue { - req.resultChan <- req.f(req.args) - } -} --
-There's clearly a lot more to do to make it realistic, but this -code is a framework for a rate-limited, parallel, non-blocking RPC -system, and there's not a mutex in sight. -
- --Another application of these ideas is to parallelize a calculation -across multiple CPU cores. If the calculation can be broken into -separate pieces that can execute independently, it can be parallelized, -with a channel to signal when each piece completes. -
--Let's say we have an expensive operation to perform on a vector of items, -and that the value of the operation on each item is independent, -as in this idealized example. -
--type Vector []float64 - -// Apply the operation to v[i], v[i+1] ... up to v[n-1]. -func (v Vector) DoSome(i, n int, u Vector, c chan int) { - for ; i < n; i++ { - v[i] += u.Op(v[i]) - } - c <- 1 // signal that this piece is done -} --
-We launch the pieces independently in a loop, one per CPU. -They can complete in any order but it doesn't matter; we just -count the completion signals by draining the channel after -launching all the goroutines. -
--const numCPU = 4 // number of CPU cores - -func (v Vector) DoAll(u Vector) { - c := make(chan int, numCPU) // Buffering optional but sensible. - for i := 0; i < numCPU; i++ { - go v.DoSome(i*len(v)/numCPU, (i+1)*len(v)/numCPU, u, c) - } - // Drain the channel. - for i := 0; i < numCPU; i++ { - <-c // wait for one task to complete - } - // All done. -} --
-Rather than create a constant value for numCPU, we can ask the runtime what
-value is appropriate.
-The function runtime.NumCPU
-returns the number of hardware CPU cores in the machine, so we could write
-
-var numCPU = runtime.NumCPU() --
-There is also a function
-runtime.GOMAXPROCS
,
-which reports (or sets)
-the user-specified number of cores that a Go program can have running
-simultaneously.
-It defaults to the value of runtime.NumCPU
but can be
-overridden by setting the similarly named shell environment variable
-or by calling the function with a positive number. Calling it with
-zero just queries the value.
-Therefore if we want to honor the user's resource request, we should write
-
-var numCPU = runtime.GOMAXPROCS(0) --
-Be sure not to confuse the ideas of concurrency—structuring a program -as independently executing components—and parallelism—executing -calculations in parallel for efficiency on multiple CPUs. -Although the concurrency features of Go can make some problems easy -to structure as parallel computations, Go is a concurrent language, -not a parallel one, and not all parallelization problems fit Go's model. -For a discussion of the distinction, see the talk cited in -this -blog post. - -
-The tools of concurrent programming can even make non-concurrent
-ideas easier to express. Here's an example abstracted from an RPC
-package. The client goroutine loops receiving data from some source,
-perhaps a network. To avoid allocating and freeing buffers, it keeps
-a free list, and uses a buffered channel to represent it. If the
-channel is empty, a new buffer gets allocated.
-Once the message buffer is ready, it's sent to the server on
-serverChan
.
-
-var freeList = make(chan *Buffer, 100) -var serverChan = make(chan *Buffer) - -func client() { - for { - var b *Buffer - // Grab a buffer if available; allocate if not. - select { - case b = <-freeList: - // Got one; nothing more to do. - default: - // None free, so allocate a new one. - b = new(Buffer) - } - load(b) // Read next message from the net. - serverChan <- b // Send to server. - } -} --
-The server loop receives each message from the client, processes it, -and returns the buffer to the free list. -
--func server() { - for { - b := <-serverChan // Wait for work. - process(b) - // Reuse buffer if there's room. - select { - case freeList <- b: - // Buffer on free list; nothing more to do. - default: - // Free list full, just carry on. - } - } -} --
-The client attempts to retrieve a buffer from freeList
;
-if none is available, it allocates a fresh one.
-The server's send to freeList
puts b
back
-on the free list unless the list is full, in which case the
-buffer is dropped on the floor to be reclaimed by
-the garbage collector.
-(The default
clauses in the select
-statements execute when no other case is ready,
-meaning that the selects
never block.)
-This implementation builds a leaky bucket free list
-in just a few lines, relying on the buffered channel and
-the garbage collector for bookkeeping.
-
-Library routines must often return some sort of error indication to
-the caller.
-As mentioned earlier, Go's multivalue return makes it
-easy to return a detailed error description alongside the normal
-return value.
-It is good style to use this feature to provide detailed error information.
-For example, as we'll see, os.Open
doesn't
-just return a nil
pointer on failure, it also returns an
-error value that describes what went wrong.
-
-By convention, errors have type error
,
-a simple built-in interface.
-
-type error interface { - Error() string -} --
-A library writer is free to implement this interface with a
-richer model under the covers, making it possible not only
-to see the error but also to provide some context.
-As mentioned, alongside the usual *os.File
-return value, os.Open
also returns an
-error value.
-If the file is opened successfully, the error will be nil
,
-but when there is a problem, it will hold an
-os.PathError
:
-
-// PathError records an error and the operation and -// file path that caused it. -type PathError struct { - Op string // "open", "unlink", etc. - Path string // The associated file. - Err error // Returned by the system call. -} - -func (e *PathError) Error() string { - return e.Op + " " + e.Path + ": " + e.Err.Error() -} --
-PathError
's Error
generates
-a string like this:
-
-open /etc/passwx: no such file or directory --
-Such an error, which includes the problematic file name, the -operation, and the operating system error it triggered, is useful even -if printed far from the call that caused it; -it is much more informative than the plain -"no such file or directory". -
- -
-When feasible, error strings should identify their origin, such as by having
-a prefix naming the operation or package that generated the error. For example, in package
-image
, the string representation for a decoding error due to an
-unknown format is "image: unknown format".
-
-Callers that care about the precise error details can
-use a type switch or a type assertion to look for specific
-errors and extract details. For PathErrors
-this might include examining the internal Err
-field for recoverable failures.
-
-for try := 0; try < 2; try++ { - file, err = os.Create(filename) - if err == nil { - return - } - if e, ok := err.(*os.PathError); ok && e.Err == syscall.ENOSPC { - deleteTempFiles() // Recover some space. - continue - } - return -} -- -
-The second if
statement here is another type assertion.
-If it fails, ok
will be false, and e
-will be nil
.
-If it succeeds, ok
will be true, which means the
-error was of type *os.PathError
, and then so is e
,
-which we can examine for more information about the error.
-
-The usual way to report an error to a caller is to return an
-error
as an extra return value. The canonical
-Read
method is a well-known instance; it returns a byte
-count and an error
. But what if the error is
-unrecoverable? Sometimes the program simply cannot continue.
-
-For this purpose, there is a built-in function panic
-that in effect creates a run-time error that will stop the program
-(but see the next section). The function takes a single argument
-of arbitrary type—often a string—to be printed as the
-program dies. It's also a way to indicate that something impossible has
-happened, such as exiting an infinite loop.
-
-// A toy implementation of cube root using Newton's method. -func CubeRoot(x float64) float64 { - z := x/3 // Arbitrary initial value - for i := 0; i < 1e6; i++ { - prevz := z - z -= (z*z*z-x) / (3*z*z) - if veryClose(z, prevz) { - return z - } - } - // A million iterations has not converged; something is wrong. - panic(fmt.Sprintf("CubeRoot(%g) did not converge", x)) -} -- -
-This is only an example but real library functions should
-avoid panic
. If the problem can be masked or worked
-around, it's always better to let things continue to run rather
-than taking down the whole program. One possible counterexample
-is during initialization: if the library truly cannot set itself up,
-it might be reasonable to panic, so to speak.
-
-var user = os.Getenv("USER") - -func init() { - if user == "" { - panic("no value for $USER") - } -} -- -
-When panic
is called, including implicitly for run-time
-errors such as indexing a slice out of bounds or failing a type
-assertion, it immediately stops execution of the current function
-and begins unwinding the stack of the goroutine, running any deferred
-functions along the way. If that unwinding reaches the top of the
-goroutine's stack, the program dies. However, it is possible to
-use the built-in function recover
to regain control
-of the goroutine and resume normal execution.
-
-A call to recover
stops the unwinding and returns the
-argument passed to panic
. Because the only code that
-runs while unwinding is inside deferred functions, recover
-is only useful inside deferred functions.
-
-One application of recover
is to shut down a failing goroutine
-inside a server without killing the other executing goroutines.
-
-func server(workChan <-chan *Work) { - for work := range workChan { - go safelyDo(work) - } -} - -func safelyDo(work *Work) { - defer func() { - if err := recover(); err != nil { - log.Println("work failed:", err) - } - }() - do(work) -} -- -
-In this example, if do(work)
panics, the result will be
-logged and the goroutine will exit cleanly without disturbing the
-others. There's no need to do anything else in the deferred closure;
-calling recover
handles the condition completely.
-
-Because recover
always returns nil
unless called directly
-from a deferred function, deferred code can call library routines that themselves
-use panic
and recover
without failing. As an example,
-the deferred function in safelyDo
might call a logging function before
-calling recover
, and that logging code would run unaffected
-by the panicking state.
-
-With our recovery pattern in place, the do
-function (and anything it calls) can get out of any bad situation
-cleanly by calling panic
. We can use that idea to
-simplify error handling in complex software. Let's look at an
-idealized version of a regexp
package, which reports
-parsing errors by calling panic
with a local
-error type. Here's the definition of Error
,
-an error
method, and the Compile
function.
-
-// Error is the type of a parse error; it satisfies the error interface. -type Error string -func (e Error) Error() string { - return string(e) -} - -// error is a method of *Regexp that reports parsing errors by -// panicking with an Error. -func (regexp *Regexp) error(err string) { - panic(Error(err)) -} - -// Compile returns a parsed representation of the regular expression. -func Compile(str string) (regexp *Regexp, err error) { - regexp = new(Regexp) - // doParse will panic if there is a parse error. - defer func() { - if e := recover(); e != nil { - regexp = nil // Clear return value. - err = e.(Error) // Will re-panic if not a parse error. - } - }() - return regexp.doParse(str), nil -} -- -
-If doParse
panics, the recovery block will set the
-return value to nil
—deferred functions can modify
-named return values. It will then check, in the assignment
-to err
, that the problem was a parse error by asserting
-that it has the local type Error
.
-If it does not, the type assertion will fail, causing a run-time error
-that continues the stack unwinding as though nothing had interrupted
-it.
-This check means that if something unexpected happens, such
-as an index out of bounds, the code will fail even though we
-are using panic
and recover
to handle
-parse errors.
-
-With error handling in place, the error
method (because it's a
-method bound to a type, it's fine, even natural, for it to have the same name
-as the builtin error
type)
-makes it easy to report parse errors without worrying about unwinding
-the parse stack by hand:
-
-if pos == 0 { - re.error("'*' illegal at start of expression") -} -- -
-Useful though this pattern is, it should be used only within a package.
-Parse
turns its internal panic
calls into
-error
values; it does not expose panics
-to its client. That is a good rule to follow.
-
-By the way, this re-panic idiom changes the panic value if an actual -error occurs. However, both the original and new failures will be -presented in the crash report, so the root cause of the problem will -still be visible. Thus this simple re-panic approach is usually -sufficient—it's a crash after all—but if you want to -display only the original value, you can write a little more code to -filter unexpected problems and re-panic with the original error. -That's left as an exercise for the reader. -
- - -
-Let's finish with a complete Go program, a web server.
-This one is actually a kind of web re-server.
-Google provides a service at chart.apis.google.com
-that does automatic formatting of data into charts and graphs.
-It's hard to use interactively, though,
-because you need to put the data into the URL as a query.
-The program here provides a nicer interface to one form of data: given a short piece of text,
-it calls on the chart server to produce a QR code, a matrix of boxes that encode the
-text.
-That image can be grabbed with your cell phone's camera and interpreted as,
-for instance, a URL, saving you typing the URL into the phone's tiny keyboard.
-
-Here's the complete program. -An explanation follows. -
-{{code "/doc/progs/eff_qr.go" `/package/` `$`}} -
-The pieces up to main
should be easy to follow.
-The one flag sets a default HTTP port for our server. The template
-variable templ
is where the fun happens. It builds an HTML template
-that will be executed by the server to display the page; more about
-that in a moment.
-
-The main
function parses the flags and, using the mechanism
-we talked about above, binds the function QR
to the root path
-for the server. Then http.ListenAndServe
is called to start the
-server; it blocks while the server runs.
-
-QR
just receives the request, which contains form data, and
-executes the template on the data in the form value named s
.
-
-The template package html/template
is powerful;
-this program just touches on its capabilities.
-In essence, it rewrites a piece of HTML text on the fly by substituting elements derived
-from data items passed to templ.Execute
, in this case the
-form value.
-Within the template text (templateStr
),
-double-brace-delimited pieces denote template actions.
-The piece from {{html "{{if .}}"}}
-to {{html "{{end}}"}}
executes only if the value of the current data item, called .
(dot),
-is non-empty.
-That is, when the string is empty, this piece of the template is suppressed.
-
-The two snippets {{html "{{.}}"}}
say to show the data presented to
-the template—the query string—on the web page.
-The HTML template package automatically provides appropriate escaping so the
-text is safe to display.
-
-The rest of the template string is just the HTML to show when the page loads. -If this is too quick an explanation, see the documentation -for the template package for a more thorough discussion. -
--And there you have it: a useful web server in a few lines of code plus some -data-driven HTML text. -Go is powerful enough to make a lot happen in a few lines. -
- - diff --git a/content/doc/gccgo_contribute.html b/content/doc/gccgo_contribute.html deleted file mode 100644 index 6374cd0c..00000000 --- a/content/doc/gccgo_contribute.html +++ /dev/null @@ -1,112 +0,0 @@ - - --These are some notes on contributing to the gccgo frontend for GCC. -For information on contributing to parts of Go other than gccgo, -see Contributing to the Go project. For -information on building gccgo for yourself, -see Setting up and using gccgo. -For more of the gritty details on the process of doing development -with the gccgo frontend, -see the -file HACKING in the gofrontend repository. -
- --You must follow the Go copyright -rules for all changes to the gccgo frontend and the associated -libgo library. Code that is part of GCC rather than gccgo must follow -the general GCC -contribution rules. -
- -
-The master sources for the gccgo frontend may be found at
-https://go.googlesource.com/gofrontend.
-They are mirrored
-at https://github.com/golang/gofrontend.
-The master sources are not buildable by themselves, but only in
-conjunction with GCC (in the future, other compilers may be
-supported). Changes made to the gccgo frontend are also applied to
-the GCC source code repository hosted at gcc.gnu.org
. In
-the gofrontend
repository, the go
directory
-is mirrored to the gcc/go/gofrontend
directory in the GCC
-repository, and the gofrontend
libgo
-directory is mirrored to the GCC libgo
directory. In
-addition, the test
directory
-from the main Go repository
-is mirrored to the gcc/testsuite/go.test/test
directory
-in the GCC repository.
-
-Changes to these directories always flow from the master sources to -the GCC repository. The files should never be changed in the GCC -repository except by changing them in the master sources and mirroring -them. -
- -
-The gccgo frontend is written in C++.
-It follows the GNU and GCC coding standards for C++.
-In writing code for the frontend, follow the formatting of the
-surrounding code.
-Almost all GCC-specific code is not in the frontend proper and is
-instead in the GCC sources in the gcc/go
directory.
-
-The run-time library for gccgo is mostly the same as the library
-in the main Go repository.
-The library code in the Go repository is periodically merged into
-the libgo/go
directory of the gofrontend
and
-then the GCC repositories, using the shell
-script 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/runtime
in the main Go repository.
-
-All patches must be tested. A patch that introduces new failures is -not acceptable. -
- -
-To run the gccgo test suite, run make check-go
in your
-build directory. This will run various tests
-under gcc/testsuite/go.*
and will also run
-the libgo
testsuite. This copy of the tests from the
-main Go repository is run using the DejaGNU script found
-in gcc/testsuite/go.test/go-test.exp
.
-
-Most new tests should be submitted to the main Go repository for later
-mirroring into the GCC repository. If there is a need for specific
-tests for gccgo, they should go in
-the gcc/testsuite/go.go-torture
-or gcc/testsuite/go.dg
directories in the GCC repository.
-
-Changes to the Go frontend should follow the same process as for the
-main Go repository, only for the gofrontend
project and
-the gofrontend-dev@googlegroups.com
mailing list
-rather than the go
project and the
-golang-dev@googlegroups.com
mailing list. Those changes
-will then be merged into the GCC sources.
-
-This document explains how to use gccgo, a compiler for -the Go language. The gccgo compiler is a new frontend -for GCC, the widely used GNU compiler. Although the -frontend itself is under a BSD-style license, gccgo is -normally used as part of GCC and is then covered by -the GNU General Public -License (the license covers gccgo itself as part of GCC; it -does not cover code generated by gccgo). -
- -
-Note that gccgo is not the gc
compiler; see
-the Installing Go instructions for that
-compiler.
-
-The simplest way to install gccgo is to install a GCC binary release -built to include Go support. GCC binary releases are available from -various -websites and are typically included as part of GNU/Linux -distributions. We expect that most people who build these binaries -will include Go support. -
- --The GCC 4.7.1 release and all later 4.7 releases include a complete -Go 1 compiler and libraries. -
- --Due to timing, the GCC 4.8.0 and 4.8.1 releases are close to but not -identical to Go 1.1. The GCC 4.8.2 release includes a complete Go -1.1.2 implementation. -
- --The GCC 4.9 releases include a complete Go 1.2 implementation. -
- --The GCC 5 releases include a complete implementation of the Go 1.4 -user libraries. The Go 1.4 runtime is not fully merged, but that -should not be visible to Go programs. -
- --The GCC 6 releases include a complete implementation of the Go 1.6.1 -user libraries. The Go 1.6 runtime is not fully merged, but that -should not be visible to Go programs. -
- --The GCC 7 releases include a complete implementation of the Go 1.8.1 -user libraries. As with earlier releases, the Go 1.8 runtime is not -fully merged, but that should not be visible to Go programs. -
- --The GCC 8 releases are expected to include a complete implementation -of the Go 1.10 release, depending on release timing. The Go 1.10 -runtime has now been fully merged into the GCC development sources, -and concurrent garbage collection is expected to be fully supported in -GCC 8. -
- -
-If you cannot use a release, or prefer to build gccgo for
-yourself,
-the gccgo source code is accessible via Subversion. The
-GCC web site
-has instructions for getting the
-GCC source code. The gccgo source code is included. As a
-convenience, a stable version of the Go support is available in
-a branch of the main GCC code
-repository: svn://gcc.gnu.org/svn/gcc/branches/gccgo
.
-This branch is periodically updated with stable Go compiler sources.
-
-Note that although gcc.gnu.org
is the most convenient way
-to get the source code for the Go frontend, it is not where the master
-sources live. If you want to contribute changes to the Go frontend
-compiler, see Contributing to
-gccgo.
-
-Building gccgo is just like building GCC
-with one or two additional options. See
-the instructions on the gcc web
-site. When you run configure
, add the
-option --enable-languages=c,c++,go
(along with other
-languages you may want to build). If you are targeting a 32-bit x86,
-then you will want to build gccgo to default to
-supporting locked compare and exchange instructions; do this by also
-using the configure
option --with-arch=i586
-(or a newer architecture, depending on where you need your programs to
-run). If you are targeting a 64-bit x86, but sometimes want to use
-the -m32
option, then use the configure
-option --with-arch-32=i586
.
-
-On x86 GNU/Linux systems the gccgo compiler is able to -use a small discontiguous stack for goroutines. This permits programs -to run many more goroutines, since each goroutine can use a relatively -small stack. Doing this requires using the gold linker version 2.22 -or later. You can either install GNU binutils 2.22 or later, or you -can build gold yourself. -
- -
-To build gold yourself, build the GNU binutils,
-using --enable-gold=default
when you run
-the configure
script. Before building, you must install
-the flex and bison packages. A typical sequence would look like
-this (you can replace /opt/gold
with any directory to
-which you have write access):
-
-cvs -z 9 -d :pserver:anoncvs@sourceware.org:/cvs/src login -[password is "anoncvs"] -[The next command will create a directory named src, not binutils] -cvs -z 9 -d :pserver:anoncvs@sourceware.org:/cvs/src co binutils -mkdir binutils-objdir -cd binutils-objdir -../src/configure --enable-gold=default --prefix=/opt/gold -make -make install -- -
-However you install gold, when you configure gccgo, use the
-option --with-ld=GOLD_BINARY
.
-
-A number of prerequisites are required to build GCC, as
-described on
-the gcc web
-site. It is important to install all the prerequisites before
-running the gcc configure
script.
-The prerequisite libraries can be conveniently downloaded using the
-script contrib/download_prerequisites
in the GCC sources.
-
-
-Once all the prerequisites are installed, then a typical build and
-install sequence would look like this (only use
-the --with-ld
option if you are using the gold linker as
-described above):
-
-svn checkout svn://gcc.gnu.org/svn/gcc/branches/gccgo gccgo -mkdir objdir -cd objdir -../gccgo/configure --prefix=/opt/gccgo --enable-languages=c,c++,go --with-ld=/opt/gold/bin/ld -make -make install -- -
-The gccgo compiler works like other gcc frontends. As of GCC 5 the gccgo
-installation also includes a version of the go
command,
-which may be used to build Go programs as described at
-https://golang.org/cmd/go.
-
-To compile a file without using the go
command:
-
-gccgo -c file.go -- -
-That produces file.o
. To link files together to form an
-executable:
-
-gccgo -o file file.o -- -
-To run the resulting file, you will need to tell the program where to -find the compiled Go packages. There are a few ways to do this: -
- -
-Set the LD_LIBRARY_PATH
environment variable:
-
-LD_LIBRARY_PATH=${prefix}/lib/gcc/MACHINE/VERSION -[or] -LD_LIBRARY_PATH=${prefix}/lib64/gcc/MACHINE/VERSION -export LD_LIBRARY_PATH -- -
-Here ${prefix}
is the --prefix
option used
-when building gccgo. For a binary install this is
-normally /usr
. Whether to use lib
-or lib64
depends on the target.
-Typically lib64
is correct for x86_64 systems,
-and lib
is correct for other systems. The idea is to
-name the directory where libgo.so
is found.
-
-Passing a -Wl,-R
option when you link (replace lib with
-lib64 if appropriate for your system):
-
-go build -gccgoflags -Wl,-R,${prefix}/lib/gcc/MACHINE/VERSION -[or] -gccgo -o file file.o -Wl,-R,${prefix}/lib/gcc/MACHINE/VERSION --
-Use the -static-libgo
option to link statically against
-the compiled packages.
-
-Use the -static
option to do a fully static link (the
-default for the gc
compiler).
-
-The gccgo compiler supports all GCC options
-that are language independent, notably the -O
-and -g
options.
-
-The -fgo-pkgpath=PKGPATH
option may be used to set a
-unique prefix for the package being compiled.
-This option is automatically used by the go command, but you may want
-to use it if you invoke gccgo directly.
-This option is intended for use with large
-programs that contain many packages, in order to allow multiple
-packages to use the same identifier as the package name.
-The PKGPATH
may be any string; a good choice for the
-string is the path used to import the package.
-
-The -I
and -L
options, which are synonyms
-for the compiler, may be used to set the search path for finding
-imports.
-These options are not needed if you build with the go command.
-
-When you compile a file that exports something, the export -information will be stored directly in the object file. -If you build with gccgo directly, rather than with the go command, -then when you import a package, you must tell gccgo how to find the -file. -
- --When you import the package FILE with gccgo, -it will look for the import data in the following files, and use the -first one that it finds. - -
FILE.gox
-libFILE.so
-libFILE.a
-FILE.o
-
-FILE.gox
, when used, will typically contain
-nothing but export data. This can be generated from
-FILE.o
via
-
-objcopy -j .go_export FILE.o FILE.gox -- -
-The gccgo compiler will look in the current
-directory for import files. In more complex scenarios you
-may pass the -I
or -L
option to
-gccgo. Both options take directories to search. The
--L
option is also passed to the linker.
-
-The gccgo compiler does not currently (2015-06-15) record -the file name of imported packages in the object file. You must -arrange for the imported data to be linked into the program. -Again, this is not necessary when building with the go command. -
- --gccgo -c mypackage.go # Exports mypackage -gccgo -c main.go # Imports mypackage -gccgo -o main main.o mypackage.o # Explicitly links with mypackage.o -- -
-If you use the -g
option when you compile, you can run
-gdb
on your executable. The debugger has only limited
-knowledge about Go. You can set breakpoints, single-step,
-etc. You can print variables, but they will be printed as though they
-had C/C++ types. For numeric types this doesn't matter. Go strings
-and interfaces will show up as two-element structures. Go
-maps and channels are always represented as C pointers to run-time
-structures.
-
-When using gccgo there is limited interoperability with C,
-or with C++ code compiled using extern "C"
.
-
-Basic types map directly: an int32
in Go is
-an int32_t
in C, an int64
is
-an int64_t
, etc.
-The Go type int
is an integer that is the same size as a
-pointer, and as such corresponds to the C type intptr_t
.
-Go byte
is equivalent to C unsigned char
.
-Pointers in Go are pointers in C.
-A Go struct
is the same as C struct
with the
-same fields and types.
-
-The Go string
type is currently defined as a two-element
-structure (this is subject to change):
-
-struct __go_string { - const unsigned char *__data; - intptr_t __length; -}; -- -
-You can't pass arrays between C and Go. However, a pointer to an
-array in Go is equivalent to a C pointer to the
-equivalent of the element type.
-For example, Go *[10]int
is equivalent to C int*
,
-assuming that the C pointer does point to 10 elements.
-
-A slice in Go is a structure. The current definition is -(this is subject to change): -
- --struct __go_slice { - void *__values; - intptr_t __count; - intptr_t __capacity; -}; -- -
-The type of a Go function is a pointer to a struct (this is -subject to change). The first field in the -struct points to the code of the function, which will be equivalent to -a pointer to a C function whose parameter types are equivalent, with -an additional trailing parameter. The trailing parameter is the -closure, and the argument to pass is a pointer to the Go function -struct. - -When a Go function returns more than one value, the C function returns -a struct. For example, these functions are roughly equivalent: -
- --func GoFunction(int) (int, float64) -struct { int i; float64 f; } CFunction(int, void*) -- -
-Go interface
, channel
, and map
-types have no corresponding C type (interface
is a
-two-element struct and channel
and map
are
-pointers to structs in C, but the structs are deliberately undocumented). C
-enum
types correspond to some integer type, but precisely
-which one is difficult to predict in general; use a cast. C union
-types have no corresponding Go type. C struct
types containing
-bitfields have no corresponding Go type. C++ class
types have
-no corresponding Go type.
-
-Memory allocation is completely different between C and Go, as Go uses -garbage collection. The exact guidelines in this area are undetermined, -but it is likely that it will be permitted to pass a pointer to allocated -memory from C to Go. The responsibility of eventually freeing the pointer -will remain with C side, and of course if the C side frees the pointer -while the Go side still has a copy the program will fail. When passing a -pointer from Go to C, the Go function must retain a visible copy of it in -some Go variable. Otherwise the Go garbage collector may delete the -pointer while the C function is still using it. -
- -
-Go code can call C functions directly using a Go extension implemented
-in gccgo: a function declaration may be preceded by
-//extern NAME
. For example, here is how the C function
-open
can be declared in Go:
-
-//extern open -func c_open(name *byte, mode int, perm int) int -- -
-The C function naturally expects a NUL-terminated string, which in
-Go is equivalent to a pointer to an array (not a slice!) of
-byte
with a terminating zero byte. So a sample call
-from Go would look like (after importing the syscall
package):
-
-var name = [4]byte{'f', 'o', 'o', 0}; -i := c_open(&name[0], syscall.O_RDONLY, 0); -- -
-(this serves as an example only, to open a file in Go please use Go's
-os.Open
function instead).
-
-Note that if the C function can block, such as in a call
-to read
, calling the C function may block the Go program.
-Unless you have a clear understanding of what you are doing, all calls
-between C and Go should be implemented through cgo or SWIG, as for
-the gc
compiler.
-
-The name of Go functions accessed from C is subject to change. At present
-the name of a Go function that does not have a receiver is
-prefix.package.Functionname
. The prefix is set by
-the -fgo-prefix
option used when the package is compiled;
-if the option is not used, the default is go
.
-To call the function from C you must set the name using
-a GCC extension.
-
-extern int go_function(int) __asm__ ("myprefix.mypackage.Function"); -- -
-The Go version of GCC supports automatically generating
-Go declarations from C code. The facility is rather awkward, and most
-users should use the cgo program with
-the -gccgo
option instead.
-
-Compile your C code as usual, and add the option
--fdump-go-spec=FILENAME
. This will create the
-file FILENAME
as a side effect of the
-compilation. This file will contain Go declarations for the types,
-variables and functions declared in the C code. C types that can not
-be represented in Go will be recorded as comments in the Go code. The
-generated file will not have a package
declaration, but
-can otherwise be compiled directly by gccgo.
-
-This procedure is full of unstated caveats and restrictions and we make no -guarantee that it will not change in the future. It is more useful as a -starting point for real Go code than as a regular procedure. -
diff --git a/content/doc/go-logo-black.png b/content/doc/go-logo-black.png deleted file mode 100644 index 3077ebdad0726b3fbf7451897cbeaa33b3cb0bb4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8843 zcmV;6B6Qt}P)NBAxQT++(s-)vw4zFyMnn6wr6HC6a(X-R#Oo{;o; zG{-)Cy9|$7Ch!Qy%mBRWCEX_JHzhq^W?|7P>3ezKCh1-T!}XZI4Va4)+`|?=Hz4-$ zn*#`*L4LP^$3{uV6Tl^{9IXNK@McM`VlvJGqG|wSlks^;pG3PAn4Hr9tP5aPK|)lb zZ7Ko9w50Em^yV@GuAcMm2Fz(myEx}A?qkGh?t0!=I{|S6;A`br6PTHY6xhpG;>#Tu zCrDb-mfETS*xizD$Aqi|Wc3gStq>rON_vn9JH`L=5D&r(8$la%OS+Ha*E_%&Q}~cO z#&TK*AifQa_G+%T1rsxe4_A#)s6$W;@yKznb=>z5_ml>N0Gbpf~(WWrx5 zFpER{=So_s1>j9O^HP8?=lrb}BOsR8(oFszQD7o>VDfGR)MJ390N8R|%On8W3+Og; zy=j2CkI$arxaPC=Bam*AbT|QA(iYoN_$IgGw;73GQvRHzcT4&v8m>@+q^MDhVGVH1 zjgszS(sn5_f~Em0`Q4}k@M6i46n^17l5R!&G)n3PXcLM7cnew|;XaN@`WxO`h#-X! z`58&S&vkY4+b-wRjiO0Y3E+~p*w!xT`v6BL6RDnwdQsA!N%}9%9i+}X4b|tsFa()$ zE9V&DxCU}d?>ep$861na_Fm_=HDU%%I$vy@bBrj&(LM}GbC%D9U)S!;+Rq_)-ivT} z7~ti&hjz^1+5~V(TTH80ULYnSvHN$*ieZCY%r14MlQZ%i?6Cuh246oSZ$ zH7PTI>u!jV`vJrZ$F2cPwfuHe($^(@86k2F&z81!0H7M-a~+^PppfF#Lf_2b(^a9Z zs}sN_ZK17M(yt(?yA>0U`z3t}e{Hd*UKLu)G*(uDW^ZPKnwB&+@VKN$wD=USW`x8K zDa6}mIqxjjFvYna#vFV?AwBCL*Jc_vg@7@QT+L_uB>fV{If1{{k5H mn3~w(to09XZ3#*u?vbT0a5@j%lqdzPd~ruL*w1f>u*Y$O#qj)`C1!3&s!AO zJ!A0xThjX_ePfBli-iEphs!Ilc^#N!IRIw?@~lEE@8~?lNZy^J8-Mf7XyiOVpF!i~ zFf|{P^v`I}oHJz$MbGAg&Tvg>G;dxZO>KzlJjZW)-2X<+woO{n=4#anF{;-oFp||w zvj2b_xv k_An{j^Stb1*Op@P?&umsYOE8_{^k~W_ycDJOT!Y8SAe$Gdjs7qaqU4W$Un&bw| z#wPcfeP1i-i@Ne^fwa4xHvF}>I3KQ#bEeU*XC!?AO??ueq!roF!aSPP%*h%a!YsW8 zAa{YUel%Wv0=T5j)fy%J1X}GDK#)bl{3B$-a@VHW(i}4#U#SoulL8BAX;cL!>|g83 zfpaqjn=pajz%gnddQJn9Ni@#8C4J5P&jReZ1z!7%19~kcYX(i$%5g3#=2h-b0GG5< zEhFg{nf!M!X(#Y;K8l~S+-BOylAI0T?FuPi#_pLp`Dx6++&q3^vqBE$uPLrJNOS$? z0mDV^eG2Lq%Au%DC*aUD%D{en0>9vwxfz%&Wh_U@WW~61w zr?vD1;#`rR_{*4-0vNm8_Xi+n3iJ4yS%pQbKco hr^2Wd#N_9K)?T#0yCJ$j2vU~e;YISzZC-W `FZ=PIn17ZB zIoCOx6*5S!#h>b>KL;g!OCcEjAm(tk%zc;R`3`{B4`E_s`aXZ%3E-}7OJBj9@eG~? zfb%7^#By7WLfq?Dn6%?e)Q?K~09t6I%=c|X#aARfrckfs6$%XBR?h#t!m9B8c>ume zp@zuY@tyj(-e!fYkuzw?7w6H+=_QzzRrJ@JIPWmRsuy7IS6F #3$|Arm2jtea zDy+hu#<@Q!>35m@MqJb^<9zeA1}FTtVq$JqT%I%Eg#SJTdjBbfdMA$qvWFFNJGVie z)ULp_H*>8YP*}FJ2hb1GpMO+}kxJV7XgS4vzQQuJTfPWve}MmEMNFSo$o4<0n9n%1 zg7-D%?(YKNDJ)QM+yLM@@s;jIC>_V|`$xbhEj}e|zSat;9#BlQwy=OOV?R;K22I-f zX-2A4VFoU?*_tw|r1eXfk((9cQ=i0~%V~8Bu-c01g@7%?B)=1~Vgo{>ihDSykm-Mv z |< z0AKiX2TPqh0o>YX7Tc;vinbuZI}{RPZ(%T-81$PN^j&;D%wtS}#{YT|$O=wE*I|nN zvEu6HLuj=R0@}hHKwS&1T4BxE{q$3fV$l1TLj9C~M?j2}*_1TvAPvx7qfla^8K2k8 z$|n_82PgsD)g?VFNw<>8vYUb1iZtw2NO~1OvSlP2+;}x9#G0y@Y!gg^V+s^{DO1f- zmooS~KaN(goWL9aJXeC0n9$nU!A1(K M4gdA&j~IR&69`Ofn1YMCIjiUHsz{`Vq)9EVgm zgao|@2|fl(_PFM*WM%apD-|jNUyr|$X7YTN;~D@h BX$|n37u+VqK$H0TuMgBbd~w6#$#pa(4a(gkJ}JUja$;X~r-CT#3%hC?>8J z6bsj697AWINYly9ba)2?+^e`bMK8Y@<97{;3A#dK*|tnM#cYUvCzWdyvJ}3eKsA4y z=Sc^ungz0lDbCZWkVUc^@Y{wP?^9T6BgI%>1>fh~=f(3Tw*Z2}PkO&jtw~|Y%nqKV zP)e?YK6nJup%|R^D Sk7S1PF%@% z`2Rva*p^AHiZLzQP@+{a##N_Sk#_>EQma_QqaF}7(#ai6ytLCKV;rwdA!Fktll+`Q zpm)Og0!R4$DYTfC&pxFqul-sG8IV?7czFxvWG!Htfkpd-E?;|QKIDl0Z}`C`;_L!I zUYw@Z%W*d CN}F2PfnLvS=P z?z7y-Rxoq{VR&BB|6FO@zFPrjOD4J$^Xje#9JNTKj9hUSIo+R &l)S^v`UL&y^3vstH}`#?XJVD%5J`B z;!iP2PVk>eKD)p`Kg&dYiQk{+H ! bN$;C@zmdLdQ&=W5gvr&37SHjY6ce)vQ@RqN*y()OEefe! z?UH^}aeZ3{eZHUjdklhNas~U*HuKn|5Vx#>DeYy >Ag;fRx;m-JRX@1dWJBpT&d1;)aNiw*R(3An6caJY-{GlE45 zOL0C0<5+-EeE^_tW6Zt*AouVXSNU>FOPR;hoNtF>I@eC_WfB2BjF!u<2f$S_NH=pc z_CDh@l`Zb8apqsaX}GLnffyr0QVjNSwA3Sj?Yv@)X0ABR`J(r;T3^j-guKpamID6H zyBr9Lt5R7Q!6xu-`t_{}>(&k_Zoy zwT=JZu29x)3;#RGech@MYy2lSPWcrQ_(E{) LS+ti_s&aHMnK%MLGQ%Ics3T50z@QEh$-Pua9l{J!nn916!SWW7z zq(9}k;0TaH2_L2fM(~HxjNe1QHZVqg0Bzi9#wLZ>)LzEUR$EUg7D?TJRyf0Ny7~Ve z0A%5kLFPp#V`{#)RonW2o9rvuu0`07q2V?&51W{O{g}RATgbu63AjopxvbKyZDwaB zu`McZ+Zox$54Hzbqci>NH&fhLJ%c;KV9Y8kD13$vIZ3CSS)<{Hf-cWpwfg$Y)trs= zku4Z)MFRgcuNxVU6ADSmhcKP%oj+HKblL=9n_)K_o#~x%zSjYMcaCw{4|Dhe*K klbYS}KR9FUd4;E9#nYSNX zs6byV;Ocp7Qrtea5fi|6gskWDcE|KJ@Y;Z7dqEpGZ7F{xlW-JMVN@Z5;w%&8B(KlT zA(_`ov-N8kXYS1MKFf7aEOPM8AMIh%T3LY+r(r5^>VKJu(vFatM1wrYq%9~WCa2tW znIO2!F`Qc%CkyIUx^d~@IR63TnO3aNXhHv73OSFxj$HbdLfp-k|2z#L)yDabK*Y#} zVO~UgK8xTOSV1%25)^v4k87O9pF-;$ e!p~H1_gJS)^F*gVYkXVl~sFThN8rS7D0M|=cB45HkoN=b|ObKDu=}hW76*nZb z0<6PKv@-zhQN^s49KOcAjE_y!3B_byD^*bK%+P`^4^UeS@ qqs>%3)&)s5BFX)<_17lfaTo5^`BtAe3^SbwF>iL2RP_eOo-UV z^;$XfXNs8UMFGyD=r &j6aC(b8P<$R*T@9F0GO;4_-hsN z42@)%rGL$&9n<{9e+ChJ=M?f1Z&p|henz3(!cj*mjp_2_=tf6GO+)41jL^-X73we* zEuQvX?r9V@@{^MO!7 WeFe_@A4&Q{%&hI0VLoqi8jbO=LVb`X#T`bk6eR9PBMM*ZQ{2z- zIS3YOqlzoU+Z2`nStiam0oJ_;a6vX)LTJ>Wf#0RLg;ZK`kAYU^T6P7;wTg4!#=YFG zm}s8kp3XxGeP$`wlX2`}1-9{Tak33Kz MFs}}A{?}lgnE5xzc%4vK`8>|C zv(A^cbTq%;TB+2i#gsHJAXI(_O>29)< ^o@;&ql58op zM;1!@b)wmBqaSZ{{Z@ysS&5(e&81G7-Q3J~P?1lgv0lc2nseRi%#o?@QgGEd)2~G_ z$I_(USw7D*7`BT{Fa2Q@ys=w(H>qcxZ WoQn(e5hzva8b^m!+JatD2A z!l??O@u(9>Dw7&J>)fwLvj>Ym8Kfi@R)Mz=ssqp4B-}&MI!+mvbPQ!UVJ`z7wu* z&*K-_)<{EWrsE2!V$CirGJpm+#Cc92Q7>VtpLc#(Jrj9~V_1IYltOU$f1KZFHT_p= z;@%?Zx1rGUn98kA!<)JK8Ls090;d}`a|gd~XIvgv46J|0`B?cC5VUXQ{8dgMbvi$K z7Ge8mTKW#G3knOYHuauX+?CQ|OIFHlj1Hf0AZlX3u6N{(B_)rzFvW;-zBkj!*SJu| z1_ri{ <0b%pSkm8djA_L*By%CA%RFv3N%~a>wj W?tcE|l9I!1EaI0m?H6Rf)_y8Tw1R2Li z@jmAalQ^xo9c`7Pl}*!`d1z@!b&7d?X4;vlx53f!S;xBNF@r8~Z6~<4eF~{kgIs@~ zlj0|km=_eYFeZ3xB6hWrK^{@8LqF;KtV44MJTvDT6f*1Eou;s@aX-#$ukliIu&B#z zuVj24ppRalFMe8az1vYpl5YSWe{I(Q)B-|rL@@ _)VR2(Cv zxQf}9RE)a`Zp& JCJtmK#@cWisza+_qe_?T}(xL9KNkGuJ`7k_gvV|)(4$+4Q2sniP~ z?Kr2I^yO^zoafDoi-cQnA4V0kTaGKlL;n~8v9MkMw?!c(W-|awDJCPE7O8fhSvE?e zqnIn) %YpZk=vmAcOxveC~m&70YRPN`GP|3=@-itj#v%A8I5}< zn#fG27H%}-%sk6Cv@K@q++?j~Lgg5MF-KaQRNSk1ACk!^Wh=yE^*^%Ck1`)I<;WRh z9)$+3VxkQ47;%Kd>=l5ulC6@-c_Y4StGlLg{Jy*co27x}%Q&XCGW*vVOA8h4ViGrF zn*AwOK&2CGzI9=CZlZ6e5E?@Wk@ID`?s~5Iwa!PIQH;IWUUGx@Z3D28UoUqoX*F7( zq<_UZ9cMr+nAxD1nv|zg4l$@F6c=s|IvU+p1Y}*P!V;PbbFf)Heq+mg8tD8Cri%rf zZ3mQ#T<^4Ec74q%f$B=l$`tJ2zMJTS#|Z@-b3pS+)5|d@t^ZnFsN swV zs{uIMRdNqDd@Cw_zcU|Bxydo@9Ofy U1(6_@#YfImnaenbqo&E;Jb#NOc{fI*5yq*75SS><3`~})6JI^_10c -)SyTHDA<4dB&ow%p!I)ur5Z zrJRN|le1Qr*V#yyAS0&T`@$O3Qp?e98Cbz>2$e00OPU&;aIxxKR Q6IU=jwGuY;I&GF!GmCcHrMRZ87E`iMF+VfyNRylvzAKIQeX1cyQXK2m zXrQBLjSlD64N3Y4#MokXWHO)}10WVA${|P&DaIC!4YtLyQ_fTtLcANHP=g?_f<~56 zl0k!ZaGs~=yHCI;OsvL0mYc5j>#b~%i_>975)3Vxc(QU8mWpKgoJKH>DemfG+3i(D z5<9m*foY3ZtrXt7`0R}0$^}cN9+LDo3OSp@&fK4i(6T()F2w>x78;nq=du93Eo7Z` zU})i-w#=xJdA1D#B;)3ynb_8Mrx8{&fbI7H?@L 4bO4QF|!re$t`aM+=^pTSPWWPpQ^BOd}pmYS9;;jdXJ#+Q6QhG|%V z8Tz8)y1$c(>3JjW7#2LY !*E5*%K>E>FtDy|WfVz}q43MC=-t+qd(Z04~(nuR#- zL%W%&Zp6a~lg#QzPB<1f itfr*D=`!9ARP!0~LU2tVr|N_Ql5X+J9ygVrXv%#91b9 z3!u0J>F}2j9xo|YAImM$e3b%SZ>1wlTem0_uYE`{v@ziPQojbViPu{c*C_V#zb4lo z2hpJa3IjTr04`~znrVtQ#T5t^3aE9aQU}__YIGX$U^$J`CCvSL#W<8@T)YvVs!?%a z=vfE!Gz{WniV4WeX?==WD7KDqL?QXPpja5Tp8K)Y@O=tJZfg`4xOQ<5wTdg+>(InU z6jmI31=IMdmG(#gw>}7yjC1^LEuRNZqe7;}t(Z)0Ncp3Rd856$d>i3bN3NtXSKkJ> zZUzJsn2_7>cm9RR`;1~%PO69?TWs5>kS}Q^@-mpJ`xQ#74=a>bsC62<5y7yN*Si#x zC-M%E&mg3p 0FQLH;kWUp_n>_9Kn9T zyB*)@m5POA&HuBtX*q>B)w7TpLq*rNoOV%Rjoi%+P 6F*o-IyvkiDxJ;am%ZvFUhStil}w3PwKSjbw1vgCJRMm?sO>Q%|)o8TC) zRmgk18x3Z=dCoXcP5?~vcOK^bN(6?#tdL*Zrns-(y^5iQTX>k6Y-It5ou4_WSl~(s znJ*|T4;s@NiRUJOTR&}>Ni~MAX8YP13puH{a()W-ZyNLQLA0Okh-3Rx8?)D 2;;_vSn-tb1b}ED_J`brgx|Rkp zmCWNc+5AccD;~R%$@B(Ezu|nEN@v Zj&)dJ zE!a1-GO<;^r=R&<@5DFj2S7Ohbp!XcAA-b|2OYo%>_Hms%Sa{ln8TJm$L@R8x zNpW>X0dO8wEH|D-bG-}z&Y xAZG3cWyq}IVP-;Dl= v;eZz^z|R*R4pK zXBDfBy?}o+skm2mAFr*7*I3epNlV)DT1C Px#24YJ`L;(K){{a7>y{D4^03 3Vh6cmA1 z|8stK=1ki&%nZ%UAoqUX`EK{^?%TI-SDmW**T3qtYL#y3_BGwMIyhUj)xoYbdY(z| zO1h<6-Aa?}%fjBJHznQHuE1@1P&Rt**179vv`hcZbZZJ>Ya3jfy4{&A4{AO|O1?W* z?CRID8N2ok(| WZaX( qdo5`SIn-neeUl`w{&Z)D^oS|R`0W|iCea`v6m^xakjtG z#-;Z7cQ&rE$A7T*pJ9*pv&Y+Gg_?X8msP8_GTAa4ZLo$?=w7zp)5fOux-4N)syOMk zCbM#}2~lx$ObT+ejsLOZzqfIxJ$~8*@)Z-f3HE%pJ)dV|k&QR(_#L+Yk&V9gxT2{7 zf4dH|blGp(IK;-`Hukac-*#Nj&$n@mjZ1=pyK`)Rki90wZr>6Ci*#$*N`h7KR-_cS z MHXgDu)W&cdGi=PV_rGTXHN_rJl%m*p%f>1@{;ch =6Kg GpiOJ%7)}2SGWU ztj0nVR@bu3#&oRT^Y$5C=RDi%eRtZvV=4*hR;xu(04r-^f^wog){Oh8J$}ptZLmFl z#rCh;^Jnd~ZwV^4(ScZ@IHAEP=VJRxdu>~Le75c1wfz?%cFC@?=U)V2b;mT)JxmnF zU}|@S4aH7R$x_&BQxrGZm}AF3<@;8K$8M&*ZmyuSILaCL;8t)QQka+R_>1=XLX<}_ z*6y`f-85!NH!lp`Z2ZIoLKfj42%+4lu^J{!zqPR`vw9|9kPaXqYol1_Y}~I^L1COM z%PMB}Un+6g5Cw^>$}Yh@bbqjO$R(Ujys?n|VqB`_pmMS<6L7KQp3UW&=HZsj!983Y ztdW}{moEBE`n{X*yHY_}j|2I{|F;C4&zD$!#0T $_fxphu%-Xc5xxs=jg zTf%oJMww~j^Z)=jDcSD!zMeLIf+Cq>c*`;+SR9?hTc3yQczL9tsj#f?u2+O6oo3@U zkfPUwUfGytkFPgDYQy`A65+`Sv|Gi;?R`5EG!F+pUV-p_94w2sE`1t!jj~vs$?-gn zh4=uAu!wUmMsZ{*6zt1gtc g>s5vwn~*G-CE^XhhxY; zJa1!+35pcuZ4 Q##iMxO1o3^CxkQuqJLXiZeaoW!2NFC?@Ivgnd5< z*JpPA4-xhcP?n{{8)6e2YOfy>uEk~etz}Z4aGkCzaI?YR?(+a($W8RtNJ=;k=0Qm+ zCF`~8RfD#2hK;}4u~BkK zM;4_O$wnnK{}YfjACFkv;XdJ hTlRcp$illrZETPWF;}B!J~%Id7nWGbol%l8xSfWg zWep~GvRc1Sr6i3}psjlX;hhA@%ET+P{ZqM7jX3WH!JTu7C1?*wuw1T<3E-+IZqY2h zbADJho5`Wl8`&{?F7DyWAX;DGCOwOCn^FeOSz_60xyCkpM+FLFL{KM7^A^8-2!Z`9 zDYdfusl=@3ilSiM9$TR6{$hgiwi0+)mNVo& MXPb?ipU8ShZ>h`CHWb% zF5V4Y0NgAD?V?m_*6&zFf+9iwKj nZ*i zfWruTUHO* l0%|7DkG_IWdbRHQhAgmf7T8 zhStSAPPZnV;j>MtB+32=5{+}nci3#|4g$q0frj6v;peXrV{B|A3(aH<79nxPi~-=p z8{4Rs>ud|8yN~Ukg%CNzu5T(zrvP8c$lZfwa9{b24Y()zt=;V$JJ|VVV711P;QYvr z-I7Xa3y2%^M>pm70h{&?P^kNuthIvLQvxI#XXIT`Bfg`U2|%;;$>Lu{FmYm4G%m8& z5@ R3|cP;R8eU_91#1qyz2Dy=OJmCCMm zW^Ak#iq8Fw5G0FWr~um|N 9hOk*YI5A4Z(7%|hc zod2#EBCvm*1bB!&&f4`E&E>1EQC%&MR--H`KNyAOdKINy1@cyz=2n_FUMQ+d*fe9( z&nouCiyEUKk^iq`o@Q!e-g;`fke}0%yvUjgL{yuvpt%Q7^krn(#}jXekoo=C3guWn zjqX@Fxk4`i3(Eq&5ZpSqS8Y_A1h{D6eG >3oekPlMFnX^KE#SIHtd-nkZ%pFq6TxVP}*BDo*hTtfdV&h73 z6Y~3Q@0^W|QKZ&|1{-n%ZfaxdbSKGs>?*nqH6{J2n=z(y_8wfw;)Ys|+LRd@PG{OP zJx)#jBs(S|reN*6Qb}x4O5s-bdIi)BRVwZfdU9nqu7^;xj#{f;5NI4C2)g%iXSPjT zJA(eAW}Y0RD5{P5UtF(o)bwjS27D|lSe^?CG#q{OZlc%$rMRG{pe+BS#zpaw;OV|i zjaH^xo&Yr8v7i*LGp PgO_se?68aJRq)zQg{&KZjx}pMj6#8W^?SnkYuuTWyIb zWSUCu;IO23R-{ mgpie*vJm|~y}*2JnL-xq-Z?V#P?6M}kQ zieQOOXSFcyDK+OvCAPrv#p-6cNGMC8mu$u?x~ILicj#Xw^vGR@3vx5G4$XG|vG=@A z#ok= z+WG3Qg);n(-c+&_&)D&Q1)*@y(I`Q5lgDj8gMy}E_WTK4r}qQB!*igl^P_8@JJW_v zik=);4ze>5t0Ht~C`rc*0lnVe0pGp&s}n(;LZ3 !N!61+C?;t6GUnX;2r~?AB}*HX2u*zv$-)) z$;V?oB-ECBkn7=RSCJTxr!z`NXd|t2^9s4bjEhl3z j@tTm{12JNS&^Da zR(N2g)X-bf)QRpt&VJX&QK8p`&E=N1w3wkR;P_51%3fl`iX;~rvbl4K1AeaVh4wyW ziPZ$*!q5*Zdpmi8$KWXq3WD#OBur#>8c+YM3FHU<9u&n}m1F5?brwB;#hdCBW=^LW zv`e1rO=6JZ+7u; QUh^=W_UYxe`x39h5}DcCU6$b zdpLi#g3DX&`DL{Iv>v(c^g!QGhY}x)$k*+rnVK20xGv>RgmEoTA{BI8d6aV41^D3V z# xps0O9gaxOJlPJ0_S>)V;`kG5Wnn+2&LGF@{{u z#84mOfr-z;MB`MpTuG8L%X_Dg-G77$>p;P}g@$Yu&nZR=lcw4x$*Oouwiw_=}J z|5+o@o@}!#29}~C1gCB{doJNU9mGQ2MsBy~4?=~w&mR91v;S{ 0XrGyD$L6C1dTt8h=F# Lq+05OPUU43!h0ClGUAg715&YZ=EmG~>=B>pubV jc1&GeMvx5#zlI=y6Tb6r#{_2Vk>($T9gE{(-jt zl>78<=%DZRZ88J#)j+UT + !G zKL9G$CUC#9wdETWl>gB_HyT%I9tBSy5u*(R#aj^SJe( VUW#)7D}Nm?wy@$GJEjc%Gn`uqK%s`;R2}@<5LguDAQbf$yAI=id2nVn zNaV4Jg)P{3*P#Fzs1+U5RYL);Fmn9m{h3wHu?xA1s<*po2b#nR6PeLwFk{UIU78Uw zR^Pyq*kU<8uCVjDK6Uk+YHF-JYSd5!*{`biZw$xQr;0Bm7hT)nKKKriZHP^Zcw9_V ziP6mNE0{P2vRF?!Zsb>pn4n;4*1bQ9HWMrG4zTwSnoLNbA0deUg@6)!+%{T2vNx3b zArwtL4ov(dbu2= D- z$ZQ^NygdZz?r=4q2GQx#oNJcngKTpqjn)Lr#5>gqyL_x+>PULf?$nZ)9>UhL4oYHP zfz|y^*!%n5Hu@j73yTO {OdQc41miVkpx2^6dIB@vTWIn_ zC{Mp&Ra`%)9jDkidlR5m1hk^|>cN(fRVBVES$$mMSLtmP^{0~SxjQqoX4t=ww;5^Y zdxJP&E)&N)1ix={d VXVadCu5sfPT#1o5gJmiAVuJ1t8OgFZ7htZU-e zRM~=F#_>eZ0V+* 9`aBc#dsvhwLbE=%X+e}Ust+iKs*!XbpTZ0=mmqL1fs*2i`|Y`zZJ!-I6~=5I zGO` +IZ!Y@ zV=_8~?+~xd&>QbgET=E;JXYiCLJdiAZJGGo0yIJ3!Mf$2sG`bAxpj&I_hh0R6Y5T~ zmx#JUGj1u%-<0&jJwF!f@tP(DJ2sWi4Wn#$!varcKA@N9qn5J(2WA0P7vtT{k5TFi zlngF3lAs&Z(Y~}#aH|xUxv?NrLSgoRw6`m>m1T6@Mlx;TqFswgc&<+IlDdm%#jALf zz~;?hB|5R+k3iXAPpvkUeIhJ| u-)ZBH@DPs5@;S>I;l4N6SLaGogSLYLG( zHs@w0EY8f@6ztU{_!?#b{47}!f@d{|_C0ZTK=_ZqRnqz-SA^17zY_2LAWg$V#}ZE| znF|CddiUa-#td|e_wQkiLSIY%0xsCyK;e(7Uzc5jV?|$~OM_5~L#RLL4uW+!LHUU4 zrQUol `W zA@eB!Ao~&v>0aI&8s@pTx&PBbV%2xlFD}$gDULga*LKsJATymbb8cN |)U5^XkvtAftY_=#nx zYDLPbQXd3=+y}c)1ea9Z9#xa!V+^qZt_|^qr&e4<9sC7cvtkB;83(bNRvRo_C6p9d zx7&cz7X<3P8e%(#l~ae74*Bvj1rWr8nW0Cq;@7PxDU*Yn!M!{%=@etnPtxxcdKnU& zKIrcs2&dVz3YpAJ`jmwhNnQ~jfU!LhpQv;fK_+?1`mrPdwM5 zmiti(6{RoSuff&pBl^6^A>@=)Nm-us{8}^DD=uyJF8EVWga%R1|5h|%$i=b6iabrG zdjgf?I^IoiJrZj)0IS-)aI)lccRvO+x!bOxAC_0^NiIqdT6=tGq3U9q1%l;|=?r?b z1uoFpVMcQ1?~0S;9)RtuHOl*unSV)wkKe5LU?gt9q>#My3AU+WZ9)I|J=Wh4A8aPV zrXYF+%NEelqbhs-Mp)&_)69)F@AE}_%R=do2`gG a|Vh#57K8R5UO_7RQX1?GpdoNVBEtRjEYCD*OJ&a zSW(M2dC>YR2Vk|6&$a{pevxJnFOy18uzgLkl2!pGUB%OKtF8~ZAvZ#GLEIy8<6eM8 zAUAsBbxKhpcu!=+BLN8<$;y7rJpbaxjv~Mv1r+^!l8XVWPu2yTiEEP7ZNC9LI1}_~ zBuLa4g1cm<>qk-6{!sQe4^@nQwyy{^AM*eGAEJf{N^l8f=}B2?>tsm=5f!6l=Dya_Y=Q@;XjoL4fxZNZ$1bni)e*}okz}hXs9sX-Wm(FNO3R6TMNDRiR+!T`9HH*(07(cZmHvMH_ z47h|5G8#`}0lAz%QWnsz)w;UDm1@hnAg6>s#p#FLft&FV0b0Lc37mBy6sqEX_{ER} z^+z5N{aIb|VfIPkRBksD0>XCmqB1U-ha0z~h-wSar%GI> sqtO%?U)fGN6ZkqP+$0MC(7kgJn z9--*R?GkE5{Ca=w$sCu%uC>|SZN;D2kpiJio){=u%{D_Ow>8StAyg&$AXKoXxl?W% z5^|LxZmObPWb(yXO=-r7Ysvx*#`EIdgwr%Ru&8~)w<9iKIk~NN4T)27mdV>Nz|@|` z-k&~N18|9xU|xjE-QtCg@>ElHg 7k3IuTc?TvR_@m0r$3?we5!ips26%Al8-qc3icYTL~JU7wEi_Lc5+= zJF!EQmwKDBf~Vo3Ee~vFU&eh~h%H;j|5%_P-?ge1;LuEfc%dDBdRv-C$X)8du`&d| zII%2AK~sG?zc*KrRwFXe%+Q`%J_7VBS!((*IA-0G$$)(+_p42P1cW4K5%JiLoO2i} z3lAnPS%gIqsPMhjwFrt9GdhuAJAvl!;r#onvr5RF1+r;au*j1%S&6HPSzUq~+A~1$ z?wW{`s90AF<}t)?&ja2lbKff;>bfpl61fi>gt)+0DsDocouT$4lc)dh8s%@+jftej zJ?arEI-M2+6|Ln9yB8y<8PRH28&fjeG5F@*61S>v%?u?KJ%S6GJsalt!_gXzLL67X zXg)t!byrl^gp;_jBz^@k&k00N&p1AgicBd(T*_R6M^Kg|RiPJELUz0uqUQb3W?o PhF@Pc0`-m{h653XPeGy7{Nb+9l_r$I@?Pbt zO7r#b%IER~SlGK>qU-koi5vl{_$orU1SZ4z!5tLxmcQpf !m)(fahIco}^G1Aa|>b|EnEc&awv1ddh@XDb+V%Fp#!Q{=JPXUfFYs;y!# z-SP&uZ9*SjCqzj~BC5?w;PT&wg-w0JbK_8w9oXEp2};hwqwPWbIt8~#i969(yfDs& za|S!tbI~@Z*H(Gd)xRq41Kn%~$gnZ>N5_%tT8Mz_T$X#OVxA{1S4k8{b|7aXMLR!~ z0Q)@HRch^O&&Og-L@5#}^F!jfU5Q~+;aT4{y4IB863vM?XiKO}ycwa|76GmRQZ0#Q z=Nhgo6O(d8U6srWZm&nZ#sdv6qUSHXH{V3uESNi3G#ffN)_~({i-Wj^lWBOd3Wb>x z;uz1;=)!fkhH$AQZ%^X0@1iVc^8PzmOXkVI+V(vbmSIr@9q-D*NSRb})+;5cfdp<7 z{Bn^q{S3OCJjZNu3WB`V+-^hiL5e3T5!j-f*rx>7radm3_LoO}(WXIPkuuH?i;nto z;LSs2q>I;ysTWW}9nUN*!J^Q3+w~WZ4Oa5ELg4O`pS!`XJ{Z>WB~i @-T9Zm@qWOll$Wv zMu^$`DCGi!LnjumGz%!;n@NwbHA=ve5F8v>(VlwpEa$#2lv4YI^sYeTq8jyu&VN%- z24C)+ls3#E&$AGomk6`H;~vfFww_uRgugd4d_wSCLY>T)VTKih*$2|QK+;UwNbLqg zTW;D;v>(!9ria7GofJX3iE?}ht>s*byW)m?jRIk46!B8%_~ uj^=&df_#*$0DucOo{|UE?d+5fVNJL7Q)$|eTlf{iyb_DD62V(R-Ttl6VAS5{ z47%O)q5(z^m=L|`neY+|1gQYZAYHdqv%a0@{Xj-_H{0`Gq9G-UTNkockGQLha^l7G z6;rFG_d;_!HR ug$-qp`& zS|MfmjF@FH$;mHa*NR+u29=$A(q;1ipx0Y~nnzH3^M2Gj;cfU@S5jlsC*gTDRuHSZ zclt8)t*PD|Lj%4q=_RlXe%VSu1q$ZmZu)X{4`kRm-UE0TNyX^?G3PBsQP*3jIGc%3 zBn9V6Fm4ls*ongNk-fe$s?b~+`S3!8CQ xUKic|w$NS2 z(};@6=oi8&ZdF~Z=i55XqxbPF`V34$=_lY~eaKSa)1m!87lx 9e!{G~f|+@C($_eu=NUje@@}B2xWuJ-qq &3BIr;DkEo` KCb?^Df`k1Mrq+4xnSSgwH{p_*U zg&Yd}Iwx2e_bIjabHeJn0a7IiC~C<^&_dn`xf;J_%0uLBE(t-rk86t728)98c7xI+ z_}L2meA(~4VYRa=^i8xK#ZRh3`KP#EG zG<@^zkBMCrs4pfin2azcy#XAV`8z|glrMkYXl*M$5O`bajrI=REfr7sWjrnq%_N+) zh7H|qh)a5hT#IX)N Gn0YGNPqG134aw z`yc7}sJP?m&^5-F&-SA_@hHa0^cLt&%}W*1){ RUiQ6p*AGtO4T9TnSyc2A}V+4JGP)1I9dC#zB6K)-LBJO7Z>t` zDXyJvjh$>uTky3tYBI?wch2X6r885yHEN
- -(#r$@c#qqs`(sqtH130000< KMNUMnLSTYW!Bw{a diff --git a/content/doc/go-logo-white.png b/content/doc/go-logo-white.png deleted file mode 100644 index fa29169fabf7a23f9870d38fd913d9bf91f71f94..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 21469 zcmZ5{1yEd1@Mds#Cs>xn3GNPAY;kuDPSD^Q+?~Z87PsIoi@SsbLXhC@@WbKA|L*Fl zuIkmkeN{6(J>6gTeA91Ul&Z2U7CJflyLa!f@7}>HzWx7=iv0FFuj)kp?wv-7 zJV;X0Yx%?&wdSiNA7U4sc)&+`%6|u06jl4#~pao;WaR=@sb}!p%tEE_$v1b65I5cg6qjuKd5B z&pu@!QzO0g-7+HXj)A}rgpU0arJP7ljkJYbw0bZ1Puf}AJADT($97{MYP5fCPl)?| z?S+3p{jpE`Z?p^vGO;oT*n%E}=dEv7TUNn+&aimZ 8jPA zp4y-7F1N3&-@19ZJj0N*pDEZ|dVL%_Rr~^9Wz8DkR{o9ujc2tQSfA{69e8K+`sDpQ zc#9*E;dlCPk_eE}Mj+}dRc}Jiuip|+q i$j2G3G <`3`*O&CF46KEvJ9 z!^7DkmtRh#Y210>cZT861JBxs+70>l=MUeG%F6652f1nzD*uT%KkS2(S6?fFTPP+P zor5<~kO+TyWDYbYGS2qWy7SiA g&%b)K>A zzXJRZncc~`@?Ac6FNo1wQg#|BKtIstHn+u_2SvEd4l7oM50liBYPaQ*N*XO}BLYXZ z55U970GAM~!PeYB)!0PB8BMm&XTK#%pOK6g>uRq3{Z16!us&iX7>tN9{`1`3ccd%R z4<`~t5;$}7=Tt_J5 iJS2TguEc`iS&E- ymF95xKe*3YJ;I^VHev%C(UQYoZ3L_GhG;3>;uAmmyE!!Uu`BS^c#>! zHT+lKop?%rb}`~PIqBb=vrUT6?bF-C|7>dv14YjRWB({7YXZLk6w6U9_4l>M)egtL zmH-fB3U!Z5lnM3Q>M94(&uRh(u2u
- -KkR36gf)}On zL^v&Ds*d#czE_uL!T-3(-jaifLb6vVDrAiqAYZAOhTuvFvGhtZWVA0UzIR?3kN+)p zca?lDZbo8Mh(v`oGLW5fB?+wEioyCNc%FH3%}^!kMaA`$o!gTa 4pvD-5l0g_R?%`z79xd$kZP4iN|o`c&A zhCj_le0>iQRdO@-R$hNs^Ae4^*rz-5p{O~jjL4mzc{4NscwPOWLSr=rNs~GI0qYGl z>;@9-!HJj_hssSE7v|)UrDz&3%l5S!=$8+9NA!S>;KvSxqUOYea1zhvrK^#}b#K4# zUt^g!X(m??!la3X%IIjMs+px%<9Q IrA{3p z1XeeOFB&w4Qp9pG!6>?BZDJG(9F4sGd+(z=`jz{eIV@Bj8gv#n @ H-oKCiKt(8MojMcN)SsivVbx#I~|2Gg7bnM5f# zeVo^n<~If{k!+}KwFmPBzJHVK`LQ&odw`Z1pj9z@+7m5J1c6e$m;go7e_@Piesb@K zyiH^T|E-2Kq5W{ah2Lu<(bHy0{cA_-ZZ!4qXVB$Oa54i*1TmM_8A={Ky?7L1DcJH8 zz2$!9SH0=C7--XT-yhqL`PwVcEC^5ptHEkZ^H5fzXH*h0QAGs1z1Z)8YIYThDkf>P zA^iF4qn<64q^%QJR3(f~QJ)kHKnf7}Mw%grIUw=xGu zT;3?I0eMC5rWRRT A%01{U*majq1ysGyO{(Ued*0Qz6;dcg1t6ug@C zszGxm(vlmMY(_fliwnh=LKcCPRX%u9Ef0s9I&&Pvl2JM~MxRWxA zb1DtS2vSlhLXA$bi0UE3J#cF4%BipQO&Qanx|O>K|I8t}0F8$+>d*+ssHVBn(tm4o zs7E-xL^zX;1DWAy^bFV+CsK7cf^lVtu++lZJE#(Kxwj8u=ibX^DwcRnrLGtadZmCW z34QBRxyr$Tuc^CF7H^o~@Zub5xrBsI)=IibOq4bC9k(ibLmZzehc?&e1X3}&^P})9 zWj9P7SoM~v{9POn)oWp0Ch+EJDt8?%;pAGubsO(?s74)SL3y J5cY5nvv}a07BNC}07Kd9~ib4W6?e>l+LFqt-Latax}6D!UuWVMKM@#SG&?BvYt{ zeF>6$#1yOq$l=#juw5cYeVfyuv<`e(r59RX8Yw|d8DCibd+QzveM`Gz^Wu#^XIECo zHJBysZa; N05NydMWGda82yY>Afs9ctzs+FR2T2yXSo VV!z8)JJ<3ZyKKlZZ$nx#f=Zp<*v@)FOJ`mb)^ z-ood73iJrRg>P~Ns@5{LgmhbAQCO_~z+$$k#?~5tq8fTI2Tr1(=J@o-uPUX6%7R$B zQZbC{7qA0ADTg|lo>$;rf{wDlUYRbQecN6=v_gGFvOP_Irri830S? -SJaFKd4s21W8L+f&Yip_Ys?IK`Uqv{X(L-a|koAMo# |p(1}G@0B)PY0cajIZ|pG{TK|YkTy2}@ju*3=IO|8q=l`0<(an>mScQ1 z0fpyNy{UUv!8!#Z|AnjutNV;r>sx>8UV8FW>F8W} K-nb##OjGF#~^NRWMoK%*w7X&>n zopjdVlJV>Wc?TLIQsA1X-N-0T Z`&m=|Ax?ytBtA Mj0Cn)SipZLPT`xb*9USZ$SS z2O2)FfzjK#>qXtbll)t--<&)NivA%@MK2hm#|ar Ssbl<^P2-&i-!e?vMp z77ElckFpbFa-R6igpT5Zl8HQ{DU+buHkNSsbFbH&1y?Ic5oN)>%)FRK5U~1+b^>Lp zxYeaoiI0gs=w!x4b;}nWuN1U1#!6Uf4twM57h)E+gdcYVNoAsUqFM9~sn5G}4_h`9 z`nQrDBk?0qHNtAEPs`+?q_*5C G3srVz32$7AnBpg^4XGr z1rm?SuIjC)v|+Bg++(}j;sjHq*BPohv9bg7z@Q8;hoTNyev$}1K=ntlr9-YNv9OJe zskk=YR|Nawl?T;0?0-?VNDu|5-nCf3qZWqe;T4Xwsm*n}x31E!8*4Czk3V@pvgXU+ zng&*NTqQp%obMfQ{dsBA2$wKiHf!}EDpBbsPb-~f&ps}o;SH=^^m 0h40Zn-3Q2Bj*0GmF@c&l>-oLATw(U{)|GjC@8k!{2hM zKOTM`qG(*Bgy?0(XqL_K#<03b^~eiClgqn`@Z&L98!#pxJ47aY#q^uT78_Os_)jAR zp36PaMvvu?cR^N8+KRKinibdKgSJ5*+9OKte-WOk82>RFp?J(Jzt%s G!`F6p9ceK@sQRo^SR m&FcDmII52@^)btioJwhU!&zN zY73go7*;SpxpYRBJcW0-feIo?ahydozYOD3kPuaEB ?u_xiv+ zTXq?}`%8R;5lQ3lOfBtDk7ySIO-cnMptks#7z|GR9yYEXepFy@NpYc@EPKh9)Ukj< zSvbdOCXM|`T=dgF1|dD#Ct*z7?7KD?+%5+0yu+a=#_JNbhA|rCy68xkJ)+G^T)@#{ zVNEX_w4l%`Gsp4t3)*2|PIlWGjv*v%V3eCLGRB3)u4~15|0WkJy{QtW`8WA>16Cif z$8-^b4Gv} T zte|-VfqJTnPnK#$J2Tg+XE(o3p+2l#9x^#b;a%Sk3w-_>)<3Y-m`uk@j2ypC(@@Tb zw>ySV%0Gu`7WP(v*+P2Tm?LQ0&&n7V3hy(yru8^~$Tf2nO)22L>nx{8FSx#14Mmg9 z1L`i3%)zxs85UBcp3JWJFP?A83eBY21U@fI6g% 65r*` zXL<2AkF?-NBLi1#C_e^W8f5VJRNzhIo(Tm#Q-BW9c_3 zwvnBboi SJyZ`}2P$Zbakks7u6MpGxw%(6McT#qF7b z(IP`0g5Z9THpjS_^g&!Q!v_Fnio|6E(3=;l)AAuq8piuWu%_V5n4Mn)BAB8fZEM1O zzHfUKk&U8RHE$~nFqf`RMt%0tPc3mq%c;0Ys12qJ#y!I*a?`-f!ha^VT_|PESCeh< zFD(}{yc}JJ_c-G&naQ(1agBG>I;n2QR4D)1PY;oeN0^lto~ga0zM A1oVI^GVu4h6{6q$&1)zJYr>F&RG6;mO5FdR zr~xKNy(+}yzrH%2i_I51Bj-)~A7})(HRJQwtLT(*qM2r9I#(O19hyVssi7Bmby>U0 z+0huOTa~Ji=uyi}`(oYyS=G1z=hko;W^ S4m@ zGDCnh&&Qe6r5-6VKA|&_OAF}!H;i(pbP|!h96erw56gYm-O)K*V(YIH%vUL+Z $Y`y|D*M&PwWIE1;Gg?#Y5(mqgs8*QdkqXAtPJk`EqWJ}c zXSaZkho62X^edsM9Tl0t$xXyMX=I3+AqUUqE&d!Zo;*cD^97^sQZV|Oo4a^K_}@>V zXD5_S^=|T#GAf~U$ 7olZBEn+G4L0oyx^Lp^ishu1_}IeMR#KyS<&EStYrx zz7R+yi~j`uoQBh}^ Jm7@%F0O};?I^#qekFo z@=9<>k pC$dcXdl-W80vL#T1|Bsz4{6ataR~2ToLn3sA z2AtE(-9ju!wfj&Tnu+@3-N#$;)3ZX I7+qfPBOXqk$vEt^OJ<;lsVkomQ=gC7mlD)XsF<{tuvyLxK`LSg z3uD5 f z5K)1?GMFYzpwcVibobq=Vh_&imv+^BBn@hi;@BD7d!>wByAyk*_<;mYk;jFSPa3U^ zA?*6T)uy)kN#@Y}SPVEwiKlunJO=M2Up4p0e l617 z{j*PlsBVcS%@Q0tQsMV2q*0BVUD9uX=eZmdPs(>^fDv_>5~)U4teW;8O+kYMlU04g zH4hL?X{~z{bv$u%8nF`BOrLS6v)KNXPBx$8AT;4Sw<9uyDJh=`-EY--x2R5cfWtVA zVy-9@T7v`+_x*k4YXz4!$5E`T;A9DN1<2{TvAQ)J-{*rDYJ(fEH+xh0S0<*Ex~Lg{ zcz3mmkLjKQrA>k`vmxCU8K))s%k)}mVQ?QuZ2GEYk;{J%dq9tD3|6*`Qjz{Wl9lEF z1~YsMTcD+xQ(`IB0`%nz|3c%gcJ~r|0{s~XtcJgq4Tv3=-~M<}<$Lk@cTy2w-?PYE zPMega0F=W>oXX$nEo9KQQOAaEc>6ItGulE-%+$y?K2uP;@J??EL~T@!)FZ~c&kDF5 zmeAt)w*KYPzqM~1g+Za5&E*t7yVLW*2VZ_I-BYNyh`_C= UAf6X$>OA3c+fysy5O5ypvK74tkW1O=vJ%q2Gh12CPdF%b4 zgT>lgV!h3;CQLXs5%$Tl>s=E|DGJWwE`9d!Dg5aTw=^>EM9o6#v 5Ky09e#hJu8faUK*W?)duypE^@f@Q_))#Iu8-b6b`^H026qQmrylS6ft zfdKC2uC2*7(4tMa>9{;yO0Q2c|GMn?J;;KI*YDfhbF=w=*&Crzsgx!mH}+XIx~-?p zDU5AV)xS^#$zjb;UN=iwR75vu6a83c5#hOS_8XD{$q$wn&|T2%kt9QtNJb5;e%#wV z6E!RZNkuPmrAKE}J8ip=Z-^bPamoO^e#HjH?_f&i@0iZA?Xel1ef+mkz56v}3gqHJ zC!nvARRpUtf#C$r>tykut$@@l#yL+CwB@!x6lY3LqNF~;=#WCb2D4haOgOC$Uyr>W zyFeu)@``3rjdP0+jki*jXwzuN?S!{7BbR{q6GdhhI%sBu=AwiVmmU}9)^3=VH*GC= z4soq0DLlNk$YR(?!q8{5h)28J5YIa<+RH&oZ#hJS_N7rZ`@gc3lnR2{kmFpb9!NP$ z?KdWOXQtBw;=3e2k8D*zg8K|rtz1U?gZ!g|-03>Tp&M9l>i&HpIn(Sq&w$m83w*d4 zK2Sl5gqb8(f{?xtyQT=#qJD53`S<)&4Jr~-3`!n(fnK>~n|dF0INYh^DHxt9;BK6< zlsUWqQ=UeyXA;W5wxc@trap$%1nLtj+P?U6U;xw(!MJ;;ZzWgS3b)jYy@;UJw-w2_ z>oqT2lR+(-rQdlKE0qzYmwdP?DK8}O2U_neX-2tA4ond|s|e*}OKI-<1b*JAqniU$ zGRd?d JIM0Po-%DMAgiAy`M*1Wh!w!@P_HzbL__%-xjnHKQ|();p>I*Q4tfzKQw zu$u?qt(NQ|_PTH}X?}m@0Xn7aYIiRR-ZtxLF8LQWbjYAM2t~x;U_TET$wfq15_Er` z5oX?*M1m`xFa9+TYXG<_e!)s#XlxkDUyd ;em2bBT5;}BW9YT%6ndZ5t+W>E*=|FpJ{Mx zPNex}rLIO(=LwpptkK030Va&& v-6#)_bmzz zYqg l*82eC(BKqh#uCFK`8clC@ijr-My!|P z3hu8&RQ)R)fh6RWzW31-^$dZvo)*@o&4EGUtu($L(Oms**!7IK)}%x`5I^a=e9y-j zH(@q(K}#)A9AN*+vFHbTGDJw(OVZbTUo0k2k9YJyyTjrR@U0Lg{c=FLBnX@S&B5|< z+rXLaJ21kyZbOYQe0{%-Hq5KgwIz!r<9&7nbEE?H{I3f!V+lRV;yJRWIn@AOsH0Zl zF+HB@y$91t5PK8G7d#dRv1rr)Be`};rHojeHM0UjaUQv30O){5gE3bzu@-B O%%N`b=P>fPLHk)oz_GNnprjo=2aw_x7koM9E$mQ`bosc(-5bYM% z;-l_MpJ&!$*@^6Ckxy-1L=dNOlBs`ML2Do+o7BLaDg^M>WA3Z3^p2~u6P5;%%h=6= z)TCuER%sLRT+_|F7N+K+q heR3%Cc0_;Biz%N3kmzJgbtD37e0qPQN30h*w8{ zhw}%rYoGmXjsX1Eb~UxFwOPk$mNnYy#&7n39_(i=SWiOhUOR$h9eAUOpN}ZGDKYX( zv_p-b&^N=i{$dm$kxH=0iIrvWB&*w|a}jthhs`$RV8PYfb!8=EF}o4&O_#q2Kf;kk zHn!0+_Q@kIf_6wU%aP=G6eUS@%E%_=oY2MIr>aKmk~ XzXmb+YXJWmIg5yD$-l2G3ap2J#;Pe;h7sRrI zue9021jFq8F{^2rwhqd)r$tJiaQQPfJ=AMV?^2Dd%8LGRO|N`Zm(Ln{WHqxKv!>CV zVIqjnIiytDVI@$IENb4JZ$C`SN+o*I6<$Ca=P#o%;7hoJTf;D>CZ-w<$d|;UwBXJZ zV%W&mFOS&+Y+|TteWiTnMg0MM0{`hhdPp=8%WnRvVywD#W<6PfCK7-VmtC=7IV@Jl z3|7xR|L+Unq>E2(o?g>Xy7CY$xGCj6z~W~F@l{wBL-O4#A9-aqQ!(01;A@KfHIAQ( zQ8|laX&ghEIL07ydHwhs6XDk53Q#l>;4qr8SkP>KmTp>;wK|4)m>tkWb g z5r-AL*=-s?rjryki%1XucGHMVV-7WM*jK)P7$Jn(6CkJM6_GlQKXq3rmGo!m_6<}J z)0e-ZOQtQl?BfX}F4dJb^X2`Ved;2}{n$13f3e2!od#vW$|gZ2EIXX!!YQe?>m1W! z$DIW~a}4+vL+0S4mdy &oVBtD-Me!?`HfKb{$VhYHBRi;aAw2 ZA YDD z_ouzpoz*kC@5WgD^%ulJYax*t7H7%SOX)OQp;uAUjM4|&iQ{hOdB4@*Z`1@n Qgd-rtZww-a{d#yEH$ROc8HsTDpxh^-OGR83PIMk1%ua_m6X!BkN7-r zKy-wgtaBNhJ!K$TV}gwcjp$MTIusdiJZN46$G8>KqXt%{$+YB9q*%1ZYrB;`nhbVx zbhj|`aa#x6nm~nSrFeeqGRDOB0G2oOB%>ymA$(epanEcTEQNxXFTrjX!R6yF2D4;~ z>UqR?d4l*AWH!o%#Pm+?)ooAVtDd t-(uK@nfxG8O(tqz3yUE#V HqZQM0m2gau6(s z DCeLXWXCbJFbJr=V;{SfLs9!Uz*bD_D5+} z0g`%mXz{27V%Nm#tz2Ul8Ow*)KlfHY80THAb?*7A3wt}d^*huver|ZgMUoA;aVgmw z2mj`sbL`H$dqiLB2MxLiGb+hIZ^C3k|Ds|Xr!FJ#qUG~j3+*!Br^!gB)l;Mo`WjV? z0V!iG^vbUny`LY;2qW4RXboE{S297i*o!@6jc{>$dWs!1jW$IQu=#Tms7yumjdu(w zMCOkZ7SK}5{7-0g@8!0G*SG8w@r`B*{};PZCdMSQ3M)LQ-A=9~L&`Jnu5ZGaAwZ`Hk zCG?=<-3MD1teY^%HiS=kg{ybAu}Yo!1y&ezp3@d-y&EP4Kmjnxd%dq3 ShZt% zYE(E~Eia<89#CIPS~hgW+n&jU1Xpo*g&6+Ozol~ehskpjXr>@UUa9qM3*1T0YhsHP zKG33n<#ZyYfnaeIH3xV9jj*O9(u_E2fXYbb@n>8djaL#$J%$`?9d5S%E?10LqK$q| zttDy>Q}n2P@lOU90^DOAI6Bw6{1F3OGX05#I;%nr{mm2`LGremsikL8c1&c@O z f+?-1+dlT%FjTq_m-0wiu%+Jh%x!XXMwI2LsP<;b=cd zDkam0k*y1A$yT-}H`k0df}(P@MBY6}(XUNl;oLDrjx4>GA7FuO_B@M)Y_%j>M`}TR zaNmtVUli@;!Dk9_x 7x~{I@xw98lTb86b6(l5`GD@f+`1u%WW@#z9RVetjnU``= zGZGdSom@=oxE}htDFpE5ChH-1&a38d30P)^nZE{L@z-}1I+VZIl{?^Am=|0bGS=hD z|4>})XT~4X(ph0d{c&TDK`{{pj<3XUCZLm#2YEf-L!7H!yo7b!=+Q%rLgrmQ^sXqX zAsS!VFmOa347FV;5&~N0^OF)7`MX4Gt`Aqvk)(%D71zE&wxzr7U(lQgh0hge91M6H z0M{w%k8&@e#)-7_(t49Dljg-qq2ss}UGk~3wXe5k6@qe?wOB~u1l`;ai|~9+VhL#f zCB=hOa)yJBnFe1nnkR5ZK2ZB(zh1oDVdP)4pQeRzMPPJxbK0C>uL#P^WO_Ap7&4WJ z4#s`6s|4%Zr^as=UZAVCeCxov_r~km%w^hh4((CCb%}GYFg(7qfC7eO8`@q~eD2X{ zL;+@i+qI{jTikg(Kavpx>ApZYN|NxbVg{A8Ke~vtXhlzz4TiDphQhT3Yrk&15hFUY zDlfAWNzzR6Xs4?nql1zp!^#?}+lm}Sm(c8?7T;EtN(0FE$=6RCOz~P>*YgXMGeF~4 zoU@S{%B6 1HI%uUKW4PW32nFupTEk9scq=}K&ea8s14Uz7!cc%+Lz&p^-BV&xitpD_? zRfqMYJkHXR^qu^ qtNNc!uW zS6D=E_0M5x;hqp;64arDqFwnTZ&Yl;?Ha1dEzs#keyhUlyr=9|kZgA^*h)ZK;|3No za9U&vQ+%i3|C^E7>T5a>WGp9LnGclu6GbMg7*Fi=*QHN;k;^5EkW8h3;^IamIx;FO zIqRz5^e3~7 L;N+Va%FvfiAfLz)rmsL zjYGb)Nh6Y1@| ERF8Q{YladlmK01nH$JZ8X{>bw}!{tU8(`T^QbKq<-Q{k?M#>V$mp5?~p`V#(olO z4LI|VNcM^t-xB9jryuT14{NLjOI)^mBP@!j5GHSzdOZ`a#1+U^347GWv;DSs (&zfr6)N|*fHZ?ADK%?jU>CHH#tK-QcuBa=Hnq%z(|CM z*aE|xvi{gBE|c`qNzh5Zf2uT)ILnDT-j>wlCNUUAlbybH1{m@c1=q8@0$-y^;OBct zK@DCODIV0d;PMM#LNQ55bJpkLn9K$xCj?9HdX0efa8*xS)t+z)W9IbeACXkz%PcbG z!n;k&uT~v@AWbzz0cc}X3rkN{Riz5VFRlbjLe6wQ6z$E@m L-Jww;gV!)>N}rZ zSdoidcchWJiJ$-dafg>kdl8@@cusAedHg9`7 V_r_ E_N)raP2HMMHJ;G2JIBcmRiKJXvrRg2^CRs>hH5bIh)s!ZI zFiy`a{V8^C=5uUR1xVEcAPdDi>sx$JFaDX|l=_KEml;fmmK1zyt0|_fn*PfZUAcrq zpB{$cKF_AfInG0!_=!nS{9}s#&)%)Lulp$K4K3set`m-H96eG<(6q-qSK|eHd^3j_ zuX5H@4x>Q?UxJgH9GPxP%<8U1!)}y=PB|Jb$PZ1-2!Mxu0qYE4! Cmi+CGGl}cE%y>TcZEB0YGT+zB88&A zY74HTgUZ=<6&_L6hf#$|LN@& {1>BOQ)L?sI=!-}mC zYGNiiAMr!PRr1_CYlCC)Vk(C?iz5L3l}q?9#flLOrq7Juw-7u^xyD%WpIrK B;*7Y`xA41re{q8U8f?P#JFT-y{q~89Y|2WBx;kn}IkZBCarN=?lrJGh*6EF{ zlR(NmxhSum+Q_C}oV*-SI(k#~!v{)Z!_>P3g-na>`)RE(Q)coXR&TwQpBaU0WjIOD zCxlrb_zk0G@{(m`S)wf{lm)Uob+koa+1r2+P&>Q=F1IL+V3T{1x5W=CoM9QQ@?!Nd z&=#(Y-8$8&s=LrKQ5DZ+vHEU9AVvM36Mjsne+U@HSX(SLlA#r8Aob}YAh*6>wmh0L zuBZQNFVg#TDN8^e>xT)Kx>|C0yj{J7sz~fnNsg1ZYNm9?tt nL?C>~~gRU|~ zr=1Y}$hS(<$J7U5jR 2=r#eJ z#!AXig<0XfSLC_=2~P5gwH+|)HZTI)$s93(JR*$Q`qpaZ1Ow^Mw8goybB>2 E^OVvCvvDt^+P*Ahy8 z1BlPDSv=vFOWt6Jf@IM(h-Ahgsg!Klbm-6T4`$>MMdF)G3uAlKcL~_+xTU`t4w8mN zz0?Z(uF7mQoPWvk5KR ;PJuKjPSaO2Nn7F~74DK2-J)tjHP)>6D(qM;((U3d5FXdj}-DSC|vti<{I& zdkk-$2_?2Zc5~i{>T`_Z3ai1hmnqJ`NNY3;wC>P|A0DK@YH09E#oKm#{EH!%i)3|k zbG>hwO6L8^n)NuFq$^L7KF`VPv{;T!kb$Qt$5-IG>f6^h`GQI6KM4d64}>I}D>~D^ zG@%k?OlTFkiH_zm`--sCcJj7ehC#OEL-Sl;NGkDcUj>B9EH6(--PUvF(DtlKx#k;= zlEkBVYBa?R16;c%5pYdcLh02rtfLo4ohSL`NRx+nzi+z5wHju`jfk=XiYwnLxTN$x zg}LHu68jkHRtI6h`^g+=G6-pc8j(uvddKPw=Zy8Y1*lw2lubiUD0zjAmJKtNa$QRW z(J4_)nA< `otnt+IXnOpFPEdzb(ZAev42eS~^-d?kNq? zp?CW?x=w+Ntc4lTDCjuw)I`6YkkBZW`*_qGp-hipT112xwo156F8ofHknis57d#oA zu20tQj<&ud4jpZ{Wz~o{Utq2xA5KWoJlrHRi}*DFTU47eVZs%`O!?t`FFAm~t58g# z9UNa>zN3>_Z?7txP`bAM!`nkfdRe9EDgEymI+JaTYS`t=nZyJHY!JiIp71#0t*@9y zpZxb??`DB%p!6YzW^*ce*^^ytfo$Xlg4bL;evd){n^8QB!K4dwF@=2Wmda#=I|;&V zVM`b01H4?OE !GHQ9#gU%!(^DH1NZj&!#69s^;5~7u%-Yvra0QpNh>!wyG4+6%*;zDXh$V@(zaC zgP%$YuC;=nQs+lWn2X#>@$*^>D6|n$+zTD+00ADW;@DFnSqUBrp7H9G97q{6(m2d2 z2_I)*+tWt=IhbN ;ffRQW1KIp|eA(rnE-zvB zia0ahrC#Wy1-wHs#dW?DM$GK)ln=~tY}XPJSLb=$tnjv=JIyj59#a%#kV9*`jtVns zbclg+kcGRmR+$6VtgpmOpql*ex#!ds#FwIsTQ!fp-0{hBelHSiqwjwuJ(P7>hNxl) z+YRUhMG@dOV8{I`fxqchBYxa@tS-i<-#agNU6C2|TM60dkTv;Z@`aCrQb+UC_iJ@> z`Ge4| zi}lm+pno*i7@ 2IE58#iPst>A_ir3bLXq`uSWS3tazf>?3t zBe9d&%My3?J2*eZ#=0@eRTui+;J&EMLrjClyfrY#Y>A2Y9Qo%tpv$6oAG}>%!LjgT zcr<$~ncVKJMCe*}TFWv=Ui9^`(&DNBGvWe{2&`MpR$;AM_4Z!i(m=)Tz`c=crJiX> zAWr&@fg7@g&ossYSu#=L)SP1{$XOqC{f-7J8L!p>@CL&KGFi#2*{5Az1=#H!?xHRw zS=^3}-d>WyL-u2n-O@l1f_zzmV~k96HGDS7_z~78VS; d>*5N#4PCepjD z%O~>~g=i%W_8p0C3EeV7P!&l9vTbaW;#p|D1R}F!o-=UIlZLjjl56?^dY&n7H&87< ziM`tBYyURP?9ebN6=pkEW&=>ON3C?QiWG&_qO6rGr{?ZhXS?Vd>65<{1NE K?^aZnbpMZ?%z&_DWY}BuQXA(3A(;N^t^YCA2%pc8~~M*)J;hC6;ach$Y#iJ z(Y2Z*jI+^~vT#*T|Hh~Shp2vVEskmaDcOlsSkRS}5k_*JmKo&r`aObR!b#8VW|NyF zUvRx= s_e;7bE zM#cGOVeL__p7;UdJ_W2(un~Ue=m*L}bsRAk=`=fu^E)y~(Hx742iyJKG>oMa*@B<9 z;e G_?T7k(W@Xn zeL{sDzH+-hCa70RQ2jHfX5yAor`bB4iE z=D3TZ=e=3>sw3Nj)9X-Q5Zzs{V#oDTZ!p3PHXHAl6n6T(DTc_4rJ_j2jn&^D$32-K zb$vltrh5wII{l!S9>QaVo$|()ls@h-<$G1+_eQRcu*#T$=*r>#I6JN8K1;y!?BTnQ zpAp6;Y$S9tc3tFJMT>s(`7>uuhGn!Cnw7=)+lvqjZk2_Aexv`0G0lt~2O}Aq$3MTH zIkn^zV|_reHzhi5X)H0|WDWN2_XU|kUH?_|GuSXdK~rk$4$1P593TZ}vAI>Qn?FG2 zFwbl*Z$CIM#QRIdg?EXfOAPxo>iaNGZy;b!!#M|lR<=-7*JJCb>e^u{f;l~`VRfv4 zi)1=~rF*NTQdrCKalhv8Jm_`>2I|!U1hlv?N+K`O+31s240XY`>q;wr5+zlQldKEL znDV?YI(pZc&`N_~S1f3g9Z7yb#o7M?v^} rx>`KiqMg2gs-rE!QVd^x2cHe_!$h1?bKl za1H=aC7!JFDApCFcGT(06jYNRE{uMu@n_mhoZ*1272kDwQn*|c-KwIjMS<6%KW6Zb z20^2q6kIiM %Y%OlQ(##*-v@pWeMwJrKb^kMWjM;B_H~dOGZeI=`#*6Md z%3BK2iPFC71Vo(m3G|qkYu3i;U>V{jBhb_*7XO@J(?wwFAT$2_Vx# U zb&x5d-BcOsJmpDmna8nWtb|_2%3Z_lels6o?vmct3d@)9rNP8iMY?GDFfEzIeF7(# z=A+mHDG8^H1yT6DA8gx5wc>ty3q^i=-%K5@({AZZqVzS8YdzpGr}-DcT#fKtWDT%k zxFNDx9+c$)zECb s={XATXWj;w Ti3(> z+#@J3fo^1@m8f*Topst$MgBmtw_+?KeZ4ITlx@|Ktmf8R5iMb2f(pH^~-CKkeM0U3qmBj1?11(T8awLk1ct85Q0~ zsJ{$y #=eCtMI<|89WrHP--jqm3z2nf*|H?czDuYG zCH^!2-}Bt(x#vFj+;g6LmiN5(-1qa1y__@ca(PLbKkeo6CuX~=DlbIHS|58PHM`Y$ z&ZMpzlmvT6(sd*)u_tLidJU8FG j3bqweJv= 80zMe?e?F5B8&WGI|n-7zObMa4uyFx3tg%lqD5Nt7IE4^JF z4G;zp7Wj#z^NjR6 8RenRy@4;z4jyw`e_#GxwVm_I^C!9}4p7)k9!7r#C9AqBT<~w&& zCw6{`hybQRr+7gP??eeB9Zpf<8-f}MG51Rq_!d?K4I8(Hz4dJJ^B-=DP^?f#cS_(Z zN$cJN;DkC1mq($JH%HSNP^t4vz4P($;Ds PsKTDPq9wA zBV1-DH_lTws#S0q8a`)#NX*zRw&*Wg#J#c+&+$L!V09{#sM@jv?=o~=aO!mO(~>)P z+zfYlm3zq`{lX&91
- -zS+U%;bA#xrOi0}}p4@R8`j9fGiK!Vylzqnrs!JxaK)? v}TT7O6(JBD1Y2vmi1{ur4wj@Ene?l&63cmHYoqa%&6q=j $#WE z&J?u4mRZX|gtOmsZNApfLZ7}={E>A>pzF5nHx1D)hJlXahS5WQnHQFu-pgqkKu5MB z`jN2-2O~fGXUV?rLPT8-JOqZDr SV{2sJ|>;B5QK)nmH&YXNv)2zXK0pi#M z90#wI+PSCQwYFUeMWWbVN>Eg3&p4{b67)?m51n FbWuDPvpT>8y9!nAQ+%g @hsHCwNj4th0yYUYHP;pkL5v(TPyS!7 zBq)(}tv~0i>rjEd6To$4)$!;H)Vx5hmKwdF^c5*0AT#_O&Oc@9A}nDP-?a#%6OPW} zTOolW4^um~TDU!Cr60KiDkoN|=#Z41na-W7=}NCrEOKZ>8`93-nq6=<>W6%oy&LLr z+>Rv!jZX5lz_@=D)P1@53DWp7jm)eX#b0OC$vOVLHA`8784+K~lWm#5uC>JeQX;t( zYO^7VxvSFkw`yo#Ds33j-RxabsgR!K4*5|&_Y5*qn5_c9fjqXDAKfXev-KD_aN;uw zqPU3J-fYe2gix!qN7!}v+k#i--37KJS8*oXI96b@!v?`?Alkfp2Vv(!IySoc+u2uO z_2U6{!zx8*<%qZ!07vRUZ%V&P|FSdH893?Prq|=h`H`*Oz(Ew^%R($C+8akDp+08O z*PjiKJbe@I ;b z7$EjfPQ1bgODKhQ-`-;C@h$hCHR$hYgU6-SeLgwT@~gS!m1%V8=OCi2{H9ctEH)%i zA`N4Pa4*X|(n#R4LeSG^l!C85K#!f%ha2yPW=qhpJuw_+Y|V?nN8Mc%kZqeK*1(_0 zUEgrJf+Aj7KfeU8uiPpbFSX Z(IU-?L*xuJZ= z!P?pHOJmyEvQSU56v$|)oOi`^tOpU=c4>n#r*ovaUy(ID?5ZiQWwl3wM%GoRSgRmV zh4+^vgQ#m_cE=iN8tC@NrG=pH9H-W0jrhyn(?>`u-XV|7x}r#IQ3Dd6 Sl!?;3D{=l#fPd*E4Ytz^ zm7}^!oz}6Z1IFgpZzM-;z%M{b^mZ3p@n`GxPk;kn5AJoSbnMqM>%@32>9~BzUF3hj zt)Rh}2)O@#zeEKGSuwV+0#BcMp?ro?yxtLRa(;OD&&P>6wY$BzCEyUhGalT 8Ki%WDl`-G)(PJJ5^{Pm?Mbg zU3= #Ko-%+@jV)JlGi=wVBd#HNvWg91iIZy{8$u(Xwxj|{ljpK`Y8IZ9@J zzww@Nu2S9gpG8L8Y?IDgc86JS-+7m+{Yyb+8WXS~si$3Nsr6j*?!Tbmq0RPW#CG1Z z$TMc%pVevnaI^wP=6v%US>e0$&+pP{Wp4S%0%u!LVTK*5NYEW9#96Bgp!}M(y11aL zlC-xC?WOX6`ROe-@_vJR%lE$^A}&2EcH0G9Oz#`lnq*=%mmgSEu0Z1b+Y%LmeT#%| zMh7I2kQKK3D)B>?Xds|E*yL@o!}+GgO^#nHYLE|h23of-6|&K>h8C)@JL-KF^Ut$b z9h<1alDja`+i$>S XuSvK{^BYYv=FF- SK5en7Iz9d8e z&g|D(6C_t?*33-gY3yhd@qQ_v ZfYUEl zlq< XxpDRW?p4$~L$Qz)Wqzbr3e13+bt z<1QNVn1-d*1^wnJA@A=@*``FM!nh&ZW#4o+OjFvmu@&?)7S9CI(H`SW*-7b{90;Y; z>=6emv}48 L+f1UG7XcL z`XEzXm-JJsR !oq3|{JtSJnz<9|@4dSN{eYCXLSwM_m|_67eK zAN5;*pPX4aa}HW?IubnyG^n>)AJ&5SDe$mg0Nw7ai=Wd(4_K(Wa#sT)hIxzrX@=ckT^$ zvfh@#O;^CGN83J8MWK*0J|t!=x1E_m+dYg>B{R&HZ0;Fl`m#Ll+yQnnbKPJ|JJ&*a z$ 99Q$&uv66^!j!X46eNLa)eMXSsJ&IB(z;2E O}f#Uk3lMD(c}^d%iXx@#bf`Q zt5Ay`DEk7@b?g#~pqBnw%RGK{#csHY+UIvOEb#2bsZC?93;Y_-at2&T{|ffsvHomG z%&_D2uNdgkJw7okdB~5-kW@Ouxl<`~p(0c3>C5?S62rx5#Mc`aeW{_=;wzC$Z6ku= zzmd37e3Q^=S?ynA5Y>{DV Wln)`&&o_57z!X1635{xCsLcPMg@R7 )3g5SF#P)CB|gQ?2(3>)`MQ}BKzp)oY1JV%D+280sJQschfD^SY4XpDZJ z+TX3Q*`$dKSY_bVQdSPqb5Tlpu^VnFW}Kz4jTShIa|B4AoamHzlvqc4p)!`>&9EGC z6`uf&dzYdH>{65uKZaeSd7|%t?Wy)zbq^n=5I&T28;uK%mxD4_UeB-jr0lIDH~Hln z*vN)>3uc+YYQmAq<(Z>#)v+XYc{vAvu1$7=%KpQG#w?0}6RnPg`bJSs&V(BG>wV z=_pHLjLygsyR4_+T5>KZbLdv(*e7?kIfQ<0Hba>XI}e$4%d2lWi4+OJN&7U^1>W+Y zuIlggvQ* IF^>Dw0r=ygRx za#LL+_!OJ@4Tp7J7_a1fJ4oIOKY8#ZjNz+E!4=H<15dE_zW+tDk6_+5#9G=Z^?M_| zX6)nIC~Y9)DV&-)df89aSckcu`5P5no@kp3bgk1`yHtDh1|<|4>r;uKuat6h*WK_U zmZvILLF$Ui7hbdJUP<1)TLhTZ5kwY8OVJuqAH_Bjt<>gN#%vC3C*&(8RH6A{927eP zIL4Ero#b_}sXQ-oG!6ETWxOl5aS;uY7V<9IQKZ6poeJUi(0_kPF c*;Hlka}bbhl# z2CRd|Bt4RnFVg9GZ1z!{C-0whOLUF(!V*iS{8n-{!mzfdjxfBplm0^}f!N|gTT}yN zyc?E8D`cWd;=Ua4a8y$;Q}iWX!0s(@7|bA95Bi0DIdnlrx{8aMnQG}_A)5%&GSYU} zY+%~Di@F+R7DckJ93H^P`p3Rfhq;o_sVrey_s9KMiot8 W2M`j0 zHU4)YY3v&RUn(Bar%!XasK tYxAj{+b&bX_5hC5efsNN?vcd<#< o1EzUe%f;cS3S)yV^QTM!6vcp$@q{(1Z08w6T~kDj&h4oG0Z4MiwEzGB diff --git a/content/doc/go1.1.html b/content/doc/go1.1.html deleted file mode 100644 index f615c97e..00000000 --- a/content/doc/go1.1.html +++ /dev/null @@ -1,1099 +0,0 @@ - - - Introduction to Go 1.1
- --The release of Go version 1 (Go 1 or Go 1.0 for short) -in March of 2012 introduced a new period -of stability in the Go language and libraries. -That stability has helped nourish a growing community of Go users -and systems around the world. -Several "point" releases since -then—1.0.1, 1.0.2, and 1.0.3—have been issued. -These point releases fixed known bugs but made -no non-critical changes to the implementation. -
- --This new release, Go 1.1, keeps the promise -of compatibility but adds a couple of significant -(backwards-compatible, of course) language changes, has a long list -of (again, compatible) library changes, and -includes major work on the implementation of the compilers, -libraries, and run-time. -The focus is on performance. -Benchmarking is an inexact science at best, but we see significant, -sometimes dramatic speedups for many of our test programs. -We trust that many of our users' programs will also see improvements -just by updating their Go installation and recompiling. -
- --This document summarizes the changes between Go 1 and Go 1.1. -Very little if any code will need modification to run with Go 1.1, -although a couple of rare error cases surface with this release -and need to be addressed if they arise. -Details appear below; see the discussion of -64-bit ints and Unicode literals -in particular. -
- -Changes to the language
- --The Go compatibility document promises -that programs written to the Go 1 language specification will continue to operate, -and those promises are maintained. -In the interest of firming up the specification, though, there are -details about some error cases that have been clarified. -There are also some new language features. -
- -Integer division by zero
- --In Go 1, integer division by a constant zero produced a run-time panic: -
- --func f(x int) int { - return x/0 -} -- --In Go 1.1, an integer division by constant zero is not a legal program, so it is a compile-time error. -
- -Surrogates in Unicode literals
- --The definition of string and rune literals has been refined to exclude surrogate halves from the -set of valid Unicode code points. -See the Unicode section for more information. -
- -Method values
- --Go 1.1 now implements -method values, -which are functions that have been bound to a specific receiver value. -For instance, given a -
- -Writer
-valuew
, -the expression -w.Write
, -a method value, is a function that will always write tow
; it is equivalent to -a function literal closing overw
: --func (p []byte) (n int, err error) { - return w.Write(p) -} -- --Method values are distinct from method expressions, which generate functions -from methods of a given type; the method expression
- -(*bufio.Writer).Write
-is equivalent to a function with an extra first argument, a receiver of type -(*bufio.Writer)
: --func (w *bufio.Writer, p []byte) (n int, err error) { - return w.Write(p) -} -- --Updating: No existing code is affected; the change is strictly backward-compatible. -
- -Return requirements
- --Before Go 1.1, a function that returned a value needed an explicit "return" -or call to
- -panic
at -the end of the function; this was a simple way to make the programmer -be explicit about the meaning of the function. But there are many cases -where a final "return" is clearly unnecessary, such as a function with -only an infinite "for" loop. --In Go 1.1, the rule about final "return" statements is more permissive. -It introduces the concept of a -terminating statement, -a statement that is guaranteed to be the last one a function executes. -Examples include -"for" loops with no condition and "if-else" -statements in which each half ends in a "return". -If the final statement of a function can be shown syntactically to -be a terminating statement, no final "return" statement is needed. -
- --Note that the rule is purely syntactic: it pays no attention to the values in the -code and therefore requires no complex analysis. -
- --Updating: The change is backward-compatible, but existing code -with superfluous "return" statements and calls to
- -panic
may -be simplified manually. -Such code can be identified bygo vet
. -Changes to the implementations and tools
- -Status of gccgo
- --The GCC release schedule does not coincide with the Go release schedule, so some skew is inevitable in -
- -gccgo
's releases. -The 4.8.0 version of GCC shipped in March, 2013 and includes a nearly-Go 1.1 version ofgccgo
. -Its library is a little behind the release, but the biggest difference is that method values are not implemented. -Sometime around July 2013, we expect 4.8.2 of GCC to ship with agccgo
-providing a complete Go 1.1 implementation. -Command-line flag parsing
- --In the gc toolchain, the compilers and linkers now use the -same command-line flag parsing rules as the Go flag package, a departure -from the traditional Unix flag parsing. This may affect scripts that invoke -the tool directly. -For example, -
- -go tool 6c -Fw -Dfoo
must now be written -go tool 6c -F -w -D foo
. -Size of int on 64-bit platforms
- --The language allows the implementation to choose whether the
- -int
type and -uint
types are 32 or 64 bits. Previous Go implementations madeint
-anduint
32 bits on all systems. Both the gc and gccgo implementations -now make -int
anduint
64 bits on 64-bit platforms such as AMD64/x86-64. -Among other things, this enables the allocation of slices with -more than 2 billion elements on 64-bit platforms. --Updating: -Most programs will be unaffected by this change. -Because Go does not allow implicit conversions between distinct -numeric types, -no programs will stop compiling due to this change. -However, programs that contain implicit assumptions -that
- -int
is only 32 bits may change behavior. -For example, this code prints a positive number on 64-bit systems and -a negative one on 32-bit systems: --x := ^uint32(0) // x is 0xffffffff -i := int(x) // i is -1 on 32-bit systems, 0xffffffff on 64-bit -fmt.Println(i) -- -Portable code intending 32-bit sign extension (yielding
- --1
on all systems) -would instead say: --i := int(int32(x)) -- -Heap size on 64-bit architectures
- --On 64-bit architectures, the maximum heap size has been enlarged substantially, -from a few gigabytes to several tens of gigabytes. -(The exact details depend on the system and may change.) -
- --On 32-bit architectures, the heap size has not changed. -
- --Updating: -This change should have no effect on existing programs beyond allowing them -to run with larger heaps. -
- -Unicode
- --To make it possible to represent code points greater than 65535 in UTF-16, -Unicode defines surrogate halves, -a range of code points to be used only in the assembly of large values, and only in UTF-16. -The code points in that surrogate range are illegal for any other purpose. -In Go 1.1, this constraint is honored by the compiler, libraries, and run-time: -a surrogate half is illegal as a rune value, when encoded as UTF-8, or when -encoded in isolation as UTF-16. -When encountered, for example in converting from a rune to UTF-8, it is -treated as an encoding error and will yield the replacement rune, -
- -utf8.RuneError
, -U+FFFD. --This program, -
- --import "fmt" - -func main() { - fmt.Printf("%+q\n", string(0xD800)) -} -- --printed
- -"\ud800"
in Go 1.0, but prints"\ufffd"
in Go 1.1. --Surrogate-half Unicode values are now illegal in rune and string constants, so constants such as -
- -'\ud800'
and"\ud800"
are now rejected by the compilers. -When written explicitly as UTF-8 encoded bytes, -such strings can still be created, as in"\xed\xa0\x80"
. -However, when such a string is decoded as a sequence of runes, as in a range loop, it will yield onlyutf8.RuneError
-values. --The Unicode byte order mark U+FEFF, encoded in UTF-8, is now permitted as the first -character of a Go source file. -Even though its appearance in the byte-order-free UTF-8 encoding is clearly unnecessary, -some editors add the mark as a kind of "magic number" identifying a UTF-8 encoded file. -
- --Updating: -Most programs will be unaffected by the surrogate change. -Programs that depend on the old behavior should be modified to avoid the issue. -The byte-order-mark change is strictly backward-compatible. -
- -Race detector
- --A major addition to the tools is a race detector, a way to -find bugs in programs caused by concurrent access of the same -variable, where at least one of the accesses is a write. -This new facility is built into the
- -go
tool. -For now, it is only available on Linux, Mac OS X, and Windows systems with -64-bit x86 processors. -To enable it, set the-race
flag when building or testing your program -(for instance,go test -race
). -The race detector is documented in a separate article. -The gc assemblers
- --Due to the change of the
- -int
to 64 bits and -a new internal representation of functions, -the arrangement of function arguments on the stack has changed in the gc toolchain. -Functions written in assembly will need to be revised at least -to adjust frame pointer offsets. --Updating: -The
- -go vet
command now checks that functions implemented in assembly -match the Go function prototypes they implement. -Changes to the go command
- --The
- -go
command has acquired several -changes intended to improve the experience for new Go users. --First, when compiling, testing, or running Go code, the
- -go
command will now give more detailed error messages, -including a list of paths searched, when a package cannot be located. --$ go build foo/quxx -can't load package: package foo/quxx: cannot find package "foo/quxx" in any of: - /home/you/go/src/pkg/foo/quxx (from $GOROOT) - /home/you/src/foo/quxx (from $GOPATH) -- --Second, the
- -go get
command no longer allows$GOROOT
-as the default destination when downloading package source. -To use thego get
-command, a valid$GOPATH
is now required. --$ GOPATH= go get code.google.com/p/foo/quxx -package code.google.com/p/foo/quxx: cannot download, $GOPATH not set. For more details see: go help gopath -- --Finally, as a result of the previous change, the
- -go get
command will also fail -when$GOPATH
and$GOROOT
are set to the same value. --$ GOPATH=$GOROOT go get code.google.com/p/foo/quxx -warning: GOPATH set to GOROOT (/home/you/go) has no effect -package code.google.com/p/foo/quxx: cannot download, $GOPATH must not be set to $GOROOT. For more details see: go help gopath -- -Changes to the go test command
- --The
- -go test
-command no longer deletes the binary when run with profiling enabled, -to make it easier to analyze the profile. -The implementation sets the-c
flag automatically, so after running, --$ go test -cpuprofile cpuprof.out mypackage -- --the file
- -mypackage.test
will be left in the directory wherego test
was run. --The
- -go test
-command can now generate profiling information -that reports where goroutines are blocked, that is, -where they tend to stall waiting for an event such as a channel communication. -The information is presented as a -blocking profile -enabled with the --blockprofile
-option of -go test
. -Rungo help test
for more information. -Changes to the go fix command
- --The
- -fix
command, usually run as -go fix
, no longer applies fixes to update code from -before Go 1 to use Go 1 APIs. -To update pre-Go 1 code to Go 1.1, use a Go 1.0 toolchain -to convert the code to Go 1.0 first. -Build constraints
- --The "
- -go1.1
" tag has been added to the list of default -build constraints. -This permits packages to take advantage of the new features in Go 1.1 while -remaining compatible with earlier versions of Go. --To build a file only with Go 1.1 and above, add this build constraint: -
- --// +build go1.1 -- --To build a file only with Go 1.0.x, use the converse constraint: -
- --// +build !go1.1 -- -Additional platforms
- --The Go 1.1 toolchain adds experimental support for
- -freebsd/arm
, -netbsd/386
,netbsd/amd64
,netbsd/arm
, -openbsd/386
andopenbsd/amd64
platforms. --An ARMv6 or later processor is required for
- -freebsd/arm
or -netbsd/arm
. --Go 1.1 adds experimental support for
- -cgo
onlinux/arm
. -Cross compilation
- --When cross-compiling, the
- -go
tool will disablecgo
-support by default. --To explicitly enable
- -cgo
, setCGO_ENABLED=1
. -Performance
- --The performance of code compiled with the Go 1.1 gc tool suite should be noticeably -better for most Go programs. -Typical improvements relative to Go 1.0 seem to be about 30%-40%, sometimes -much more, but occasionally less or even non-existent. -There are too many small performance-driven tweaks through the tools and libraries -to list them all here, but the following major changes are worth noting: -
- --
- -- The gc compilers generate better code in many cases, most noticeably for -floating point on the 32-bit Intel architecture.
-- The gc compilers do more in-lining, including for some operations -in the run-time such as
-append
-and interface conversions.- There is a new implementation of Go maps with significant reduction in -memory footprint and CPU time.
-- The garbage collector has been made more parallel, which can reduce -latencies for programs running on multiple CPUs.
-- The garbage collector is also more precise, which costs a small amount of -CPU time but can reduce the size of the heap significantly, especially -on 32-bit architectures.
-- Due to tighter coupling of the run-time and network libraries, fewer -context switches are required on network operations.
-Changes to the standard library
- -bufio.Scanner
- --The various routines to scan textual input in the -
- -bufio
-package, -ReadBytes
, -ReadString
-and particularly -ReadLine
, -are needlessly complex to use for simple purposes. -In Go 1.1, a new type, -Scanner
, -has been added to make it easier to do simple tasks such as -read the input as a sequence of lines or space-delimited words. -It simplifies the problem by terminating the scan on problematic -input such as pathologically long lines, and having a simple -default: line-oriented input, with each line stripped of its terminator. -Here is code to reproduce the input a line at a time: --scanner := bufio.NewScanner(os.Stdin) -for scanner.Scan() { - fmt.Println(scanner.Text()) // Println will add back the final '\n' -} -if err := scanner.Err(); err != nil { - fmt.Fprintln(os.Stderr, "reading standard input:", err) -} -- --Scanning behavior can be adjusted through a function to control subdividing the input -(see the documentation for
- -SplitFunc
), -but for tough problems or the need to continue past errors, the older interface -may still be required. -net
- --The protocol-specific resolvers in the
- -net
package were formerly -lax about the network name passed in. -Although the documentation was clear -that the only valid networks for -ResolveTCPAddr
-are"tcp"
, -"tcp4"
, and"tcp6"
, the Go 1.0 implementation silently accepted any string. -The Go 1.1 implementation returns an error if the network is not one of those strings. -The same is true of the other protocol-specific resolversResolveIPAddr
, -ResolveUDPAddr
, and -ResolveUnixAddr
. --The previous implementation of -
- -ListenUnixgram
-returned a -UDPConn
as -a representation of the connection endpoint. -The Go 1.1 implementation instead returns a -UnixConn
-to allow reading and writing -with its -ReadFrom
-and -WriteTo
-methods. --The data structures -
- -IPAddr
, -TCPAddr
, and -UDPAddr
-add a new string field calledZone
. -Code using untagged composite literals (e.g.net.TCPAddr{ip, port}
) -instead of tagged literals (net.TCPAddr{IP: ip, Port: port}
) -will break due to the new field. -The Go 1 compatibility rules allow this change: client code must use tagged literals to avoid such breakages. --Updating: -To correct breakage caused by the new struct field, -
- -go fix
will rewrite code to add tags for these types. -More generally,go vet
will identify composite literals that -should be revised to use field tags. -reflect
- --The
- -reflect
package has several significant additions. --It is now possible to run a "select" statement using -the
- -reflect
package; see the description of -Select
-and -SelectCase
-for details. --The new method -
- -Value.Convert
-(or -Type.ConvertibleTo
) -provides functionality to execute a Go conversion or type assertion operation -on a -Value
-(or test for its possibility). --The new function -
- -MakeFunc
-creates a wrapper function to make it easier to call a function with existing -Values
, -doing the standard Go conversions among the arguments, for instance -to pass an actualint
to a formalinterface{}
. --Finally, the new functions -
- - -ChanOf
, -MapOf
-and -SliceOf
-construct new -Types
-from existing types, for example to construct the type[]T
given -onlyT
. -time
--On FreeBSD, Linux, NetBSD, OS X and OpenBSD, previous versions of the -
- -time
package -returned times with microsecond precision. -The Go 1.1 implementation on these -systems now returns times with nanosecond precision. -Programs that write to an external format with microsecond precision -and read it back, expecting to recover the original value, will be affected -by the loss of precision. -There are two new methods ofTime
, -Round
-and -Truncate
, -that can be used to remove precision from a time before passing it to -external storage. --The new method -
- -YearDay
-returns the one-indexed integral day number of the year specified by the time value. --The -
- -Timer
-type has a new method -Reset
-that modifies the timer to expire after a specified duration. --Finally, the new function -
- -ParseInLocation
-is like the existing -Parse
-but parses the time in the context of a location (time zone), ignoring -time zone information in the parsed string. -This function addresses a common source of confusion in the time API. --Updating: -Code that needs to read and write times using an external format with -lower precision should be modified to use the new methods. -
- -Exp and old subtrees moved to go.exp and go.text subrepositories
- --To make it easier for binary distributions to access them if desired, the
- -exp
-andold
source subtrees, which are not included in binary distributions, -have been moved to the newgo.exp
subrepository at -code.google.com/p/go.exp
. To access thessa
package, -for example, run --$ go get code.google.com/p/go.exp/ssa -- --and then in Go source, -
- --import "code.google.com/p/go.exp/ssa" -- --The old package
- -exp/norm
has also been moved, but to a new repository -go.text
, where the Unicode APIs and other text-related packages will -be developed. -New packages
- --There are three new packages. -
- --
- -- -The
- -go/format
package provides -a convenient way for a program to access the formatting capabilities of the -go fmt
command. -It has two functions, -Node
to format a Go parser -Node
, -and -Source
-to reformat arbitrary Go source code into the standard format as provided by the -go fmt
command. -- -The
- -net/http/cookiejar
package provides the basics for managing HTTP cookies. -- -The
-runtime/race
package provides low-level facilities for data race detection. -It is internal to the race detector and does not otherwise export any user-visible functionality. -Minor changes to the library
- --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. -
- --
diff --git a/content/doc/go1.10.html b/content/doc/go1.10.html deleted file mode 100644 index 2974fef9..00000000 --- a/content/doc/go1.10.html +++ /dev/null @@ -1,1448 +0,0 @@ - - - - - - -- -The
- -bytes
package has two new functions, -TrimPrefix
-and -TrimSuffix
, -with self-evident properties. -Also, theBuffer
type -has a new method -Grow
that -provides some control over memory allocation inside the buffer. -Finally, the -Reader
type now has a -WriteTo
method -so it implements the -io.WriterTo
interface. -- -The
- -compress/gzip
package has -a newFlush
-method for its -Writer
-type that flushes its underlyingflate.Writer
. -- -The
- -crypto/hmac
package has a new function, -Equal
, to compare two MACs. -- -The
- -crypto/x509
package -now supports PEM blocks (see -DecryptPEMBlock
for instance), -and a new function -ParseECPrivateKey
to parse elliptic curve private keys. -- -The
- -database/sql
package -has a new -Ping
-method for its -DB
-type that tests the health of the connection. -- -The
- -database/sql/driver
package -has a new -Queryer
-interface that a -Conn
-may implement to improve performance. -- -The
- -encoding/json
package's -Decoder
-has a new method -Buffered
-to provide access to the remaining data in its buffer, -as well as a new method -UseNumber
-to unmarshal a value into the new type -Number
, -a string, rather than a float64. -- -The
- -encoding/xml
package -has a new function, -EscapeText
, -which writes escaped XML output, -and a method on -Encoder
, -Indent
, -to specify indented output. -- -In the
- -go/ast
package, a -new typeCommentMap
-and associated methods makes it easier to extract and process comments in Go programs. -- -In the
- -go/doc
package, -the parser now keeps better track of stylized annotations such asTODO(joe)
-throughout the code, -information that thegodoc
-command can filter or present according to the value of the-notes
flag. -- -The undocumented and only partially implemented "noescape" feature of the -
- -html/template
-package has been removed; programs that depend on it will break. -- -The
- -image/jpeg
package now -reads progressive JPEG files and handles a few more subsampling configurations. -- -The
- -io
package now exports the -io.ByteWriter
interface to capture the common -functionality of writing a byte at a time. -It also exports a new error,ErrNoProgress
, -used to indicate aRead
implementation is looping without delivering data. -- -The
- -log/syslog
package now provides better support -for OS-specific logging features. -- -The
- -math/big
package's -Int
type -now has methods -MarshalJSON
-and -UnmarshalJSON
-to convert to and from a JSON representation. -Also, -Int
-can now convert directly to and from auint64
using -Uint64
-and -SetUint64
, -while -Rat
-can do the same withfloat64
using -Float64
-and -SetFloat64
. -- -The
- -mime/multipart
package -has a new method for its -Writer
, -SetBoundary
, -to define the boundary separator used to package the output. -TheReader
also now -transparently decodes anyquoted-printable
parts and removes -theContent-Transfer-Encoding
header when doing so. -- -The -
- -net
package's -ListenUnixgram
-function has changed return types: it now returns a -UnixConn
-rather than a -UDPConn
, which was -clearly a mistake in Go 1.0. -Since this API change fixes a bug, it is permitted by the Go 1 compatibility rules. -- -The
- -net
package includes a new type, -Dialer
, to supply options to -Dial
. -- -The
- -net
package adds support for -link-local IPv6 addresses with zone qualifiers, such asfe80::1%lo0
. -The address structuresIPAddr
, -UDPAddr
, and -TCPAddr
-record the zone in a new field, and functions that expect string forms of these addresses, such as -Dial
, -ResolveIPAddr
, -ResolveUDPAddr
, and -ResolveTCPAddr
, -now accept the zone-qualified form. -- -The
- -net
package adds -LookupNS
to its suite of resolving functions. -LookupNS
returns the NS records for a host name. -- -The
- -net
package adds protocol-specific -packet reading and writing methods to -IPConn
-(ReadMsgIP
-andWriteMsgIP
) and -UDPConn
-(ReadMsgUDP
and -WriteMsgUDP
). -These are specialized versions ofPacketConn
's -ReadFrom
andWriteTo
methods that provide access to out-of-band data associated -with the packets. -- -The
- -net
package adds methods to -UnixConn
to allow closing half of the connection -(CloseRead
and -CloseWrite
), -matching the existing methods ofTCPConn
. -- -The
- -net/http
package includes several new additions. -ParseTime
parses a time string, trying -several common HTTP time formats. -ThePostFormValue
method of -Request
is like -FormValue
but ignores URL parameters. -TheCloseNotifier
interface provides a mechanism -for a server handler to discover when a client has disconnected. -TheServeMux
type now has a -Handler
method to access a path's -Handler
without executing it. -TheTransport
can now cancel an in-flight request with -CancelRequest
. -Finally, the Transport is now more aggressive at closing TCP connections when -aResponse.Body
is closed before -being fully consumed. -- -The
- -net/mail
package has two new functions, -ParseAddress
and -ParseAddressList
, -to parse RFC 5322-formatted mail addresses into -Address
structures. -- -The
- -net/smtp
package's -Client
type has a new method, -Hello
, -which transmits aHELO
orEHLO
message to the server. -- -The
- -net/textproto
package -has two new functions, -TrimBytes
and -TrimString
, -which do ASCII-only trimming of leading and trailing spaces. -- -The new method
- -os.FileMode.IsRegular
makes it easy to ask if a file is a plain file. -- -The
- -os/signal
package has a new function, -Stop
, which stops the package delivering -any further signals to the channel. -- -The
- -regexp
package -now supports Unix-original leftmost-longest matches through the -Regexp.Longest
-method, while -Regexp.Split
slices -strings into pieces based on separators defined by the regular expression. -- -The
- -runtime/debug
package -has three new functions regarding memory usage. -TheFreeOSMemory
-function triggers a run of the garbage collector and then attempts to return unused -memory to the operating system; -theReadGCStats
-function retrieves statistics about the collector; and -SetGCPercent
-provides a programmatic way to control how often the collector runs, -including disabling it altogether. -- -The
- -sort
package has a new function, -Reverse
. -Wrapping the argument of a call to -sort.Sort
-with a call toReverse
causes the sort order to be reversed. -- -The
- -strings
package has two new functions, -TrimPrefix
-and -TrimSuffix
-with self-evident properties, and the new method -Reader.WriteTo
so the -Reader
-type now implements the -io.WriterTo
interface. -- -The
-syscall
package's -Fchflags
function on various BSDs -(including Darwin) has changed signature. -It now takes an int as the first parameter instead of a string. -Since this API change fixes a bug, it is permitted by the Go 1 compatibility rules. -- -The
- -syscall
package also has received many updates -to make it more inclusive of constants and system calls for each supported operating system. -- -The
- -testing
package now automates the generation of allocation -statistics in tests and benchmarks using the new -AllocsPerRun
function. And the -ReportAllocs
-method ontesting.B
will enable printing of -memory allocation statistics for the calling benchmark. It also introduces the -AllocsPerOp
method of -BenchmarkResult
. -There is also a new -Verbose
function to test the state of the-v
-command-line flag, -and a new -Skip
method of -testing.B
and -testing.T
-to simplify skipping an inappropriate test. -- -In the
- -text/template
-and -html/template
packages, -templates can now use parentheses to group the elements of pipelines, simplifying the construction of complex pipelines. -Also, as part of the new parser, the -Node
interface got two new methods to provide -better error reporting. -Although this violates the Go 1 compatibility rules, -no existing code should be affected because this interface is explicitly intended only to be used -by the -text/template
-and -html/template
-packages and there are safeguards to guarantee that. -- -The implementation of the
- -unicode
package has been updated to Unicode version 6.2.0. -- -In the
-unicode/utf8
package, -the new functionValidRune
reports whether the rune is a valid Unicode code point. -To be valid, a rune must be in range and not be a surrogate half. -Introduction to Go 1.10
- --The latest Go release, version 1.10, arrives six months after Go 1.9. -Most of its changes are in the implementation of the toolchain, runtime, and libraries. -As always, the release maintains the Go 1 promise of compatibility. -We expect almost all Go programs to continue to compile and run as before. -
- --This release improves caching of built packages, -adds caching of successful test results, -runs vet automatically during tests, -and -permits passing string values directly between Go and C using cgo. -A new compiler option whitelist may cause -unexpected
- -invalid -flag
errors in code that built successfully with older -releases. -Changes to the language
- --There are no significant changes to the language specification. -
- --A corner case involving shifts of untyped constants has been clarified, -and as a result the compilers have been updated to allow the index expression -
- -x[1.0
<<
s]
wheres
is an unsigned integer; -the go/types package already did. --The grammar for method expressions has been updated to relax the -syntax to allow any type expression as a receiver; -this matches what the compilers were already implementing. -For example,
- -struct{io.Reader}.Read
is a valid, if unusual, -method expression that the compilers already accepted and is -now permitted by the language grammar. -Ports
- --There are no new supported operating systems or processor architectures in this release. -Most of the work has focused on strengthening the support for existing ports, -in particular new instructions in the assembler -and improvements to the code generated by the compilers. -
- --As announced in the Go 1.9 release notes, -Go 1.10 now requires FreeBSD 10.3 or later; -support for FreeBSD 9.3 has been removed. -
- --Go now runs on NetBSD again but requires the unreleased NetBSD 8. -Only
- -GOARCH
amd64
and386
have -been fixed. Thearm
port is still broken. --On 32-bit MIPS systems, the new environment variable settings -
- -GOMIPS=hardfloat
(the default) and -GOMIPS=softfloat
select whether to use -hardware instructions or software emulation for floating-point computations. --Go 1.10 is the last release that will run on OpenBSD 6.0. -Go 1.11 will require OpenBSD 6.2. -
- --Go 1.10 is the last release that will run on OS X 10.8 Mountain Lion or OS X 10.9 Mavericks. -Go 1.11 will require OS X 10.10 Yosemite or later. -
- --Go 1.10 is the last release that will run on Windows XP or Windows Vista. -Go 1.11 will require Windows 7 or later. -
- -Tools
- -Default GOROOT & GOTMPDIR
- --If the environment variable
- -$GOROOT
is unset, -the go tool previously used the defaultGOROOT
-set during toolchain compilation. -Now, before falling back to that default, the go tool attempts to -deduceGOROOT
from its own executable path. -This allows binary distributions to be unpacked anywhere in the -file system and then be used without settingGOROOT
-explicitly. --By default, the go tool creates its temporary files and directories -in the system temporary directory (for example,
- -$TMPDIR
on Unix). -If the new environment variable$GOTMPDIR
is set, -the go tool will creates its temporary files and directories in that directory instead. -Build & Install
- --The
- -go
build
command now detects out-of-date packages -purely based on the content of source files, specified build flags, and metadata stored in the compiled packages. -Modification times are no longer consulted or relevant. -The old advice to add-a
to force a rebuild in cases where -the modification times were misleading for one reason or another -(for example, changes in build flags) is no longer necessary: -builds now always detect when packages must be rebuilt. -(If you observe otherwise, please file a bug.) --The
- -go
build
-asmflags
,-gcflags
,-gccgoflags
, and-ldflags
options -now apply by default only to the packages listed directly on the command line. -For example,go
build
-gcflags=-m
mypkg
-passes the compiler the-m
flag when buildingmypkg
-but not its dependencies. -The new, more general form-asmflags=pattern=flags
(and similarly for the others) -applies theflags
only to the packages matching the pattern. -For example:go
install
-ldflags=cmd/gofmt=-X=main.version=1.2.3
cmd/...
-installs all the commands matchingcmd/...
but only applies the-X
option -to the linker flags forcmd/gofmt
. -For more details, seego
help
build
. --The
- -go
build
command now maintains a cache of -recently built packages, separate from the installed packages in$GOROOT/pkg
or$GOPATH/pkg
. -The effect of the cache should be to speed builds that do not explicitly install packages -or when switching between different copies of source code (for example, when changing -back and forth between different branches in a version control system). -The old advice to add the-i
flag for speed, as ingo
build
-i
-orgo
test
-i
, -is no longer necessary: builds run just as fast without-i
. -For more details, seego
help
cache
. --The
- -go
install
command now installs only the -packages and commands listed directly on the command line. -For example,go
install
cmd/gofmt
-installs the gofmt program but not any of the packages on which it depends. -The new build cache makes future commands still run as quickly as if the -dependencies had been installed. -To force the installation of dependencies, use the new -go
install
-i
flag. -Installing dependency packages should not be necessary in general, -and the very concept of installed packages may disappear in a future release. --Many details of the
- -go
build
implementation have changed to support these improvements. -One new requirement implied by these changes is that -binary-only packages must now declare accurate import blocks in their -stub source code, so that those imports can be made available when -linking a program using the binary-only package. -For more details, seego
help
filetype
. -Test
- --The
- -go
test
command now caches test results: -if the test executable and command line match a previous run -and the files and environment variables consulted by that run -have not changed either,go
test
will print -the previous test output, replacing the elapsed time with the string “(cached).” -Test caching applies only to successful test results; -only togo
test
-commands with an explicit list of packages; and -only to command lines using a subset of the --cpu
,-list
,-parallel
, --run
,-short
, and-v
test flags. -The idiomatic way to bypass test caching is to use-count=1
. --The
- -go
test
command now automatically runs -go
vet
on the package being tested, -to identify significant problems before running the test. -Any such problems are treated like build errors and prevent execution of the test. -Only a high-confidence subset of the availablego
vet
-checks are enabled for this automatic check. -To disable the running ofgo
vet
, use -go
test
-vet=off
. --The
- -go
test
-coverpkg
flag now -interprets its argument as a comma-separated list of patterns to match against -the dependencies of each test, not as a list of packages to load anew. -For example,go
test
-coverpkg=all
-is now a meaningful way to run a test with coverage enabled for the test package -and all its dependencies. -Also, thego
test
-coverprofile
option is now -supported when running multiple tests. --In case of failure due to timeout, tests are now more likely to write their profiles before exiting. -
- --The
- -go
test
command now always -merges the standard output and standard error from a given test binary execution -and writes both togo
test
's standard output. -In past releases,go
test
only applied this -merging most of the time. --The
- -go
test
-v
output -now includesPAUSE
andCONT
status update -lines to mark when parallel tests pause and continue. --The new
- -go
test
-failfast
flag -disables running additional tests after any test fails. -Note that tests running in parallel with the failing test are allowed to complete. --Finally, the new
- - -go
test
-json
flag -filters test output through the new command -go
tool
test2json
-to produce a machine-readable JSON-formatted description of test execution. -This allows the creation of rich presentations of test execution -in IDEs and other tools. --For more details about all these changes, -see
- -go
help
test
-and the test2json documentation. -Cgo
- --Options specified by cgo using
- -#cgo CFLAGS
and the like -are now checked against a whitelist of permitted options. -This closes a security hole in which a downloaded package uses -compiler options like --fplugin
-to run arbitrary code on the machine where it is being built. -This can cause a build error such asinvalid flag in #cgo CFLAGS
. -For more background, and how to handle this error, see -https://golang.org/s/invalidflag. --Cgo now implements a C typedef like “
- -typedef
X
Y
” using a Go type alias, -so that Go code may use the typesC.X
andC.Y
interchangeably. -It also now supports the use of niladic function-like macros. -Also, the documentation has been updated to clarify that -Go structs and Go arrays are not supported in the type signatures of cgo-exported functions. --Cgo now supports direct access to Go string values from C. -Functions in the C preamble may use the type
- -_GoString_
-to accept a Go string as an argument. -C code may call_GoStringLen
and_GoStringPtr
-for direct access to the contents of the string. -A value of type_GoString_
-may be passed in a call to an exported Go function that takes an argument of Go typestring
. --During toolchain bootstrap, the environment variables
- -CC
andCC_FOR_TARGET
specify -the default C compiler that the resulting toolchain will use for host and target builds, respectively. -However, if the toolchain will be used with multiple targets, it may be necessary to specify a different C compiler for each -(for example, a different compiler fordarwin/arm64
versuslinux/ppc64le
). -The new set of environment variablesCC_FOR_goos_goarch
-allows specifying a different default C compiler for each target. -Note that these variables only apply during toolchain bootstrap, -to set the defaults used by the resulting toolchain. -Latergo
build
commands use theCC
environment -variable or else the built-in default. --Cgo now translates some C types that would normally map to a pointer -type in Go, to a
- -uintptr
instead. These types include -theCFTypeRef
hierarchy in Darwin's CoreFoundation -framework and thejobject
hierarchy in Java's JNI -interface. --These types must be
- -uintptr
on the Go side because they -would otherwise confuse the Go garbage collector; they are sometimes -not really pointers but data structures encoded in a pointer-sized integer. -Pointers to Go memory must not be stored in theseuintptr
values. --Because of this change, values of the affected types need to be -zero-initialized with the constant
- -0
instead of the -constantnil
. Go 1.10 providesgofix
-modules to help with that rewrite: --go tool fix -r cftype <pkg> -go tool fix -r jni <pkg> -- --For more details, see the cgo documentation. -
- -Doc
- --The
- -go
doc
tool now adds functions returning slices ofT
or*T
-to the display of typeT
, similar to the existing behavior for functions returning singleT
or*T
results. -For example: --$ go doc mail.Address -package mail // import "net/mail" - -type Address struct { - Name string - Address string -} - Address represents a single mail address. - -func ParseAddress(address string) (*Address, error) -func ParseAddressList(list string) ([]*Address, error) -func (a *Address) String() string -$ -- --Previously,
- -ParseAddressList
was only shown in the package overview (go
doc
Fix
- --The
- -go
fix
tool now replaces imports of"golang.org/x/net/context"
-with"context"
. -(Forwarding aliases in the former make it completely equivalent to the latter when using Go 1.9 or later.) -Get
- --The
- -go
get
command now supports Fossil source code repositories. -Pprof
- --The blocking and mutex profiles produced by the
- -runtime/pprof
package -now include symbol information, so they can be viewed -ingo
tool
pprof
-without the binary that produced the profile. -(All other profile types were changed to include symbol information in Go 1.9.) --The
- -go
tool
pprof
-profile visualizer has been updated to git version 9e20b5b (2017-11-08) -from github.com/google/pprof, -which includes an updated web interface. -Vet
- --The
- -go
vet
command now always has access to -complete, up-to-date type information when checking packages, even for packages using cgo or vendored imports. -The reports should be more accurate as a result. -Note that onlygo
vet
has access to this information; -the more low-levelgo
tool
vet
does not -and should be avoided except when working onvet
itself. -(As of Go 1.9,go
vet
provides access to all the same flags as -go
tool
vet
.) -Diagnostics
- --This release includes a new overview of available Go program diagnostic tools. -
- -Gofmt
- --Two minor details of the default formatting of Go source code have changed. -First, certain complex three-index slice expressions previously formatted like -
- -x[i+1
:
j:k]
and now -format with more consistent spacing:x[i+1
:
j
:
k]
. -Second, single-method interface literals written on a single line, -which are sometimes used in type assertions, -are no longer split onto multiple lines. --Note that these kinds of minor updates to gofmt are expected from time to time. -In general, we recommend against building systems that check that source code -matches the output of a specific version of gofmt. -For example, a continuous integration test that fails if any code already checked into -a repository is not “properly formatted” is inherently fragile and not recommended. -
- --If multiple programs must agree about which version of gofmt is used to format a source file, -we recommend that they do this by arranging to invoke the same gofmt binary. -For example, in the Go open source repository, our Git pre-commit hook is written in Go -and could import
- -go/format
directly, but instead it invokes thegofmt
-binary found in the current path, so that the pre-commit hook need not be recompiled -each timegofmt
changes. -Compiler Toolchain
- --The compiler includes many improvements to the performance of generated code, -spread fairly evenly across the supported architectures. -
- --The DWARF debug information recorded in binaries has been improved in a few ways: -constant values are now recorded; -line number information is more accurate, making source-level stepping through a program work better; -and each package is now presented as its own DWARF compilation unit. -
- --The various build modes -have been ported to more systems. -Specifically,
- -c-shared
now works onlinux/ppc64le
,windows/386
, andwindows/amd64
; -pie
now works ondarwin/amd64
and also forces the use of external linking on all systems; -andplugin
now works onlinux/ppc64le
anddarwin/amd64
. --The
- -linux/ppc64le
port now requires the use of external linking -with any programs that use cgo, even uses by the standard library. -Assembler
- --For the ARM 32-bit port, the assembler now supports the instructions -
- -BFC
, -BFI
, -BFX
, -BFXU
, -FMULAD
, -FMULAF
, -FMULSD
, -FMULSF
, -FNMULAD
, -FNMULAF
, -FNMULSD
, -FNMULSF
, -MULAD
, -MULAF
, -MULSD
, -MULSF
, -NMULAD
, -NMULAF
, -NMULD
, -NMULF
, -NMULSD
, -NMULSF
, -XTAB
, -XTABU
, -XTAH
, -and -XTAHU
. --For the ARM 64-bit port, the assembler now supports the -
- -VADD
, -VADDP
, -VADDV
, -VAND
, -VCMEQ
, -VDUP
, -VEOR
, -VLD1
, -VMOV
, -VMOVI
, -VMOVS
, -VORR
, -VREV32
, -and -VST1
-instructions. --For the PowerPC 64-bit port, the assembler now supports the POWER9 instructions -
- -ADDEX
, -CMPEQB
, -COPY
, -DARN
, -LDMX
, -MADDHD
, -MADDHDU
, -MADDLD
, -MFVSRLD
, -MTVSRDD
, -MTVSRWS
, -PASTECC
, -VCMPNEZB
, -VCMPNEZBCC
, -and -VMSUMUDM
. --For the S390X port, the assembler now supports the -
- -TMHH
, -TMHL
, -TMLH
, -and -TMLL
-instructions. --For the X86 64-bit port, the assembler now supports 359 new instructions, -including the full AVX, AVX2, BMI, BMI2, F16C, FMA3, SSE2, SSE3, SSSE3, SSE4.1, and SSE4.2 extension sets. -The assembler also no longer implements
- -MOVL
$0,
AX
-as anXORL
instruction, -to avoid clearing the condition flags unexpectedly. -Gccgo
- --Due to the alignment of Go's semiannual release schedule with GCC's -annual release schedule, -GCC release 7 contains the Go 1.8.3 version of gccgo. -We expect that the next release, GCC 8, will contain the Go 1.10 -version of gccgo. -
- -Runtime
- --The behavior of nested calls to -
- -LockOSThread
and -UnlockOSThread
-has changed. -These functions control whether a goroutine is locked to a specific operating system thread, -so that the goroutine only runs on that thread, and the thread only runs that goroutine. -Previously, callingLockOSThread
more than once in a row -was equivalent to calling it once, and a singleUnlockOSThread
-always unlocked the thread. -Now, the calls nest: ifLockOSThread
is called multiple times, -UnlockOSThread
must be called the same number of times -in order to unlock the thread. -Existing code that was careful not to nest these calls will remain correct. -Existing code that incorrectly assumed the calls nested will become correct. -Most uses of these functions in public Go source code falls into the second category. --Because one common use of
- -LockOSThread
andUnlockOSThread
-is to allow Go code to reliably modify thread-local state (for example, Linux or Plan 9 name spaces), -the runtime now treats locked threads as unsuitable for reuse or for creating new threads. --Stack traces no longer include implicit wrapper functions (previously marked
- -<autogenerated>
), -unless a fault or panic happens in the wrapper itself. -As a result, skip counts passed to functions likeCaller
-should now always match the structure of the code as written, rather than depending on -optimization decisions and implementation details. --The garbage collector has been modified to reduce its impact on allocation latency. -It now uses a smaller fraction of the overall CPU when running, but it may run more of the time. -The total CPU consumed by the garbage collector has not changed significantly. -
- --The
- -GOROOT
function -now defaults (when the$GOROOT
environment variable is not set) -to theGOROOT
orGOROOT_FINAL
in effect -at the time the calling program was compiled. -Previously it used theGOROOT
orGOROOT_FINAL
in effect -at the time the toolchain that compiled the calling program was compiled. --There is no longer a limit on the
- -GOMAXPROCS
setting. -(In Go 1.9 the limit was 1024.) -Performance
- --As always, the changes are so general and varied that precise -statements about performance are difficult to make. Most programs -should run a bit faster, due to speedups in the garbage collector, -better generated code, and optimizations in the core library. -
- -Garbage Collector
- --Many applications should experience significantly lower allocation latency and overall performance overhead when the garbage collector is active. -
- -Core library
- --All of the changes to the standard library are minor. -The changes in bytes -and net/url are the most likely to require updating of existing programs. -
- -Minor changes to the library
- --As always, there are various minor changes and updates to the library, -made with the Go 1 promise of compatibility -in mind. -
- -- -
- archive/tar
-- -
-In general, the handling of special header formats is significantly improved and expanded. -
--
-FileInfoHeader
has always -recorded the Unix UID and GID numbers from itsos.FileInfo
argument -(specifically, from the system-dependent information returned by theFileInfo
'sSys
method) -in the returnedHeader
. -Now it also records the user and group names corresponding to those IDs, -as well as the major and minor device numbers for device files. --The new
-Header.Format
field -of typeFormat
-controls which tar header format theWriter
uses. -The default, as before, is to select the most widely-supported header type -that can encode the fields needed by the header (USTAR if possible, or else PAX if possible, or else GNU). -TheReader
setsHeader.Format
for each header it reads. --
-Reader
and theWriter
now support arbitrary PAX records, -using the newHeader.PAXRecords
field, -a generalization of the existingXattrs
field. --The
-Reader
no longer insists that the file name or link name in GNU headers -be valid UTF-8. --When writing PAX- or GNU-format headers, the
-Writer
now includes -theHeader.AccessTime
andHeader.ChangeTime
fields (if set). -When writing PAX-format headers, the times include sub-second precision. -- -
- archive/zip
-- -
-Go 1.10 adds more complete support for times and character set encodings in ZIP archives. -
--The original ZIP format used the standard MS-DOS encoding of year, month, day, hour, minute, and second into fields in two 16-bit values. -That encoding cannot represent time zones or odd seconds, so multiple extensions have been -introduced to allow richer encodings. -In Go 1.10, the
-Reader
andWriter
-now support the widely-understood Info-Zip extension that encodes the time separately in the 32-bit Unix “seconds since epoch” form. -TheFileHeader
's newModified
field of typetime.Time
-obsoletes theModifiedTime
andModifiedDate
fields, which continue to hold the MS-DOS encoding. -TheReader
andWriter
now adopt the common -convention that a ZIP archive storing a time zone-independent Unix time -also stores the local time in the MS-DOS field, -so that the time zone offset can be inferred. -For compatibility, theModTime
and -SetModTime
methods -behave the same as in earlier releases; new code should useModified
directly. --The header for each file in a ZIP archive has a flag bit indicating whether -the name and comment fields are encoded as UTF-8, as opposed to a system-specific default encoding. -In Go 1.8 and earlier, the
-Writer
never set the UTF-8 bit. -In Go 1.9, theWriter
changed to set the UTF-8 bit almost always. -This broke the creation of ZIP archives containing Shift-JIS file names. -In Go 1.10, theWriter
now sets the UTF-8 bit only when -both the name and the comment field are valid UTF-8 and at least one is non-ASCII. -Because non-ASCII encodings very rarely look like valid UTF-8, the new -heuristic should be correct nearly all the time. -Setting aFileHeader
's newNonUTF8
field to true -disables the heuristic entirely for that file. --The
-Writer
also now supports setting the end-of-central-directory record's comment field, -by calling theWriter
's newSetComment
method. -- -
- bufio
-- -
-The new
-Reader.Size
-andWriter.Size
-methods report theReader
orWriter
's underlying buffer size. -- -
- bytes
-- -
-The -
-Fields
, -FieldsFunc
, -Split
, -and -SplitAfter
-functions have always returned subslices of their inputs. -Go 1.10 changes each returned subslice to have capacity equal to its length, -so that appending to one cannot overwrite adjacent data in the original input. -- -
- crypto/cipher
-- -
-
-NewOFB
now panics if given -an initialization vector of incorrect length, like the other constructors in the -package always have. -(Previously it returned a nilStream
implementation.) -- -
- crypto/tls
-- -
-The TLS server now advertises support for SHA-512 signatures when using TLS 1.2. -The server already supported the signatures, but some clients would not select -them unless explicitly advertised. -
-- -
- crypto/x509
-- -
-
- -Certificate.Verify
-now enforces the name constraints for all -names contained in the certificate, not just the one name that a client has asked about. -Extended key usage restrictions are similarly now checked all at once. -As a result, after a certificate has been validated, now it can be trusted in its entirety. -It is no longer necessary to revalidate the certificate for each additional name -or key usage. --Parsed certificates also now report URI names and IP, email, and URI constraints, using the new -
- -Certificate
fields -URIs
,PermittedIPRanges
,ExcludedIPRanges
, -PermittedEmailAddresses
,ExcludedEmailAddresses
, -PermittedURIDomains
, andExcludedURIDomains
. Certificates with -invalid values for those fields are now rejected. --The new
- -MarshalPKCS1PublicKey
-andParsePKCS1PublicKey
-functions convert an RSA public key to and from PKCS#1-encoded form. --The new
-MarshalPKCS8PrivateKey
-function converts a private key to PKCS#8-encoded form. -(ParsePKCS8PrivateKey
-has existed since Go 1.) -- -
- crypto/x509/pkix
-- -
-
-Name
now implements a -String
method that -formats the X.509 distinguished name in the standard RFC 2253 format. -- -
- database/sql/driver
-- -
-Drivers that currently hold on to the destination buffer provided by -
-driver.Rows.Next
should ensure they no longer -write to a buffer assigned to the destination array outside of that call. -Drivers must be careful that underlying buffers are not modified when closing -driver.Rows
. --Drivers that want to construct a
-sql.DB
for -their clients can now implement theConnector
interface -and call the newsql.OpenDB
function, -instead of needing to encode all configuration into a string -passed tosql.Open
. --Drivers that want to parse the configuration string only once per
-sql.DB
-instead of once persql.Conn
, -or that want access to eachsql.Conn
's underlying context, -can make theirDriver
-implementations also implementDriverContext
's -newOpenConnector
method. --Drivers that implement
-ExecerContext
-no longer need to implementExecer
; -similarly, drivers that implementQueryerContext
-no longer need to implementQueryer
. -Previously, even if the context-based interfaces were implemented they were ignored -unless the non-context-based interfaces were also implemented. --To allow drivers to better isolate different clients using a cached driver connection in succession, -if a
-Conn
implements the new -SessionResetter
interface, -database/sql
will now callResetSession
before -reusing theConn
for a new client. -- -
- debug/elf
-- -
-This release adds 348 new relocation constants divided between the relocation types -
-R_386
, -R_AARCH64
, -R_ARM
, -R_PPC64
, -and -R_X86_64
. -- -
- debug/macho
-- -
-Go 1.10 adds support for reading relocations from Mach-O sections, -using the
-Section
struct's newRelocs
field -and the newReloc
, -RelocTypeARM
, -RelocTypeARM64
, -RelocTypeGeneric
, -and -RelocTypeX86_64
-types and associated constants. --Go 1.10 also adds support for the
-LC_RPATH
load command, -represented by the types -RpathCmd
and -Rpath
, -and new named constants -for the various flag bits found in headers. -- -
- encoding/asn1
-- -
-
-Marshal
now correctly encodes -strings containing asterisks as type UTF8String instead of PrintableString, -unless the string is in a struct field with a tag forcing the use of PrintableString. -Marshal
also now respects struct tags containingapplication
directives. --The new
-MarshalWithParams
-function marshals its argument as if the additional params were its associated -struct field tag. --
-Unmarshal
now respects -struct field tags using theexplicit
andtag
-directives. --Both
-Marshal
andUnmarshal
now support a new struct field tag -numeric
, indicating an ASN.1 NumericString. -- -
- encoding/csv
-- -
-
-Reader
now disallows the use of -nonsensicalComma
andComment
settings, -such as NUL, carriage return, newline, invalid runes, and the Unicode replacement character, -or settingComma
andComment
equal to each other. --In the case of a syntax error in a CSV record that spans multiple input lines,
-Reader
-now reports the line on which the record started in theParseError
's newStartLine
field. -- -
- encoding/hex
-- -
-The new functions -
- -NewEncoder
-and -NewDecoder
-provide streaming conversions to and from hexadecimal, -analogous to equivalent functions already in -encoding/base32 -and -encoding/base64. --When the functions -
-Decode
-and -DecodeString
-encounter malformed input, -they now return the number of bytes already converted -along with the error. -Previously they always returned a count of 0 with any error. -- -
- encoding/json
-- -
-The
- -Decoder
-adds a new method -DisallowUnknownFields
-that causes it to report inputs with unknown JSON fields as a decoding error. -(The default behavior has always been to discard unknown fields.) --As a result of fixing a reflect bug, -
-Unmarshal
-can no longer decode into fields inside -embedded pointers to unexported struct types, -because it cannot initialize the unexported embedded pointer -to point at fresh storage. -Unmarshal
now returns an error in this case. -- -
- encoding/pem
-- -
-
-Encode
-and -EncodeToMemory
-no longer generate partial output when presented with a -block that is impossible to encode as PEM data. -- -
- encoding/xml
-- -
-The new function -
-NewTokenDecoder
-is like -NewDecoder
-but creates a decoder reading from aTokenReader
-instead of an XML-formatted byte stream. -This is meant to enable the construction of XML stream transformers in client libraries. -- -
- flag
-- -
-The default -
-Usage
function now prints -its first line of output to -CommandLine.Output()
-instead of assumingos.Stderr
, -so that the usage message is properly redirected for -clients usingCommandLine.SetOutput
. --
-PrintDefaults
now -adds appropriate indentation after newlines in flag usage strings, -so that multi-line usage strings display nicely. --
-FlagSet
adds new methods -ErrorHandling
, -Name
, -and -Output
, -to retrieve the settings passed to -NewFlagSet
-and -FlagSet.SetOutput
. -- -
- go/doc
-- -
-To support the doc change described above, -functions returning slices of
-T
,*T
,**T
, and so on -are now reported inT
'sType
'sFuncs
list, -instead of in thePackage
'sFuncs
list. -- -
- go/importer
-- -
-The
-For
function now accepts a non-nil lookup argument. -- -
- go/printer
-- -
-The changes to the default formatting of Go source code -discussed in the gofmt section above -are implemented in the go/printer package -and also affect the output of the higher-level go/format package. -
-- -
- hash
-- -
-Implementations of the
-Hash
interface are now -encouraged to implementencoding.BinaryMarshaler
-andencoding.BinaryUnmarshaler
-to allow saving and recreating their internal state, -and all implementations in the standard library -(hash/crc32, crypto/sha256, and so on) -now implement those interfaces. -- -
- html/template
-- -
-The new
-Srcset
content -type allows for proper handling of values within the -srcset
-attribute ofimg
tags. -- -
- math/big
-- -
-
-Int
now supports conversions to and from bases 2 through 62 -in itsSetString
andText
methods. -(Previously it only allowed bases 2 through 36.) -The value of the constantMaxBase
has been updated. --
- -Int
adds a new -CmpAbs
method -that is likeCmp
but -compares only the absolute values (not the signs) of its arguments. -- -
- math/cmplx
-- -
-Branch cuts and other boundary cases in -
-Asin
, -Asinh
, -Atan
, -and -Sqrt
-have been corrected to match the definitions used in the C99 standard. -- -
- math/rand
-- -
-The new
-Shuffle
function and corresponding -Rand.Shuffle
method -shuffle an input sequence. -- -
- math
-- -
-The new functions -
- -Round
-and -RoundToEven
-round their arguments to the nearest floating-point integer; -Round
rounds a half-integer to its larger integer neighbor (away from zero) -whileRoundToEven
rounds a half-integer to its even integer neighbor. --The new functions -
-Erfinv
-and -Erfcinv
-compute the inverse error function and the -inverse complementary error function. -- -
- mime/multipart
-- -
-
-Reader
-now accepts parts with empty filename attributes. -- -
- mime
-- -
-
-ParseMediaType
now discards -invalid attribute values; previously it returned those values as empty strings. -- -
- net
-- -
-The
- -Conn
and -Listener
implementations -in this package now guarantee that whenClose
returns, -the underlying file descriptor has been closed. -(In earlier releases, if theClose
stopped pending I/O -in other goroutines, the closing of the file descriptor could happen in one of those -goroutines shortly afterClose
returned.) --
- -TCPListener
and -UnixListener
-now implement -syscall.Conn
, -to allow setting options on the underlying file descriptor -usingsyscall.RawConn.Control
. --The
- -Conn
implementations returned byPipe
-now support setting read and write deadlines. --The
-IPConn.ReadMsgIP
, -IPConn.WriteMsgIP
, -UDPConn.ReadMsgUDP
, -and -UDPConn.WriteMsgUDP
, -methods are now implemented on Windows. -- -
- net/http
-- -
-On the client side, an HTTP proxy (most commonly configured by -
-ProxyFromEnvironment
) -can now be specified as anhttps://
URL, -meaning that the client connects to the proxy over HTTPS before issuing a standard, proxied HTTP request. -(Previously, HTTP proxy URLs were required to begin withhttp://
orsocks5://
.) --On the server side,
-FileServer
and its single-file equivalentServeFile
-now applyIf-Range
checks toHEAD
requests. -FileServer
also now reports directory read failures to theServer
'sErrorLog
. -The content-serving handlers also now omit theContent-Type
header when serving zero-length content. --
-ResponseWriter
'sWriteHeader
method now panics -if passed an invalid (non-3-digit) status code. -- -The
-Server
will no longer add an implicit Content-Type when aHandler
does not write any output. --
-Redirect
now sets theContent-Type
header before writing its HTTP response. -- -
- net/mail
-- -
-
-ParseAddress
and -ParseAddressList
-now support a variety of obsolete address formats. -- -
- net/smtp
-- -
-The
-Client
adds a new -Noop
method, -to test whether the server is still responding. -It also now defends against possible SMTP injection in the inputs -to theHello
-andVerify
methods. -- -
- net/textproto
-- -
-
-ReadMIMEHeader
-now rejects any header that begins with a continuation (indented) header line. -Previously a header with an indented first line was treated as if the first line -were not indented. -- -
- net/url
-- -
-
-ResolveReference
-now preserves multiple leading slashes in the target URL. -Previously it rewrote multiple leading slashes to a single slash, -which resulted in thehttp.Client
-following certain redirects incorrectly. --For example, this code's output has changed: -
--base, _ := url.Parse("http://host//path//to/page1") -target, _ := url.Parse("page2") -fmt.Println(base.ResolveReference(target)) ---Note the doubled slashes around
- -path
. -In Go 1.9 and earlier, the resolved URL washttp://host/path//to/page2
: -the doubled slash beforepath
was incorrectly rewritten -to a single slash, while the doubled slash afterpath
was -correctly preserved. -Go 1.10 preserves both doubled slashes, resolving tohttp://host//path//to/page2
-as required by RFC 3986. -This change may break existing buggy programs that unintentionally -construct a base URL with a leading doubled slash in the path and inadvertently -depend on
- -ResolveReference
to correct that mistake. -For example, this can happen if code adds a host prefix -likehttp://host/
to a path like/my/api
, -resulting in a URL with a doubled slash:http://host//my/api
. --
-UserInfo
's methods -now treat a nil receiver as equivalent to a pointer to a zeroUserInfo
. -Previously, they panicked. -- -
- os
-- -
-
- -File
adds new methods -SetDeadline
, -SetReadDeadline
, -and -SetWriteDeadline
-that allow setting I/O deadlines when the -underlying file descriptor supports non-blocking I/O operations. -The definition of these methods matches those innet.Conn
. -If an I/O method fails due to missing a deadline, it will return a -timeout error; the -newIsTimeout
function -reports whether an error represents a timeout. --Also matching
- -net.Conn
, -File
's -Close
method -now guarantee that whenClose
returns, -the underlying file descriptor has been closed. -(In earlier releases, -if theClose
stopped pending I/O -in other goroutines, the closing of the file descriptor could happen in one of those -goroutines shortly afterClose
returned.) --On BSD, macOS, and Solaris systems, -
-Chtimes
-now supports setting file times with nanosecond precision -(assuming the underlying file system can represent them). -- -
- reflect
-- -
-The
- -Copy
function now allows copying -from a string into a byte array or byte slice, to match the -built-in copy function. --In structs, embedded pointers to unexported struct types were -previously incorrectly reported with an empty
-PkgPath
-in the corresponding StructField, -with the result that for those fields, -andValue.CanSet
-incorrectly returned true and -Value.Set
-incorrectly succeeded. -The underlying metadata has been corrected; -for those fields, -CanSet
now correctly returns false -andSet
now correctly panics. -This may affect reflection-based unmarshalers -that could previously unmarshal into such fields -but no longer can. -For example, see theencoding/json
notes. -- -
- runtime/pprof
-- -
-As noted above, the blocking and mutex profiles -now include symbol information so that they can be viewed without needing -the binary that generated them. -
-- -
- strconv
-- -
-
-ParseUint
now returns -the maximum magnitude integer of the appropriate size -with anyErrRange
error, as it was already documented to do. -Previously it returned 0 withErrRange
errors. -- -
- strings
-- -
-A new type -
-Builder
is a replacement for -bytes.Buffer
for the use case of -accumulating text into astring
result. -TheBuilder
's API is a restricted subset ofbytes.Buffer
's -that allows it to safely avoid making a duplicate copy of the data -during theString
method. -- -
- syscall
-- -
-On Windows, -the new
- -SysProcAttr
fieldToken
, -of typeToken
allows the creation of a process that -runs as another user duringStartProcess
-(and therefore also duringos.StartProcess
and -exec.Cmd.Start
). -The new functionCreateProcessAsUser
-gives access to the underlying system call. --On BSD, macOS, and Solaris systems,
-UtimesNano
-is now implemented. -- -
- time
-- -
-
-LoadLocation
now uses the directory -or uncompressed zip file named by the$ZONEINFO
-environment variable before looking in the default system-specific list of -known installation locations or in$GOROOT/lib/time/zoneinfo.zip
. --The new function
-LoadLocationFromTZData
-allows conversion of IANA time zone file data to aLocation
. -diff --git a/content/doc/go1.11.html b/content/doc/go1.11.html deleted file mode 100644 index 1d85be9f..00000000 --- a/content/doc/go1.11.html +++ /dev/null @@ -1,934 +0,0 @@ - - - - - - -
- unicode
-- -
-The
-unicode
package and associated -support throughout the system has been upgraded from Unicode 9.0 to -Unicode 10.0, -which adds 8,518 new characters, including four new scripts, one new property, -a Bitcoin currency symbol, and 56 new emoji. -Introduction to Go 1.11
- -- The latest Go release, version 1.11, arrives six months after Go 1.10. - Most of its changes are in the implementation of the toolchain, runtime, and libraries. - As always, the release maintains the Go 1 promise of compatibility. - We expect almost all Go programs to continue to compile and run as before. -
- -Changes to the language
- -- There are no changes to the language specification. -
- -Ports
- -- As announced in the Go 1.10 release notes, Go 1.11 now requires - OpenBSD 6.2 or later, macOS 10.10 Yosemite or later, or Windows 7 or later; - support for previous versions of these operating systems has been removed. -
- -- Go 1.11 supports the upcoming OpenBSD 6.4 release. Due to changes in - the OpenBSD kernel, older versions of Go will not work on OpenBSD 6.4. -
- -- There are known issues with NetBSD on i386 hardware. -
- -- The race detector is now supported on
- -linux/ppc64le
- and, to a lesser extent, onnetbsd/amd64
. The NetBSD race detector support - has known issues. -- The memory sanitizer (
- --msan
) is now supported onlinux/arm64
. -- The build modes
- -c-shared
andc-archive
are now supported on -freebsd/amd64
. -- On 64-bit MIPS systems, the new environment variable settings -
- -GOMIPS64=hardfloat
(the default) and -GOMIPS64=softfloat
select whether to use - hardware instructions or software emulation for floating-point computations. - For 32-bit systems, the environment variable is stillGOMIPS
, - as added in Go 1.10. -- On soft-float ARM systems (
- -GOARM=5
), Go now uses a more - efficient software floating point interface. This is transparent to - Go code, but ARM assembly that uses floating-point instructions not - guarded on GOARM will break and must be ported to - the new interface. -- Go 1.11 on ARMv7 no longer requires a Linux kernel configured - with
- -KUSER_HELPERS
. This setting is enabled in default - kernel configurations, but is sometimes disabled in stripped-down - configurations. -WebAssembly
-- Go 1.11 adds an experimental port to WebAssembly - (
-js/wasm
). -- Go programs currently compile to one WebAssembly module that - includes the Go runtime for goroutine scheduling, garbage - collection, maps, etc. - As a result, the resulting size is at minimum around - 2 MB, or 500 KB compressed. Go programs can call into JavaScript - using the new experimental -
-syscall/js
package. - Binary size and interop with other languages has not yet been a - priority but may be addressed in future releases. -- As a result of the addition of the new
-GOOS
value - "js
" andGOARCH
value "wasm
", - Go files named*_js.go
or*_wasm.go
will - now be ignored by Go - tools except when those GOOS/GOARCH values are being used. - If you have existing filenames matching those patterns, you will need to rename them. -- More information can be found on the - WebAssembly wiki page. -
- -RISC-V GOARCH values reserved
-- The main Go compiler does not yet support the RISC-V architecture - but we've reserved the
- -GOARCH
values - "riscv
" and "riscv64
", as used by Gccgo, - which does support RISC-V. This means that Go files - named*_riscv.go
will now also - be ignored by Go - tools except when those GOOS/GOARCH values are being used. -Tools
- -Modules, package versioning, and dependency management
-- Go 1.11 adds preliminary support for a new concept called “modules,” - an alternative to GOPATH with integrated support for versioning and - package distribution. - Using modules, developers are no longer confined to working inside GOPATH, - version dependency information is explicit yet lightweight, - and builds are more reliable and reproducible. -
- -- Module support is considered experimental. - Details are likely to change in response to feedback from Go 1.11 users, - and we have more tools planned. - Although the details of module support may change, projects that convert - to modules using Go 1.11 will continue to work with Go 1.12 and later. - If you encounter bugs using modules, - please file issues - so we can fix them. For more information, see the -
- -go
command documentation. -Import path restriction
- -- Because Go module support assigns special meaning to the -
- -@
symbol in command line operations, - thego
command now disallows the use of - import paths containing@
symbols. - Such import paths were never allowed bygo
get
, - so this restriction can only affect users building - custom GOPATH trees by other means. -Package loading
- -- The new package -
- -golang.org/x/tools/go/packages
- provides a simple API for locating and loading packages of Go source code. - Although not yet part of the standard library, for many tasks it - effectively replaces thego/build
- package, whose API is unable to fully support modules. - Because it runs an external query command such as -go list
- to obtain information about Go packages, it enables the construction of - analysis tools that work equally well with alternative build systems - such as Bazel - and Buck. -Build cache requirement
- -- Go 1.11 will be the last release to support setting the environment - variable
- -GOCACHE=off
to disable the - build cache, - introduced in Go 1.10. - Starting in Go 1.12, the build cache will be required, - as a step toward eliminating$GOPATH/pkg
. - The module and package loading support described above - already require that the build cache be enabled. - If you have disabled the build cache to avoid problems you encountered, - please file an issue to let us know about them. -Compiler toolchain
- -- More functions are now eligible for inlining by default, including - functions that call
- -panic
. -- The compiler toolchain now supports column information - in line - directives. -
- -- A new package export data format has been introduced. - This should be transparent to end users, except for speeding up - build times for large Go projects. - If it does cause problems, it can be turned off again by - passing
- --gcflags=all=-iexport=false
to - thego
tool when building a binary. -- The compiler now rejects unused variables declared in a type switch - guard, such as
-x
in the following example: --func f(v interface{}) { - switch x := v.(type) { - } -} --- This was already rejected by both
- -gccgo
- and go/types. -Assembler
- -- The assembler for
- -amd64
now accepts AVX512 instructions. -Debugging
- -- The compiler now produces significantly more accurate debug - information for optimized binaries, including variable location - information, line numbers, and breakpoint locations. - - This should make it possible to debug binaries - compiled without
- --N
-l
. - - There are still limitations to the quality of the debug information, - some of which are fundamental, and some of which will continue to - improve with future releases. -- DWARF sections are now compressed by default because of the expanded - and more accurate debug information produced by the compiler. - - This is transparent to most ELF tools (such as debuggers on Linux - and *BSD) and is supported by the Delve debugger on all platforms, - but has limited support in the native tools on macOS and Windows. - - To disable DWARF compression, - pass
- --ldflags=-compressdwarf=false
to - thego
tool when building a binary. -- Go 1.11 adds experimental support for calling Go functions from - within a debugger. - - This is useful, for example, to call
- -String
methods - when paused at a breakpoint. - - This is currently only supported by Delve (version 1.1.0 and up). -Test
- -- Since Go 1.10, the
- -go
test
command runs -go
vet
on the package being tested, - to identify problems before running the test. Sincevet
- typechecks the code with go/types - before running, tests that do not typecheck will now fail. - - In particular, tests that contain an unused variable inside a - closure compiled with Go 1.10, because the Go compiler incorrectly - accepted them (Issue #3059), - but will now fail, sincego/types
correctly reports an - "unused variable" error in this case. -- The
- --memprofile
flag - togo
test
now defaults to the - "allocs" profile, which records the total bytes allocated since the - test began (including garbage-collected bytes). -Vet
- -- The
- -go
vet
- command now reports a fatal error when the package under analysis - does not typecheck. Previously, a type checking error simply caused - a warning to be printed, andvet
to exit with status 1. -- Additionally,
- -go
vet
- has become more robust when format-checkingprintf
wrappers. - Vet now detects the mistake in this example: --func wrapper(s string, args ...interface{}) { - fmt.Printf(s, args...) -} - -func main() { - wrapper("%s", 42) -} -- -Trace
- -- With the new
- -runtime/trace
- package's user - annotation API, users can record application-level information - in execution traces and create groups of related goroutines. - Thego
tool
trace
- command visualizes this information in the trace view and the new - user task/region analysis page. -Cgo
- --Since Go 1.10, cgo has translated some C pointer types to the Go -type
- -uintptr
. These types include -theCFTypeRef
hierarchy in Darwin's CoreFoundation -framework and thejobject
hierarchy in Java's JNI -interface. In Go 1.11, several improvements have been made to the code -that detects these types. Code that uses these types may need some -updating. See the Go 1.10 release notes for -details. -Go command
- -- The environment variable
- -GOFLAGS
may now be used - to set default flags for thego
command. - This is useful in certain situations. - Linking can be noticeably slower on underpowered systems due to DWARF, - and users may want to set-ldflags=-w
by default. - For modules, some users and CI systems will want vendoring always, - so they should set-mod=vendor
by default. - For more information, see thego
- command documentation. -Godoc
- -- Go 1.11 will be the last release to support
- -godoc
's command-line interface. - In future releases,godoc
will only be a web server. Users should use -go
doc
for command-line help output instead. -- The
- -godoc
web server now shows which version of Go introduced - new API features. The initial Go version of types, funcs, and methods are shown - right-aligned. For example, seeUserCacheDir
, with "1.11" - on the right side. For struct fields, inline comments are added when the struct field was - added in a Go version other than when the type itself was introduced. - For a struct field example, see -ClientTrace.Got1xxResponse
. -Gofmt
- -- One minor detail of the default formatting of Go source code has changed. - When formatting expression lists with inline comments, the comments were - aligned according to a heuristic. - However, in some cases the alignment would be split up too easily, or - introduce too much whitespace. - The heuristic has been changed to behave better for human-written code. -
- -- Note that these kinds of minor updates to gofmt are expected from time to - time. - In general, systems that need consistent formatting of Go source code should - use a specific version of the
- -gofmt
binary. - See the go/format package documentation for more - information. -Run
- -- - The
- -go
run
- command now allows a single import path, a directory name or a - pattern matching a single package. - This allowsgo
run
pkg
orgo
run
dir
, most importantlygo
run
.
-Runtime
- -- The runtime now uses a sparse heap layout so there is no longer a - limit to the size of the Go heap (previously, the limit was 512GiB). - This also fixes rare "address space conflict" failures in mixed Go/C - binaries or binaries compiled with
- --race
. -- On macOS and iOS, the runtime now uses
- -libSystem.dylib
instead of - calling the kernel directly. This should make Go binaries more - compatible with future versions of macOS and iOS. - The syscall package still makes direct - system calls; fixing this is planned for a future release. -Performance
- --As always, the changes are so general and varied that precise -statements about performance are difficult to make. Most programs -should run a bit faster, due to better generated code and -optimizations in the core library. -
- --There were multiple performance changes to the
- -math/big
-package as well as many changes across the tree specific toGOARCH=arm64
. -Compiler toolchain
- -- The compiler now optimizes map clearing operations of the form: -
--for k := range m { - delete(m, k) -} -- -- The compiler now optimizes slice extension of the form -
- -append(s,
make([]T,
n)...)
. -- The compiler now performs significantly more aggressive bounds-check - and branch elimination. Notably, it now recognizes transitive - relations, so if
- -i<j
andj<len(s)
, - it can use these facts to eliminate the bounds check - fors[i]
. It also understands simple arithmetic such - ass[i-10]
and can recognize more inductive cases in - loops. Furthermore, the compiler now uses bounds information to more - aggressively optimize shift operations. -Core library
- -- All of the changes to the standard library are minor. -
- -Minor changes to the library
- -- As always, there are various minor changes and updates to the library, - made with the Go 1 promise of compatibility - in mind. -
- - - - - - -- -
- crypto
-- -
- Certain crypto operations, including -
- -ecdsa.Sign
, -rsa.EncryptPKCS1v15
and -rsa.GenerateKey
, - now randomly read an extra byte of randomness to ensure tests don't rely on internal behavior. -- -
- crypto/cipher
-- -
- The new function
- -NewGCMWithTagSize
- implements Galois Counter Mode with non-standard tag lengths for compatibility with existing cryptosystems. -- -
- crypto/rsa
-- -
-
- -PublicKey
now implements a -Size
method that - returns the modulus size in bytes. -- -
- crypto/tls
-- -
-
- -ConnectionState
's new -ExportKeyingMaterial
- method allows exporting keying material bound to the - connection according to RFC 5705. -- - - -
- crypto/x509
-- -
- The deprecated, legacy behavior of treating the
- -CommonName
field as - a hostname when no Subject Alternative Names are present is now disabled when the CN is not a - valid hostname. - TheCommonName
can be completely ignored by adding the experimental value -x509ignoreCN=1
to theGODEBUG
environment variable. - When the CN is ignored, certificates without SANs validate under chains with name constraints - instead of returningNameConstraintsWithoutSANs
. -- Extended key usage restrictions are again checked only if they appear in the
- -KeyUsages
- field ofVerifyOptions
, instead of always being checked. - This matches the behavior of Go 1.9 and earlier. -- The value returned by
- -SystemCertPool
- is now cached and might not reflect system changes between invocations. -- -
- encoding/asn1
-- -
-
- -Marshal
andUnmarshal
- now support "private" class annotations for fields. -- -
- encoding/base32
-- -
- The decoder now consistently - returns
- -io.ErrUnexpectedEOF
for an incomplete - chunk. Previously it would returnio.EOF
in some - cases. -- - - -
- encoding/csv
-- -
- The
- -Reader
now rejects attempts to set - theComma
- field to a double-quote character, as double-quote characters - already have a special meaning in CSV. -- -
- html/template
-- -
- The package has changed its behavior when a typed interface - value is passed to an implicit escaper function. Previously such - a value was written out as (an escaped form) - of
- -<nil>
. Now such values are ignored, just - as an untypednil
value is (and always has been) - ignored. -- -
- image/gif
-- -
- Non-looping animated GIFs are now supported. They are denoted by having a -
- -LoopCount
of -1. -- -
- io/ioutil
-- -
- The
- -TempFile
- function now supports specifying where the random characters in - the filename are placed. If theprefix
argument - includes a "*
", the random string replaces the - "*
". For example, aprefix
argument of "myname.*.bat
" will - result in a random filename such as - "myname.123456.bat
". If no "*
" is - included the old behavior is retained, and the random digits are - appended to the end. -- -
- math/big
-- - -
-
- -ModInverse
now returns nil when g and n are not relatively prime. The result was previously undefined. -- -
- mime/multipart
-- -
- The handling of form-data with missing/empty file names has been - restored to the behavior in Go 1.9: in the -
- -Form
for - the form-data part the value is available in - theValue
field rather than theFile
- field. In Go releases 1.10 through 1.10.3 a form-data part with - a missing/empty file name and a non-empty "Content-Type" field - was stored in theFile
field. This change was a - mistake in 1.10 and has been reverted to the 1.9 behavior. -- -
- mime/quotedprintable
-- -
- To support invalid input found in the wild, the package now - permits non-ASCII bytes but does not validate their encoding. -
- -- -
- net
-- -
- The new
- -ListenConfig
type and the new -Dialer.Control
field permit - setting socket options before accepting and creating connections, respectively. -- The
- -syscall.RawConn
Read
- andWrite
methods now work correctly on Windows. -- The
- -net
package now automatically uses the -splice
system call - on Linux when copying data between TCP connections in -TCPConn.ReadFrom
, as called by -io.Copy
. The result is faster, more efficient TCP proxying. -- The
- -TCPConn.File
, -UDPConn.File
, -UnixConn.File
, - andIPConn.File
- methods no longer put the returned*os.File
into - blocking mode. -- -
- net/http
-- -
- The
- -Transport
type has a - newMaxConnsPerHost
- option that permits limiting the maximum number of connections - per host. -- The
- -Cookie
type has a new -SameSite
field - (of new type also named -SameSite
) to represent the new cookie attribute recently supported by most browsers. - Thenet/http
'sTransport
does not use theSameSite
- attribute itself, but the package supports parsing and serializing the - attribute for browsers to use. -- It is no longer allowed to reuse a
- - - -Server
- after a call to -Shutdown
or -Close
. It was never officially supported - in the past and had often surprising behavior. Now, all future calls to the server'sServe
- methods will return errors after a shutdown or close. -- The constant
- -StatusMisdirectedRequest
is now defined for HTTP status code 421. -- The HTTP server will no longer cancel contexts or send on -
- -CloseNotifier
- channels upon receiving pipelined HTTP/1.1 requests. Browsers do - not use HTTP pipelining, but some clients (such as - Debian'sapt
) may be configured to do so. --
- -ProxyFromEnvironment
, which is used by the -DefaultTransport
, now - supports CIDR notation and ports in theNO_PROXY
environment variable. -- -
- net/http/httputil
-- -
- The -
- -ReverseProxy
- has a new -ErrorHandler
- option to permit changing how errors are handled. -- The
- -ReverseProxy
now also passes - "TE:
trailers
" request headers - through to the backend, as required by the gRPC protocol. -- - - -
- os
-- -
- The new
- -UserCacheDir
function - returns the default root directory to use for user-specific cached data. -- The new
- -ModeIrregular
- is aFileMode
bit to represent - that a file is not a regular file, but nothing else is known about it, or that - it's not a socket, device, named pipe, symlink, or other file type for which - Go has a defined mode bit. --
- -Symlink
now works - for unprivileged users on Windows 10 on machines with Developer - Mode enabled. -- When a non-blocking descriptor is passed - to
- -NewFile
, the - resulting*File
will be kept in non-blocking - mode. This means that I/O for that*File
will use - the runtime poller rather than a separate thread, and that - theSetDeadline
- methods will work. -- - - -
- os/user
-- -
- The
- -os/user
package can now be built in pure Go - mode using the build tag "osusergo
", - independent of the use of the environment - variableCGO_ENABLED=0
. Previously the only way to use - the package's pure Go implementation was to disablecgo
- support across the entire program. -- -
- runtime
-- - -
- Setting the
- -GODEBUG=tracebackancestors=N
- environment variable now extends tracebacks with the stacks at - which goroutines were created, where N limits the - number of ancestor goroutines to report. -- -
- runtime/pprof
-- -
- This release adds a new "allocs" profile type that profiles - total number of bytes allocated since the program began - (including garbage-collected bytes). This is identical to the - existing "heap" profile viewed in
- --alloc_space
mode. - Nowgo test -memprofile=...
reports an "allocs" profile - instead of "heap" profile. -- -
- sync
-- -
- The mutex profile now includes reader/writer contention - for
- -RWMutex
. - Writer/writer contention was already included in the mutex - profile. -- -
- syscall
-- -
- On Windows, several fields were changed from
- -uintptr
to a new -Pointer
- type to avoid problems with Go's garbage collector. The same change was made - to thegolang.org/x/sys/windows
- package. For any code affected, users should first migrate away from thesyscall
- package to thegolang.org/x/sys/windows
package, and then change - to using thePointer
, while obeying the -unsafe.Pointer
conversion rules. -- On Linux, the
- -flags
parameter to -Faccessat
- is now implemented just as in glibc. In earlier Go releases the - flags parameter was ignored. -- On Linux, the
- -flags
parameter to -Fchmodat
- is now validated. Linux'sfchmodat
doesn't support theflags
parameter - so we now mimic glibc's behavior and return an error if it's non-zero. -- -
- text/scanner
-- -
- The
- -Scanner.Scan
method now returns - theRawString
token - instead ofString
- for raw string literals. -- -
- text/template
-- -
- Modifying template variables via assignments is now permitted via the
-=
token: -- {{"{{"}} $v := "init" {{"}}"}} - {{"{{"}} if true {{"}}"}} - {{"{{"}} $v = "changed" {{"}}"}} - {{"{{"}} end {{"}}"}} - v: {{"{{"}} $v {{"}}"}} {{"{{"}}/* "changed" */{{"}}"}}- -- In previous versions untyped
- -nil
values passed to - template functions were ignored. They are now passed as normal - arguments. -diff --git a/content/doc/go1.12.html b/content/doc/go1.12.html deleted file mode 100644 index d8547e9f..00000000 --- a/content/doc/go1.12.html +++ /dev/null @@ -1,830 +0,0 @@ - - - - - - -
- time
-- -
- Parsing of timezones denoted by sign and offset is now - supported. In previous versions, numeric timezone names - (such as
-+03
) were not considered valid, and only - three-letter abbreviations (such asMST
) were accepted - when expecting a timezone name. -DRAFT RELEASE NOTES - Introduction to Go 1.12
- -- - Go 1.12 is not yet released. These are work-in-progress - release notes. Go 1.12 is expected to be released in February 2019. - -
- -- The latest Go release, version 1.12, arrives six months after Go 1.11. - Most of its changes are in the implementation of the toolchain, runtime, and libraries. - As always, the release maintains the Go 1 promise of compatibility. - We expect almost all Go programs to continue to compile and run as before. -
- -Changes to the language
- -- There are no changes to the language specification. -
- -Ports
- -- The race detector is now supported on
- -linux/arm64
. -- Go 1.12 is the last release that is supported on FreeBSD 10.x, which has - already reached end-of-life. Go 1.13 will require FreeBSD 11.2+ or FreeBSD - 12.0+. -
- -- cgo is now supported on
- -linux/ppc64
. --
- -hurd
is now a recognized value forGOOS
, reserved - for the GNU/Hurd system for use withgccgo
. -Windows
- -- Go's new
- -windows/arm
port supports running Go on Windows 10 - IoT Core on 32-bit ARM chips such as the Raspberry Pi 3. -AIX
- -- Go now supports AIX 7.2 and later on POWER8 architectures (
- -aix/ppc64
). External linking, cgo, pprof and the race detector aren't yet supported. -Darwin
- -- Go 1.12 is the last release that will run on macOS 10.10 Yosemite. - Go 1.13 will require macOS 10.11 El Capitan or later. -
- --
- -libSystem
is now used when making syscalls on Darwin, - ensuring forward-compatibility with future versions of macOS and iOS. - - The switch tolibSystem
triggered additional App Store - checks for private API usage. Since it is considered private, -syscall.Getdirentries
now always fails with -ENOSYS
on iOS. -Tools
- -- -
go tool vet
no longer supported- The
- -go vet
command has been rewritten to serve as the - base for a range of different source code analysis tools. See - the golang.org/x/tools/go/analysis - package for details. A side-effect is thatgo tool vet
- is no longer supported. External tools that usego tool - vet
must be changed to usego - vet
. Usinggo vet
instead ofgo tool - vet
should work with all supported versions of Go. -- As part of this change, the experimental
-shadow
option - is no longer available withgo vet
. Checking for - variable shadowing may now be done using --go install golang.org/x/tools/go/analysis/passes/shadow/cmd/shadow -go vet -vettool=$(which shadow) --Build cache requirement
- -- The build cache is now - required as a step toward eliminating -
- -$GOPATH/pkg
. Setting the environment variable -GOCACHE=off
will causego
commands that write to the - cache to fail. -Binary-only packages
- -- Go 1.12 is the last release that will support binary-only packages. -
- -Cgo
- -- Go 1.12 will translate the C type
- -EGLDisplay
to the Go typeuintptr
. - This change is similar to how Go 1.10 and newer treats Darwin's CoreFoundation - and Java's JNI types. See the - cgo documentation - for more information. -Modules
- -- When
- -GO111MODULE
is set toon
, thego
- command now supports module-aware operations outside of a module directory, - provided that those operations do not need to resolve import paths relative to - the current directory or explicitly edit thego.mod
file. - Commands such asgo
get
, -go
list
, and -go
mod
download
behave as if in a - module with initially-empty requirements. - In this mode,go
env
GOMOD
reports - the system's null device (/dev/null
orNUL
). --
- -go
commands that download and extract modules are now safe to - invoke concurrently. - The module cache (GOPATH/pkg/mod
) must reside in a filesystem that - supports file locking. -- The
- -go
directive in ago.mod
file now indicates the - version of the language used by the files within that module, and -go
mod
tidy
sets it to the - current release (go
1.12
) if no existing - version is present. - If thego
directive for a module specifies a - version newer than the toolchain in use, thego
command - will attempt to build the packages regardless, and will note the mismatch only if - that build fails. -- When an import cannot be resolved using the active modules, - the
- -go
command will now try to use the modules mentioned in the - main module'sreplace
directives before consulting the module - cache and the usual network sources. - If a matching replacement is found but thereplace
directive does - not specify a version, thego
command uses a pseudo-version - derived from the zerotime.Time
(such - asv0.0.0-00010101000000-000000000000
). -Compiler toolchain
- -- The compiler's live variable analysis has improved. This may mean that - finalizers will be executed sooner in this release than in previous - releases. If that is a problem, consider the appropriate addition of a -
- -runtime.KeepAlive
call. -- More functions are now eligible for inlining by default, including - functions that do nothing but call another function. - This extra inlining makes it additionally important to use -
runtime.CallersFrames
- instead of iterating over the result of -runtime.Callers
directly. --// Old code which no longer works correctly (it will miss inlined call frames). -var pcs [10]uintptr -n := runtime.Callers(1, pcs[:]) -for _, pc := range pcs[:n] { - f := runtime.FuncForPC(pc) - if f != nil { - fmt.Println(f.Name()) - } -} ---// New code which will work correctly. -var pcs [10]uintptr -n := runtime.Callers(1, pcs[:]) -frames := runtime.CallersFrames(pcs[:n]) -for { - frame, more := frames.Next() - fmt.Println(frame.Function) - if !more { - break - } -} --- The compiler now accepts a
- --lang
flag to set the Go language - version to use. For example,-lang=go1.8
causes the compiler to - emit an error if the program uses type aliases, which were added in Go 1.9. - Language changes made before Go 1.12 are not consistently enforced. -- The compiler toolchain now uses different conventions to call Go - functions and assembly functions. This should be invisible to users, - except for calls that simultaneously cross between Go and - assembly and cross a package boundary. If linking results - in an error like "relocation target not defined for ABIInternal (but - is defined for ABI0)", please refer to help section of the ABI - design document. - -
- -- There have been many improvements to the DWARF debug information - produced by the compiler, including improvements to argument - printing and variable location information. -
- -- Go programs now also maintain stack frame pointers on
- -linux/arm64
- for the benefit of profiling tools likeperf
. The frame pointer - maintenance has a small run-time overhead that varies but averages around 3%. - To build a toolchain that does not use frame pointers, set -GOEXPERIMENT=noframepointer
when runningmake.bash
. -- The obsolete "safe" compiler mode (enabled by the
- --u
gcflag) has been removed. -- -
godoc
andgo
doc
- In Go 1.12,
- -godoc
no longer has a command-line interface and - is only a web server. Users should usego
doc
- for command-line help output instead. --
- -go
doc
now supports the-all
flag, - which will cause it to print all exported APIs and their documentation, - as thegodoc
command line used to do. -Trace
- -- The trace tool now supports plotting mutator utilization curves, - including cross-references to the execution trace. These are useful - for analyzing the impact of the garbage collector on application - latency and throughput. -
- -Assembler
- -- On
- -arm64
, the platform register was renamed from -R18
toR18_PLATFORM
to prevent accidental - use, as the OS could choose to reserve this register. -Runtime
- -- Go 1.12 significantly improves the performance of sweeping when a - large fraction of the heap remains live. This reduces allocation - latency immediately following a garbage collection. -
- -- The Go runtime now releases memory back to the operating system more - aggressively, particularly in response to large allocations that - can't reuse existing heap space. -
- -- The Go runtime's timer and deadline code is faster and scales better - with higher numbers of CPUs. In particular, this improves the - performance of manipulating network connection deadlines. -
- -- On Linux, the runtime now uses
- -MADV_FREE
to release unused - memory. This is more efficient but may result in higher reported - RSS. The kernel will reclaim the unused data when it is needed. - To revert to the Go 1.11 behavior (MADV_DONTNEED
), set the - environment variableGODEBUG=madvdontneed=1
. -- Adding cpu.extension=off to the - GODEBUG environment - variable now disables the use of optional CPU instruction - set extensions in the standard library and runtime. This is not - yet supported on Windows. -
- -Core library
- -TLS 1.3
- -- Go 1.12 adds support in the
- -crypto/tls
package for TLS 1.3 as - specified in RFC 8446. - - Programs that did not set an explicitMaxVersion
in -Config
will automatically negotiate - TLS 1.3 if available. All TLS 1.2 features exceptTLSUnique
in -ConnectionState
- and renegotiation are available in TLS 1.3 and provide equivalent or - better security and performance. -- TLS 1.3 cipher suites are not configurable. All supported cipher suites are - safe, and if
- -PreferServerCipherSuites
is set in -Config
the preference order - is based on the available hardware. -- Early data (also called "0-RTT mode") is not currently supported as a - client or server. Additionally, a Go 1.12 server does not support skipping - unexpected early data if a client sends it. Since TLS 1.3 0-RTT mode - involves clients keeping state regarding which servers support 0-RTT, - a Go 1.12 server cannot be part of a load-balancing pool where some other - servers do support 0-RTT. If switching a domain from a server that supported - 0-RTT to a Go 1.12 server, 0-RTT would have to be disabled for at least the - lifetime of the issued session tickets before the switch to ensure - uninterrupted operation. -
- -- In TLS 1.3 the client is the last one to speak in the handshake, so if it causes - an error to occur on the server, it will be returned on the client by the first -
- -Read
, not by -Handshake
. For - example, that will be the case if the server rejects the client certificate. - Similarly, session tickets are now post-handshake messages, so are only - received by the client upon its first -Read
. -Minor changes to the library
- -- As always, there are various minor changes and updates to the library, - made with the Go 1 promise of compatibility - in mind. -
- - - -- -
- bufio
-- -
-
- -Reader
'sUnreadRune
and -UnreadByte
methods will now return an error - if they are called afterPeek
. -- -
- bytes
-- -
- The new function
- -ReplaceAll
returns a copy of - a byte slice with all non-overlapping instances of a value replaced by another. -- A pointer to a zero-value
- -Reader
is now - functionally equivalent toNewReader
(nil)
. - Prior to Go 1.12, the former could not be used as a substitute for the latter in all cases. -- -
- crypto/rand
-- -
- A warning will now be printed to standard error the first time -
- -Reader.Read
is blocked for more than 60 seconds waiting - to read entropy from the kernel. -- On FreeBSD,
- -Reader
now uses thegetrandom
- system call if available,/dev/urandom
otherwise. -- -
- crypto/rc4
-- -
- This release removes the optimized assembly implementations. RC4 is insecure - and should only be used for compatibility with legacy systems. -
- -- -
- crypto/tls
-- -
- TLS 1.2 clients and servers will now advertise and accept RSA-PSS - signature algorithms for use with regular RSA public keys. -
- -- If a client sends an initial message that does not look like TLS, the server - will no longer reply with an alert, and it will expose the underlying -
- -net.Conn
in the new fieldConn
of -RecordHeaderError
. -- - - -
- database/sql
-- -
- A query cursor can now be obtained by passing a -
- -*Rows
- value to theRow.Scan
method. -
- fmt
-- -
- Maps are now printed in key-sorted order to ease testing. The ordering rules are: -
-
-- When applicable, nil compares low -
- ints, floats, and strings order by < -
- NaN compares less than non-NaN floats -
- bool compares false before true -
- Complex compares real, then imaginary -
- Pointers compare by machine address -
- Channel values compare by machine address -
- Structs compare each field in turn -
- Arrays compare each element in turn -
- Interface values compare first by
reflect.Type
describing the concrete type - and then by concrete value as described in the previous rules. -- When printing maps, non-reflexive key values like
- - - -NaN
were previously - displayed as<nil>
. As of this release, the correct values are printed. -- -
- go/doc
-- -
- To address some outstanding issues in
- -cmd/doc
, - this package has a newMode
bit, -PreserveAST
, which controls whether AST data is cleared. -- -
- go/token
-- -
- The
- -File
type has a new -LineStart
field, - which returns the position of the start of a given line. This is especially useful - in programs that occasionally handle non-Go files, such as assembly, but wish to use - thetoken.Pos
mechanism to identify file positions. -- -
- image
-- -
- The
- -RegisterFormat
function is now safe for concurrent use. -- -
- image/png
-- -
- Paletted images with fewer than 16 colors now encode to smaller outputs. -
- -- -
- io
-- -
- The new
- -StringWriter
interface wraps the -WriteString
function. -- -
- lib/time
-- -
- The time zone database in
- -$GOROOT/lib/time/zoneinfo.zip
has been updated to version 2018g. Note that this ZIP file is only used if a time zone database is not provided by the operating system. -- -
- math/bits
-- -
- New extended precision operations
- -Add
,Sub
,Mul
, andDiv
are available inuint
,uint32
, anduint64
versions. -- -
- net
-- -
- The -
- -Dialer.DualStack
setting is now ignored and deprecated; - RFC 6555 Fast Fallback ("Happy Eyeballs") is now enabled by default. To disable, set -Dialer.FallbackDelay
to a negative value. -- Similarly, TCP keep-alives are now enabled by default if -
- -Dialer.KeepAlive
is zero. - To disable, set it to a negative value. -- On Linux, the
-splice
system call is now used when copying from a -UnixConn
to a -TCPConn
. -- -
- net/http
-- -
- The HTTP server now rejects misdirected HTTP requests to HTTPS servers with a plaintext "400 Bad Request" response. -
- -- The new
- -Client.CloseIdleConnections
- method calls theClient
's underlyingTransport
'sCloseIdleConnections
- if it has one. -- The
- -Transport
no longer rejects HTTP responses which declare - HTTP Trailers but don't use chunked encoding. Instead, the declared trailers are now just ignored. -- The
- -Transport
no longer handlesMAX_CONCURRENT_STREAMS
values - advertised from HTTP/2 servers as strictly as it did during Go 1.10 and Go 1.11. The default behavior is now back - to how it was in Go 1.9: each connection to a server can have up toMAX_CONCURRENT_STREAMS
requests - active and then new TCP connections are created as needed. In Go 1.10 and Go 1.11 thehttp2
package - would block and wait for requests to finish instead of creating new connections. - To get the stricter behavior back, import the -golang.org/x/net/http2
package - directly and set -Transport.StrictMaxConcurrentStreams
to -true
. -- -
- net/http/httputil
-- -
- The
- -ReverseProxy
now automatically - proxies WebSocket requests. -- -
- os
-- -
- The new
- -ProcessState.ExitCode
method - returns the process's exit code. --
- -ModeCharDevice
has been added to theModeType
bitmask, allowing for -ModeDevice | ModeCharDevice
to be recovered when masking a -FileMode
withModeType
. -- The new function
- -UserHomeDir
returns the - current user's home directory. --
- -RemoveAll
now supports paths longer than 4096 characters - on most Unix systems. --
- -File.Sync
now usesF_FULLFSYNC
on macOS - to correctly flush the file contents to permanent storage. - This may cause the method to run more slowly than in previous releases. -- -
- path/filepath
-- -
- The
- -IsAbs
function now returns true when passed - a reserved filename on Windows such asNUL
. - List of reserved names. -- -
- reflect
-- -
- A new
- -MapIter
type is - an iterator for ranging over a map. This type is exposed through the -Value
type's new -MapRange
method. - This follows the same iteration semantics as a range statement, withNext
- to advance the iterator, andKey
/Value
to access each entry. -- -
- regexp
-- -
-
- -Copy
is no longer necessary - to avoid lock contention, so it has been given a partial deprecation comment. -Copy
- may still be appropriate if the reason for its use is to make two copies with - differentLongest
settings. -- -
- runtime/debug
-- -
- A new
- -BuildInfo
type - exposes the build information read from the running binary, available only in - binaries built with module support. This includes the main package path, main - module information, and the module dependencies. This type is given though the -ReadBuildInfo
function - onBuildInfo
. -- -
- strings
-- -
- The new function
- -ReplaceAll
returns a copy of - a string with all non-overlapping instances of a value replaced by another. -- A pointer to a zero-value
- -Reader
is now - functionally equivalent toNewReader
(nil)
. - Prior to Go 1.12, the former could not be used as a substitute for the latter in all cases. -- The new
- -Builder.Cap
method returns the capacity of the builder's underlying byte slice. -- The character mapping functions
- -Map
, -Title
, -ToLower
, -ToLowerSpecial
, -ToTitle
, -ToTitleSpecial
, -ToUpper
, and -ToUpperSpecial
- now always guarantee to return valid UTF-8. In earlier releases, if the input was invalid UTF-8 but no character replacements - needed to be applied, these routines incorrectly returned the invalid UTF-8 unmodified. -- -
- syscall
-- -
- 64-bit inodes are now supported on FreeBSD 12. Some types have been adjusted accordingly. -
- -- The Unix socket - (
- -AF_UNIX
) - address family is now supported for compatible versions of Windows. -- The new function
- -Syscall18
- has been introduced for Windows, allowing for calls with up to 18 arguments. -- -
- syscall/js
-- -
-
- The
- -Callback
type andNewCallback
function have been renamed; - they are now called -Func
and -FuncOf
, respectively. - This is a breaking change, but WebAssembly support is still experimental - and not yet subject to the - Go 1 compatibility promise. Any code using the - old names will need to be updated. -- If a type implements the new -
- -Wrapper
- interface, -ValueOf
- will use it to return the JavaScript value for that type. -- The meaning of the zero -
- -Value
- has changed. It now represents the JavaScriptundefined
value - instead of the number zero. - This is a breaking change, but WebAssembly support is still experimental - and not yet subject to the - Go 1 compatibility promise. Any code relying on - the zeroValue
- to mean the number zero will need to be updated. -- The new -
- -Value.Truthy
- method reports the - JavaScript "truthiness" - of a given value. -- -
- testing
-- -
- The
- --benchtime
flag now supports setting an explicit iteration count instead of a time when the value ends with an "x
". For example,-benchtime=100x
runs the benchmark 100 times. -- -
- text/template
-- -
- When executing a template, long context values are no longer truncated in errors. -
--
-executing "tmpl" at <.very.deep.context.v...>: map has no entry for key "notpresent"
-- is now -
--
- -executing "tmpl" at <.very.deep.context.value.notpresent>: map has no entry for key "notpresent"
-diff --git a/content/doc/go1.2.html b/content/doc/go1.2.html deleted file mode 100644 index 1f605141..00000000 --- a/content/doc/go1.2.html +++ /dev/null @@ -1,979 +0,0 @@ - - -
- unsafe
-- -
- It is invalid to convert a nil
- -unsafe.Pointer
touintptr
and back with arithmetic. - (This was already invalid, but will now cause the compiler to misbehave.) -Introduction to Go 1.2
- --Since the release of Go version 1.1 in April, 2013, -the release schedule has been shortened to make the release process more efficient. -This release, Go version 1.2 or Go 1.2 for short, arrives roughly six months after 1.1, -while 1.1 took over a year to appear after 1.0. -Because of the shorter time scale, 1.2 is a smaller delta than the step from 1.0 to 1.1, -but it still has some significant developments, including -a better scheduler and one new language feature. -Of course, Go 1.2 keeps the promise -of compatibility. -The overwhelming majority of programs built with Go 1.1 (or 1.0 for that matter) -will run without any changes whatsoever when moved to 1.2, -although the introduction of one restriction -to a corner of the language may expose already-incorrect code -(see the discussion of the use of nil). -
- -Changes to the language
- --In the interest of firming up the specification, one corner case has been clarified, -with consequences for programs. -There is also one new language feature. -
- -Use of nil
- --The language now specifies that, for safety reasons, -certain uses of nil pointers are guaranteed to trigger a run-time panic. -For instance, in Go 1.0, given code like -
- --type T struct { - X [1<<24]byte - Field int32 -} - -func main() { - var x *T - ... -} -- --the
- -nil
pointerx
could be used to access memory incorrectly: -the expressionx.Field
could access memory at address1<<24
. -To prevent such unsafe behavior, in Go 1.2 the compilers now guarantee that any indirection through -a nil pointer, such as illustrated here but also in nil pointers to arrays, nil interface values, -nil slices, and so on, will either panic or return a correct, safe non-nil value. -In short, any expression that explicitly or implicitly requires evaluation of a nil address is an error. -The implementation may inject extra tests into the compiled program to enforce this behavior. --Further details are in the -design document. -
- --Updating: -Most code that depended on the old behavior is erroneous and will fail when run. -Such programs will need to be updated by hand. -
- -Three-index slices
- --Go 1.2 adds the ability to specify the capacity as well as the length when using a slicing operation -on an existing array or slice. -A slicing operation creates a new slice by describing a contiguous section of an already-created array or slice: -
- --var array [10]int -slice := array[2:4] -- --The capacity of the slice is the maximum number of elements that the slice may hold, even after reslicing; -it reflects the size of the underlying array. -In this example, the capacity of the
- -slice
variable is 8. --Go 1.2 adds new syntax to allow a slicing operation to specify the capacity as well as the length. -A second -colon introduces the capacity value, which must be less than or equal to the capacity of the -source slice or array, adjusted for the origin. For instance, -
- --slice = array[2:4:7] -- --sets the slice to have the same length as in the earlier example but its capacity is now only 5 elements (7-2). -It is impossible to use this new slice value to access the last three elements of the original array. -
- --In this three-index notation, a missing first index (
- -[:i:j]
) defaults to zero but the other -two indices must always be specified explicitly. -It is possible that future releases of Go may introduce default values for these indices. --Further details are in the -design document. -
- --Updating: -This is a backwards-compatible change that affects no existing programs. -
- -Changes to the implementations and tools
- -Pre-emption in the scheduler
- --In prior releases, a goroutine that was looping forever could starve out other -goroutines on the same thread, a serious problem when GOMAXPROCS -provided only one user thread. -In Go 1.2, this is partially addressed: The scheduler is invoked occasionally -upon entry to a function. -This means that any loop that includes a (non-inlined) function call can -be pre-empted, allowing other goroutines to run on the same thread. -
- -Limit on the number of threads
- --Go 1.2 introduces a configurable limit (default 10,000) to the total number of threads -a single program may have in its address space, to avoid resource starvation -issues in some environments. -Note that goroutines are multiplexed onto threads so this limit does not directly -limit the number of goroutines, only the number that may be simultaneously blocked -in a system call. -In practice, the limit is hard to reach. -
- --The new
- -SetMaxThreads
function in the -runtime/debug
package controls the thread count limit. --Updating: -Few functions will be affected by the limit, but if a program dies because it hits the -limit, it could be modified to call
- -SetMaxThreads
to set a higher count. -Even better would be to refactor the program to need fewer threads, reducing consumption -of kernel resources. -Stack size
- --In Go 1.2, the minimum size of the stack when a goroutine is created has been lifted from 4KB to 8KB. -Many programs were suffering performance problems with the old size, which had a tendency -to introduce expensive stack-segment switching in performance-critical sections. -The new number was determined by empirical testing. -
- --At the other end, the new function
- -SetMaxStack
-in theruntime/debug
package controls -the maximum size of a single goroutine's stack. -The default is 1GB on 64-bit systems and 250MB on 32-bit systems. -Before Go 1.2, it was too easy for a runaway recursion to consume all the memory on a machine. --Updating: -The increased minimum stack size may cause programs with many goroutines to use -more memory. There is no workaround, but plans for future releases -include new stack management technology that should address the problem better. -
- -Cgo and C++
- --The
- -cgo
command will now invoke the C++ -compiler to build any pieces of the linked-to library that are written in C++; -the documentation has more detail. -Godoc and vet moved to the go.tools subrepository
- --Both binaries are still included with the distribution, but the source code for the -godoc and vet commands has moved to the -go.tools subrepository. -
- --Also, the core of the godoc program has been split into a -library, -while the command itself is in a separate -directory. -The move allows the code to be updated easily and the separation into a library and command -makes it easier to construct custom binaries for local sites and different deployment methods. -
- --Updating: -Since godoc and vet are not part of the library, -no client Go code depends on the their source and no updating is required. -
- --The binary distributions available from golang.org -include these binaries, so users of these distributions are unaffected. -
- --When building from source, users must use "go get" to install godoc and vet. -(The binaries will continue to be installed in their usual locations, not -
- -$GOPATH/bin
.) --$ go get code.google.com/p/go.tools/cmd/godoc -$ go get code.google.com/p/go.tools/cmd/vet -- -Status of gccgo
- --We expect the future GCC 4.9 release to include gccgo with full -support for Go 1.2. -In the current (4.8.2) release of GCC, gccgo implements Go 1.1.2. -
- -Changes to the gc compiler and linker
- --Go 1.2 has several semantic changes to the workings of the gc compiler suite. -Most users will be unaffected by them. -
- --The
- -cgo
command now -works when C++ is included in the library being linked against. -See thecgo
documentation -for details. --The gc compiler displayed a vestigial detail of its origins when -a program had no
- -package
clause: it assumed -the file was in packagemain
. -The past has been erased, and a missingpackage
clause -is now an error. --On the ARM, the toolchain supports "external linking", which -is a step towards being able to build shared libraries with the gc -toolchain and to provide dynamic linking support for environments -in which that is necessary. -
- --In the runtime for the ARM, with
- -5a
, it used to be possible to refer -to the runtime-internalm
(machine) andg
-(goroutine) variables usingR9
andR10
directly. -It is now necessary to refer to them by their proper names. --Also on the ARM, the
- -5l
linker (sic) now defines the -MOVBS
andMOVHS
instructions -as synonyms ofMOVB
andMOVH
, -to make clearer the separation between signed and unsigned -sub-word moves; the unsigned versions already existed with a -U
suffix. -Test coverage
- --One major new feature of
- -go test
is -that it can now compute and, with help from a new, separately installed -"go tool cover" program, display test coverage results. --The cover tool is part of the -
- -go.tools
-subrepository. -It can be installed by running --$ go get code.google.com/p/go.tools/cmd/cover -- --The cover tool does two things. -First, when "go test" is given the
- --cover
flag, it is run automatically -to rewrite the source for the package and insert instrumentation statements. -The test is then compiled and run as usual, and basic coverage statistics are reported: --$ go test -cover fmt -ok fmt 0.060s coverage: 91.4% of statements -$ -- --Second, for more detailed reports, different flags to "go test" can create a coverage profile file, -which the cover program, invoked with "go tool cover", can then analyze. -
- --Details on how to generate and analyze coverage statistics can be found by running the commands -
- --$ go help testflag -$ go tool cover -help -- -The go doc command is deleted
- --The "go doc" command is deleted. -Note that the
- -godoc
tool itself is not deleted, -just the wrapping of it by thego
command. -All it did was show the documents for a package by package path, -which godoc itself already does with more flexibility. -It has therefore been deleted to reduce the number of documentation tools and, -as part of the restructuring of godoc, encourage better options in future. --Updating: For those who still need the precise functionality of running -
- --$ go doc -- --in a directory, the behavior is identical to running -
- --$ godoc . -- -Changes to the go command
- --The
- -go get
command -now has a-t
flag that causes it to download the dependencies -of the tests run by the package, not just those of the package itself. -By default, as before, dependencies of the tests are not downloaded. -Performance
- --There are a number of significant performance improvements in the standard library; here are a few of them. -
- -- -
- -- -The
- -compress/bzip2
-decompresses about 30% faster. -- -The
- -crypto/des
package -is about five times faster. -- -The
- -encoding/json
package -encodes about 30% faster. -- -Networking performance on Windows and BSD systems is about 30% faster through the use -of an integrated network poller in the runtime, similar to what was done for Linux and OS X -in Go 1.1. -
- -Changes to the standard library
- - -The archive/tar and archive/zip packages
- --The -
- -archive/tar
-and -archive/zip
-packages have had a change to their semantics that may break existing programs. -The issue is that they both provided an implementation of the -os.FileInfo
-interface that was not compliant with the specification for that interface. -In particular, theirName
method returned the full -path name of the entry, but the interface specification requires that -the method return only the base name (final path element). --Updating: Since this behavior was newly implemented and -a bit obscure, it is possible that no code depends on the broken behavior. -If there are programs that do depend on it, they will need to be identified -and fixed manually. -
- -The new encoding package
- --There is a new package,
- -encoding
, -that defines a set of standard encoding interfaces that may be used to -build custom marshalers and unmarshalers for packages such as -encoding/xml
, -encoding/json
, -and -encoding/binary
. -These new interfaces have been used to tidy up some implementations in -the standard library. --The new interfaces are called -
- -BinaryMarshaler
, -BinaryUnmarshaler
, -TextMarshaler
, -and -TextUnmarshaler
. -Full details are in the documentation for the package -and a separate design document. -The fmt package
- --The
- -fmt
package's formatted print -routines such asPrintf
-now allow the data items to be printed to be accessed in arbitrary order -by using an indexing operation in the formatting specifications. -Wherever an argument is to be fetched from the argument list for formatting, -either as the value to be formatted or as a width or specification integer, -a new optional indexing notation[
n]
-fetches argument n instead. -The value of n is 1-indexed. -After such an indexing operating, the next argument to be fetched by normal -processing will be n+1. --For example, the normal
- -Printf
call --fmt.Sprintf("%c %c %c\n", 'a', 'b', 'c') -- --would create the string
- -"a b c"
, but with indexing operations like this, --fmt.Sprintf("%[3]c %[1]c %c\n", 'a', 'b', 'c') -- --the result is "
- -"c a b"
. The[3]
index accesses the third formatting -argument, which is'c'
,[1]
accesses the first,'a'
, -and then the next fetch accesses the argument following that one,'b'
. --The motivation for this feature is programmable format statements to access -the arguments in different order for localization, but it has other uses: -
- --log.Printf("trace: value %v of type %[1]T\n", expensiveFunction(a.b[c])) -- --Updating: The change to the syntax of format specifications -is strictly backwards compatible, so it affects no working programs. -
- -The text/template and html/template packages
- --The -
- -text/template
package -has a couple of changes in Go 1.2, both of which are also mirrored in the -html/template
package. --First, there are new default functions for comparing basic types. -The functions are listed in this table, which shows their names and -the associated familiar comparison operator. -
- --
- -- -Name Operator -- -eq
- ==
- -ne
- !=
- -lt
- <
- -le
- <=
- -gt
- >
- -ge
- >=
-These functions behave slightly differently from the corresponding Go operators. -First, they operate only on basic types (
- -bool
,int
, -float64
,string
, etc.). -(Go allows comparison of arrays and structs as well, under some circumstances.) -Second, values can be compared as long as they are the same sort of value: -any signed integer value can be compared to any other signed integer value for example. (Go -does not permit comparing anint8
and anint16
). -Finally, theeq
function (only) allows comparison of the first -argument with one or more following arguments. The template in this example, --{{"{{"}}if eq .A 1 2 3 {{"}}"}} equal {{"{{"}}else{{"}}"}} not equal {{"{{"}}end{{"}}"}} -- --reports "equal" if
- -.A
is equal to any of 1, 2, or 3. --The second change is that a small addition to the grammar makes "if else if" chains easier to write. -Instead of writing, -
- --{{"{{"}}if eq .A 1{{"}}"}} X {{"{{"}}else{{"}}"}} {{"{{"}}if eq .A 2{{"}}"}} Y {{"{{"}}end{{"}}"}} {{"{{"}}end{{"}}"}} -- --one can fold the second "if" into the "else" and have only one "end", like this: -
- --{{"{{"}}if eq .A 1{{"}}"}} X {{"{{"}}else if eq .A 2{{"}}"}} Y {{"{{"}}end{{"}}"}} -- --The two forms are identical in effect; the difference is just in the syntax. -
- --Updating: Neither the "else if" change nor the comparison functions -affect existing programs. Those that -already define functions called
- -eq
and so on through a function -map are unaffected because the associated function map will override the new -default function definitions. -New packages
- --There are two new packages. -
- --
- -- -The
-encoding
package is -described above. -- -The
-image/color/palette
package -provides standard color palettes. -Minor changes to the library
- --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. -
- -- -
diff --git a/content/doc/go1.3.html b/content/doc/go1.3.html deleted file mode 100644 index 18c638a1..00000000 --- a/content/doc/go1.3.html +++ /dev/null @@ -1,608 +0,0 @@ - - -- -The
- -archive/zip
package -adds the -DataOffset
accessor -to return the offset of a file's (possibly compressed) data within the archive. -- -The
- -bufio
package -addsReset
-methods toReader
and -Writer
. -These methods allow theReaders
-andWriters
-to be re-used on new input and output readers and writers, saving -allocation overhead. -- -The
- -compress/bzip2
-can now decompress concatenated archives. -- -The
- -compress/flate
-package adds aReset
-method on theWriter
, -to make it possible to reduce allocation when, for instance, constructing an -archive to hold multiple compressed files. -- -The
- -compress/gzip
package's -Writer
type adds a -Reset
-so it may be reused. -- -The
- -compress/zlib
package's -Writer
type adds a -Reset
-so it may be reused. -- -The
- -container/heap
package -adds aFix
-method to provide a more efficient way to update an item's position in the heap. -- -The
- -container/list
package -adds theMoveBefore
-and -MoveAfter
-methods, which implement the obvious rearrangement. -- -The
- -crypto/cipher
package -adds the a new GCM mode (Galois Counter Mode), which is almost always -used with AES encryption. -- -The -
- -crypto/md5
package -adds a newSum
function -to simplify hashing without sacrificing performance. -- -Similarly, the -
- -crypto/sha1
package -adds a newSum
function. -- -Also, the -
- -crypto/sha256
package -addsSum256
-andSum224
functions. -- -Finally, the
- -crypto/sha512
package -addsSum512
and -Sum384
functions. -- -The
- -crypto/x509
package -adds support for reading and writing arbitrary extensions. -- -The
- -crypto/tls
package adds -support for TLS 1.1, 1.2 and AES-GCM. -- -The
- -database/sql
package adds a -SetMaxOpenConns
-method onDB
to limit the -number of open connections to the database. -- -The
- -encoding/csv
package -now always allows trailing commas on fields. -- -The
- -encoding/gob
package -now treats channel and function fields of structures as if they were unexported, -even if they are not. That is, it ignores them completely. Previously they would -trigger an error, which could cause unexpected compatibility problems if an -embedded structure added such a field. -The package also now supports the genericBinaryMarshaler
and -BinaryUnmarshaler
interfaces of the -encoding
package -described above. -- -The
- -encoding/json
package -now will always escape ampersands as "\u0026" when printing strings. -It will now accept but correct invalid UTF-8 in -Marshal
-(such input was previously rejected). -Finally, it now supports the generic encoding interfaces of the -encoding
package -described above. -- -The
- -encoding/xml
package -now allows attributes stored in pointers to be marshaled. -It also supports the generic encoding interfaces of the -encoding
package -described above through the new -Marshaler
, -Unmarshaler
, -and related -MarshalerAttr
and -UnmarshalerAttr
-interfaces. -The package also adds a -Flush
method -to the -Encoder
-type for use by custom encoders. See the documentation for -EncodeToken
-to see how to use it. -- -The
- -flag
package now -has aGetter
interface -to allow the value of a flag to be retrieved. Due to the -Go 1 compatibility guidelines, this method cannot be added to the existing -Value
-interface, but all the existing standard flag types implement it. -The package also now exports theCommandLine
-flag set, which holds the flags from the command line. -- -The
- -go/ast
package's -SliceExpr
struct -has a new boolean field,Slice3
, which is set to true -when representing a slice expression with three indices (two colons). -The default is false, representing the usual two-index form. -- -The
- -go/build
package adds -theAllTags
field -to thePackage
type, -to make it easier to process build tags. -- -The
- -image/draw
package now -exports an interface,Drawer
, -that wraps the standardDraw
method. -The Porter-Duff operators now implement this interface, in effect binding an operation to -the draw operator rather than providing it explicitly. -Given a paletted image as its destination, the new -FloydSteinberg
-implementation of the -Drawer
-interface will use the Floyd-Steinberg error diffusion algorithm to draw the image. -To create palettes suitable for such processing, the new -Quantizer
interface -represents implementations of quantization algorithms that choose a palette -given a full-color image. -There are no implementations of this interface in the library. -- -The
- -image/gif
package -can now create GIF files using the new -Encode
-andEncodeAll
-functions. -Their options argument allows specification of an image -Quantizer
to use; -if it isnil
, the generated GIF will use the -Plan9
-color map (palette) defined in the new -image/color/palette
package. -The options also specify a -Drawer
-to use to create the output image; -if it isnil
, Floyd-Steinberg error diffusion is used. -- -The
- -Copy
method of the -io
package now prioritizes its -arguments differently. -If one argument implementsWriterTo
-and the other implementsReaderFrom
, -Copy
will now invoke -WriterTo
to do the work, -so that less intermediate buffering is required in general. -- -The
- -net
package requires cgo by default -because the host operating system must in general mediate network call setup. -On some systems, though, it is possible to use the network without cgo, and useful -to do so, for instance to avoid dynamic linking. -The new build tagnetgo
(off by default) allows the construction of a -net
package in pure Go on those systems where it is possible. -- -The
- -net
package adds a new field -DualStack
to theDialer
-struct for TCP connection setup using a dual IP stack as described in -RFC 6555. -- -The
- -net/http
package will no longer -transmit cookies that are incorrect according to -RFC 6265. -It just logs an error and sends nothing. -Also, -thenet/http
package's -ReadResponse
-function now permits the*Request
parameter to benil
, -whereupon it assumes a GET request. -Finally, an HTTP server will now serve HEAD -requests transparently, without the need for special casing in handler code. -While serving a HEAD request, writes to a -Handler
's -ResponseWriter
-are absorbed by the -Server
-and the client receives an empty body as required by the HTTP specification. -- -The
- -os/exec
package's -Cmd.StdinPipe
method -returns anio.WriteCloser
, but has changed its concrete -implementation from*os.File
to an unexported type that embeds -*os.File
, and it is now safe to close the returned value. -Before Go 1.2, there was an unavoidable race that this change fixes. -Code that needs access to the methods of*os.File
can use an -interface type assertion, such aswc.(interface{ Sync() error })
. -- -The
- -runtime
package relaxes -the constraints on finalizer functions in -SetFinalizer
: the -actual argument can now be any type that is assignable to the formal type of -the function, as is the case for any normal function call in Go. -- -The
- -sort
package has a new -Stable
function that implements -stable sorting. It is less efficient than the normal sort algorithm, however. -- -The
- -strings
package adds -anIndexByte
-function for consistency with thebytes
package. -- -The
- -sync/atomic
package -adds a new set of swap functions that atomically exchange the argument with the -value stored in the pointer, returning the old value. -The functions are -SwapInt32
, -SwapInt64
, -SwapUint32
, -SwapUint64
, -SwapUintptr
, -and -SwapPointer
, -which swaps anunsafe.Pointer
. -- -The
- -syscall
package now implements -Sendfile
for Darwin. -- -The
- -testing
package -now exports theTB
interface. -It records the methods in common with the -T
-and -B
types, -to make it easier to share code between tests and benchmarks. -Also, the -AllocsPerRun
-function now quantizes the return value to an integer (although it -still has typefloat64
), to round off any error caused by -initialization and make the result more repeatable. -- -The
- -text/template
package -now automatically dereferences pointer values when evaluating the arguments -to "escape" functions such as "html", to bring the behavior of such functions -in agreement with that of other printing functions such as "printf". -- -In the
- -time
package, the -Parse
function -and -Format
-method -now handle time zone offsets with seconds, such as in the historical -date "1871-01-01T05:33:02+00:34:08". -Also, pattern matching in the formats for those routines is stricter: a non-lowercase letter -must now follow the standard words such as "Jan" and "Mon". -- -The
- -unicode
package -addsIn
, -a nicer-to-use but equivalent version of the original -IsOneOf
, -to see whether a character is a member of a Unicode category. -Introduction to Go 1.3
- --The latest Go release, version 1.3, arrives six months after 1.2, -and contains no language changes. -It focuses primarily on implementation work, providing -precise garbage collection, -a major refactoring of the compiler toolchain that results in -faster builds, especially for large projects, -significant performance improvements across the board, -and support for DragonFly BSD, Solaris, Plan 9 and Google's Native Client architecture (NaCl). -It also has an important refinement to the memory model regarding synchronization. -As always, Go 1.3 keeps the promise -of compatibility, -and almost everything -will continue to compile and run without change when moved to 1.3. -
- -Changes to the supported operating systems and architectures
- -Removal of support for Windows 2000
- --Microsoft stopped supporting Windows 2000 in 2010. -Since it has implementation difficulties -regarding exception handling (signals in Unix terminology), -as of Go 1.3 it is not supported by Go either. -
- -Support for DragonFly BSD
- --Go 1.3 now includes experimental support for DragonFly BSD on the
- -amd64
(64-bit x86) and386
(32-bit x86) architectures. -It uses DragonFly BSD 3.6 or above. -Support for FreeBSD
- --It was not announced at the time, but since the release of Go 1.2, support for Go on FreeBSD -requires FreeBSD 8 or above. -
- --As of Go 1.3, support for Go on FreeBSD requires that the kernel be compiled with the -
- -COMPAT_FREEBSD32
flag configured. --In concert with the switch to EABI syscalls for ARM platforms, Go 1.3 will run only on FreeBSD 10. -The x86 platforms, 386 and amd64, are unaffected. -
- -Support for Native Client
- --Support for the Native Client virtual machine architecture has returned to Go with the 1.3 release. -It runs on the 32-bit Intel architectures (
- -GOARCH=386
) and also on 64-bit Intel, but using -32-bit pointers (GOARCH=amd64p32
). -There is not yet support for Native Client on ARM. -Note that this is Native Client (NaCl), not Portable Native Client (PNaCl). -Details about Native Client are here; -how to set up the Go version is described here. -Support for NetBSD
- --As of Go 1.3, support for Go on NetBSD requires NetBSD 6.0 or above. -
- -Support for OpenBSD
- --As of Go 1.3, support for Go on OpenBSD requires OpenBSD 5.5 or above. -
- -Support for Plan 9
- --Go 1.3 now includes experimental support for Plan 9 on the
- -386
(32-bit x86) architecture. -It requires theTsemacquire
syscall, which has been in Plan 9 since June, 2012. -Support for Solaris
- --Go 1.3 now includes experimental support for Solaris on the
- -amd64
(64-bit x86) architecture. -It requires illumos, Solaris 11 or above. -Changes to the memory model
- --The Go 1.3 memory model adds a new rule -concerning sending and receiving on buffered channels, -to make explicit that a buffered channel can be used as a simple -semaphore, using a send into the -channel to acquire and a receive from the channel to release. -This is not a language change, just a clarification about an expected property of communication. -
- -Changes to the implementations and tools
- -Stack
- --Go 1.3 has changed the implementation of goroutine stacks away from the old, -"segmented" model to a contiguous model. -When a goroutine needs more stack -than is available, its stack is transferred to a larger single block of memory. -The overhead of this transfer operation amortizes well and eliminates the old "hot spot" -problem when a calculation repeatedly steps across a segment boundary. -Details including performance numbers are in this -design document. -
- -Changes to the garbage collector
- --For a while now, the garbage collector has been precise when examining -values in the heap; the Go 1.3 release adds equivalent precision to values on the stack. -This means that a non-pointer Go value such as an integer will never be mistaken for a -pointer and prevent unused memory from being reclaimed. -
- --Starting with Go 1.3, the runtime assumes that values with pointer type -contain pointers and other values do not. -This assumption is fundamental to the precise behavior of both stack expansion -and garbage collection. -Programs that use package unsafe -to store integers in pointer-typed values are illegal and will crash if the runtime detects the behavior. -Programs that use package unsafe to store pointers -in integer-typed values are also illegal but more difficult to diagnose during execution. -Because the pointers are hidden from the runtime, a stack expansion or garbage collection -may reclaim the memory they point at, creating -dangling pointers. -
- --Updating: Code that uses
- -unsafe.Pointer
to convert -an integer-typed value held in memory into a pointer is illegal and must be rewritten. -Such code can be identified bygo vet
. -Map iteration
- --Iterations over small maps no longer happen in a consistent order. -Go 1 defines that “The iteration order over maps -is not specified and is not guaranteed to be the same from one iteration to the next.” -To keep code from depending on map iteration order, -Go 1.0 started each map iteration at a random index in the map. -A new map implementation introduced in Go 1.1 neglected to randomize -iteration for maps with eight or fewer entries, although the iteration order -can still vary from system to system. -This has allowed people to write Go 1.1 and Go 1.2 programs that -depend on small map iteration order and therefore only work reliably on certain systems. -Go 1.3 reintroduces random iteration for small maps in order to flush out these bugs. -
- --Updating: If code assumes a fixed iteration order for small maps, -it will break and must be rewritten not to make that assumption. -Because only small maps are affected, the problem arises most often in tests. -
- -The linker
- --As part of the general overhaul to -the Go linker, the compilers and linkers have been refactored. -The linker is still a C program, but now the instruction selection phase that -was part of the linker has been moved to the compiler through the creation of a new -library called
- -liblink
. -By doing instruction selection only once, when the package is first compiled, -this can speed up compilation of large projects significantly. --Updating: Although this is a major internal change, it should have no -effect on programs. -
- -Status of gccgo
- --GCC release 4.9 will contain the Go 1.2 (not 1.3) version of gccgo. -The release schedules for the GCC and Go projects do not coincide, -which means that 1.3 will be available in the development branch but -that the next GCC release, 4.10, will likely have the Go 1.4 version of gccgo. -
- -Changes to the go command
- --The
- -cmd/go
command has several new -features. -Thego run
and -go test
subcommands -support a new-exec
option to specify an alternate -way to run the resulting binary. -Its immediate purpose is to support NaCl. --The test coverage support of the
- -go test
-subcommand now automatically sets the coverage mode to-atomic
-when the race detector is enabled, to eliminate false reports about unsafe -access to coverage counters. --The
- -go test
subcommand -now always builds the package, even if it has no test files. -Previously, it would do nothing if no test files were present. --The
- -go build
subcommand -supports a new-i
option to install dependencies -of the specified target, but not the target itself. --Cross compiling with
- -cgo
enabled -is now supported. -The CC_FOR_TARGET and CXX_FOR_TARGET environment -variables are used when running all.bash to specify the cross compilers -for C and C++ code, respectively. --Finally, the go command now supports packages that import Objective-C -files (suffixed
- -.m
) through cgo. -Changes to cgo
- --The
- -cmd/cgo
command, -which processesimport "C"
declarations in Go packages, -has corrected a serious bug that may cause some packages to stop compiling. -Previously, all pointers to incomplete struct types translated to the Go type*[0]byte
, -with the effect that the Go compiler could not diagnose passing one kind of struct pointer -to a function expecting another. -Go 1.3 corrects this mistake by translating each different -incomplete struct to a different named type. --Given the C declaration
- -typedef struct S T
for an incompletestruct S
, -some Go code used this bug to refer to the typesC.struct_S
andC.T
interchangeably. -Cgo now explicitly allows this use, even for completed struct types. -However, some Go code also used this bug to pass (for example) a*C.FILE
-from one package to another. -This is not legal and no longer works: in general Go packages -should avoid exposing C types and names in their APIs. --Updating: Code confusing pointers to incomplete types or -passing them across package boundaries will no longer compile -and must be rewritten. -If the conversion is correct and must be preserved, -use an explicit conversion via
- -unsafe.Pointer
. -SWIG 3.0 required for programs that use SWIG
- --For Go programs that use SWIG, SWIG version 3.0 is now required. -The
- -cmd/go
command will now link the -SWIG generated object files directly into the binary, rather than -building and linking with a shared library. -Command-line flag parsing
- --In the gc toolchain, the assemblers now use the -same command-line flag parsing rules as the Go flag package, a departure -from the traditional Unix flag parsing. -This may affect scripts that invoke the tool directly. -For example, -
- -go tool 6a -SDfoo
must now be written -go tool 6a -S -D foo
. -(The same change was made to the compilers and linkers in Go 1.1.) -Changes to godoc
--When invoked with the
- --analysis
flag, -godoc -now performs sophisticated static -analysis of the code it indexes. -The results of analysis are presented in both the source view and the -package documentation view, and include the call graph of each package -and the relationships between -definitions and references, -types and their methods, -interfaces and their implementations, -send and receive operations on channels, -functions and their callers, and -call sites and their callees. -Miscellany
- --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 thego.tools
repo. -Documentation is here. --For the few of us that build Go distributions, the tool
- -misc/dist
has been -moved and renamed; it now lives inmisc/makerelease
, still in the main repository. -Performance
- --The performance of Go binaries for this release has improved in many cases due to changes -in the runtime and garbage collection, plus some changes to libraries. -Significant instances include: -
- -- -
- -- -The runtime handles defers more efficiently, reducing the memory footprint by about two kilobytes -per goroutine that calls defer. -
- -- -The garbage collector has been sped up, using a concurrent sweep algorithm, -better parallelization, and larger pages. -The cumulative effect can be a 50-70% reduction in collector pause time. -
- -- -The race detector (see this guide) -is now about 40% faster. -
- -- -The regular expression package
- -regexp
-is now significantly faster for certain simple expressions due to the implementation of -a second, one-pass execution engine. -The choice of which engine to use is automatic; -the details are hidden from the user. --Also, the runtime now includes in stack dumps how long a goroutine has been blocked, -which can be useful information when debugging deadlocks or performance issues. -
- -Changes to the standard library
- -New packages
- --A new package
- -debug/plan9obj
was added to the standard library. -It implements access to Plan 9 a.out object files. -Major changes to the library
- --A previous bug in
- -crypto/tls
-made it possible to skip verification in TLS inadvertently. -In Go 1.3, the bug is fixed: one must specify either ServerName or -InsecureSkipVerify, and if ServerName is specified it is enforced. -This may break existing code that incorrectly depended on insecure -behavior. --There is an important new type added to the standard library:
- -sync.Pool
. -It provides an efficient mechanism for implementing certain types of caches whose memory -can be reclaimed automatically by the system. --The
- -testing
package's benchmarking helper, -B
, now has a -RunParallel
method -to make it easier to run benchmarks that exercise multiple CPUs. --Updating: The crypto/tls fix may break existing code, but such -code was erroneous and should be updated. -
- -Minor changes to the library
- --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. -
- -- -
diff --git a/content/doc/go1.4.html b/content/doc/go1.4.html deleted file mode 100644 index c8f7c9c5..00000000 --- a/content/doc/go1.4.html +++ /dev/null @@ -1,896 +0,0 @@ - - -- In the
- -crypto/tls
package, -a newDialWithDialer
-function lets one establish a TLS connection using an existing dialer, making it easier -to control dial options such as timeouts. -The package also now reports the TLS version used by the connection in the -ConnectionState
-struct. -- The
- -CreateCertificate
-function of thecrypto/tls
package -now supports parsing (and elsewhere, serialization) of PKCS #10 certificate -signature requests. -- -The formatted print functions of the
- -fmt
package now define%F
-as a synonym for%f
when printing floating-point values. -- -The
- -math/big
package's -Int
and -Rat
types -now implement -encoding.TextMarshaler
and -encoding.TextUnmarshaler
. -- -The complex power function,
- -Pow
, -now specifies the behavior when the first argument is zero. -It was undefined before. -The details are in the documentation for the function. -- -The
- -net/http
package now exposes the -properties of a TLS connection used to make a client request in the new -Response.TLS
field. -- -The
- -net/http
package now -allows setting an optional server error logger -withServer.ErrorLog
. -The default is still that all errors go to stderr. -- -The
- -net/http
package now -supports disabling HTTP keep-alive connections on the server -withServer.SetKeepAlivesEnabled
. -The default continues to be that the server does keep-alive (reuses -connections for multiple requests) by default. -Only resource-constrained servers or those in the process of graceful -shutdown will want to disable them. -- -The
- -net/http
package adds an optional -Transport.TLSHandshakeTimeout
-setting to cap the amount of time HTTP client requests will wait for -TLS handshakes to complete. -It's now also set by default -onDefaultTransport
. -- -The
- -net/http
package's -DefaultTransport
, -used by the HTTP client code, now -enables TCP -keep-alives by default. -OtherTransport
-values with a nilDial
field continue to function the same -as before: no TCP keep-alives are used. -- -The
- -net/http
package -now enables TCP -keep-alives for incoming server requests when -ListenAndServe
-or -ListenAndServeTLS
-are used. -When a server is started otherwise, TCP keep-alives are not enabled. -- -The
- -net/http
package now -provides an -optionalServer.ConnState
-callback to hook various phases of a server connection's lifecycle -(seeConnState
). -This can be used to implement rate limiting or graceful shutdown. -- -The
- -net/http
package's HTTP -client now has an -optionalClient.Timeout
-field to specify an end-to-end timeout on requests made using the -client. -- -The
- -net/http
package's -Request.ParseMultipartForm
-method will now return an error if the body'sContent-Type
-is notmutipart/form-data
. -Prior to Go 1.3 it would silently fail and returnnil
. -Code that relies on the previous behavior should be updated. -- In the
- -net
package, -theDialer
struct now -has aKeepAlive
option to specify a keep-alive period for the connection. -- -The
- -net/http
package's -Transport
-now closesRequest.Body
-consistently, even on error. -- -The
- -os/exec
package now implements -what the documentation has always said with regard to relative paths for the binary. -In particular, it only callsLookPath
-when the binary's file name contains no path separators. -- -The
- -SetMapIndex
-function in thereflect
package -no longer panics when deleting from anil
map. -- -If the main goroutine calls -
- -runtime.Goexit
-and all other goroutines finish execution, the program now always crashes, -reporting a detected deadlock. -Earlier versions of Go handled this situation inconsistently: most instances -were reported as deadlocks, but some trivial cases exited cleanly instead. -- -The runtime/debug package now has a new function -
- -debug.WriteHeapDump
-that writes out a description of the heap. -- -The
- -CanBackquote
-function in thestrconv
package -now considers theDEL
character,U+007F
, to be -non-printing. -- -The
- -syscall
package now provides -SendmsgN
-as an alternate version of -Sendmsg
-that returns the number of bytes written. -- -On Windows, the
- -syscall
package now -supports the cdecl calling convention through the addition of a new function -NewCallbackCDecl
-alongside the existing function -NewCallback
. -- -The
- -testing
package now -diagnoses tests that callpanic(nil)
, which are almost always erroneous. -Also, tests now write profiles (if invoked with profiling flags) even on failure. -- -The
- -unicode
package and associated -support throughout the system has been upgraded from -Unicode 6.2.0 to Unicode 6.3.0. -Introduction to Go 1.4
- --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. -
- -Changes to the language
- -For-range loops
--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 ofRangeStmt
-may now benil
. -Method calls on **T
- --Given these declarations, -
- --type T int -func (T) M() {} -var x **T -- --both
- -gc
andgccgo
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. -
- -Changes to the supported operating systems and architectures
- -Android
- --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. -NaCl on ARM
- --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). -Plan9 on AMD64
- --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. -Changes to the compatibility guidelines
- --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 ofunsafe
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. -
- - -Changes to the implementations and tools
- -Changes to the runtime
- --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. -Assembly
- --The language accepted by the assemblers
- -cmd/5a
,cmd/6a
-andcmd/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 forTEXT
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
andGLOBL
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. -
- -Status of gccgo
- --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. -
- -Internal packages
- --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 thego
command sees an import of a package withinternal
in its path, -it verifies that the package doing the import -is within the tree rooted at the parent of theinternal
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. -
- -Canonical import paths
- --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 importsgithub.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. -
- -Import paths for the subrepositories
- --The Go project subrepositories (
- -code.google.com/p/go.tools
and so on) -are now available under custom import paths replacingcode.google.com/p/go.
withgolang.org/x/
, -as ingolang.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 oldcode.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 generate subcommand
- --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 theyacc
-compiler-compiler on a.y
file to produce the Go source file implementing the grammar, -or to automate the generation ofString
methods for typed constants using the new -stringer -tool in thegolang.org/x/tools
subrepository. --For more information, see the -design document. -
- -Change to file name handling
- --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 filegopher_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
oramd64.go
should either -have explicit build tags added to the source or be renamed to something like -os_windows.go
orsupport_amd64.go
. -Other changes to the go command
- --There were a number of minor changes to the -
- -cmd/go
-command worth noting. -- -
- -- -Unless
- -cgo
is being used to build the package, -thego
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. -- -The
- -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. -- -The
- -go
test
-subcommand will compile and link all*_test.go
files in the package, -even when there are noTest
functions in them. -It previously ignored such files. -- -The behavior of the -
- -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. -Changes to package source layout
- --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, thepkg
level of the source tree is now gone, so for example -thefmt
package's source, once kept in -directorysrc/pkg/fmt
, now lives one level higher insrc/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. -SWIG
- --Due to runtime changes in this release, Go 1.4 requires SWIG 3.0.3. -
- -Miscellany
- --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. -
- -Performance
- --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. -
- -Changes to the standard library
- -New packages
- --There are no new packages in this release. -
- -Major changes to the library
- -bufio.Scanner
- --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. -
- -syscall
- --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 thesyscall
package -should build ongolang.org/x/sys
instead. -Minor changes to the library
- --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. -
- -- -
diff --git a/content/doc/go1.5.html b/content/doc/go1.5.html deleted file mode 100644 index 2c77cf41..00000000 --- a/content/doc/go1.5.html +++ /dev/null @@ -1,1310 +0,0 @@ - - - -- -The
- -archive/zip
package's -Writer
now supports a -Flush
method. -- -The
- -compress/flate
, -compress/gzip
, -andcompress/zlib
-packages now support aReset
method -for the decompressors, allowing them to reuse buffers and improve performance. -Thecompress/gzip
package also has a -Multistream
method to control support -for multistream files. -- -The
- -crypto
package now has a -Signer
interface, implemented by the -PrivateKey
types in -crypto/ecdsa
and -crypto/rsa
. -- -The
- -crypto/tls
package -now supports ALPN as defined in RFC 7301. -- -The
- -crypto/tls
package -now supports programmatic selection of server certificates -through the newCertificateForName
function -of theConfig
struct. -- -Also in the crypto/tls package, the server now supports -TLS_FALLBACK_SCSV -to help clients detect fallback attacks. -(The Go client does not support fallback at all, so it is not vulnerable to -those attacks.) -
- -- -The
- -database/sql
package can now list all registered -Drivers
. -- -The
- -debug/dwarf
package now supports -UnspecifiedType
s. -- -In the
- -encoding/asn1
package, -optional elements with a default value will now only be omitted if they have that value. -- -The
- -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. -- -The
- -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. -- -The
- -encoding/xml
package's -Decoder
can now report its input offset. -- -In the
- -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. -- -The
- -image
package's -Image
-implementations like -RGBA
and -Gray
have specialized -RGBAAt
and -GrayAt
methods alongside the general -At
method. -- -The
- -image/png
package now has an -Encoder
-type to control the compression level used for encoding. -- -The
- -math
package now has a -Nextafter32
function. -- -The
- -net/http
package's -Request
type -has a newBasicAuth
method -that returns the username and password from authenticated requests using the -HTTP Basic Authentication -Scheme. -- The
- -net/http
package's -Transport
type -has a newDialTLS
hook -that allows customizing the behavior of outbound TLS connections. -- -The
- -net/http/httputil
package's -ReverseProxy
type -has a new field, -ErrorLog
, that -provides user control of logging. -- -The
- -os
package -now implements symbolic links on the Windows operating system -through theSymlink
function. -Other operating systems already have this functionality. -There is also a newUnsetenv
function. -- -The
- -reflect
package's -Type
interface -has a new method,Comparable
, -that reports whether the type implements general comparisons. -- -Also in the
- -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. -- -The
- -runtime
package -now implements monotonic clocks on Windows, -as it already did for the other systems. -- -The
- -runtime
package's -Mallocs
counter -now counts very small allocations that were missed in Go 1.3. -This may break tests usingReadMemStats
-orAllocsPerRun
-due to the more accurate answer. -- -In the
- -runtime
package, -an arrayPauseEnd
-has been added to the -MemStats
-andGCStats
structs. -This array is a circular buffer of times when garbage collection pauses ended. -The corresponding pause durations are already recorded in -PauseNs
-- -The
- -runtime/race
package -now supports FreeBSD, which means the -go
command's-race
-flag now works on FreeBSD. -- -The
- -sync/atomic
package -has a new type,Value
. -Value
provides an efficient mechanism for atomic loads and -stores of values of arbitrary type. -- -In the
- -syscall
package's -implementation on Linux, the -Setuid
-andSetgid
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. -- -The
- -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 *- -that function will be called instead of running the tests directly. -Thetesting.M
) -M
struct contains methods to access and run the tests. -- -Also in the
- -testing
package, -a newCoverage
-function reports the current test coverage fraction, -enabling individual tests to report how much they are contributing to the -overall coverage. -- -The
- -text/scanner
package's -Scanner
type -has a new function, -IsIdentRune
, -allowing one to control the definition of an identifier when scanning. -- -The
- -text/template
package's boolean -functionseq
,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. -- -The
- -time
package now uses the standard symbol for the micro prefix, -the micro symbol (U+00B5 'µ'), to print microsecond durations. -ParseDuration
still acceptsus
-but the package no longer prints microseconds asus
. -
-Updating: Code that depends on the output format of durations -but does not use ParseDuration will need to be updated. -Introduction to Go 1.5
- --The latest Go release, version 1.5, -is a significant release, including major architectural changes to the implementation. -Despite that, we expect almost all Go programs to continue to compile and run as before, -because the release still maintains the Go 1 promise -of compatibility. -
- --The biggest developments in the implementation are: -
- -- -
- -- -The compiler and runtime are now written entirely in Go (with a little assembler). -C is no longer involved in the implementation, and so the C compiler that was -once necessary for building the distribution is gone. -
- -- -The garbage collector is now concurrent and provides dramatically lower -pause times by running, when possible, in parallel with other goroutines. -
- -- -By default, Go programs run with
- -GOMAXPROCS
set to the -number of cores available; in prior releases it defaulted to 1. -- -Support for internal packages -is now provided for all repositories, not just the Go core. -
- -- -The
- -go
command now provides experimental -support for "vendoring" external dependencies. -- -A new
- -go tool trace
command supports fine-grained -tracing of program execution. -- -A new
- -go doc
command (distinct fromgodoc
) -is customized for command-line use. --These and a number of other changes to the implementation and tools -are discussed below. -
- --The release also contains one small language change involving map literals. -
- --Finally, the timing of the release -strays from the usual six-month interval, -both to provide more time to prepare this major release and to shift the schedule thereafter to -time the release dates more conveniently. -
- -Changes to the language
- -Map literals
- --Due to an oversight, the rule that allowed the element type to be elided from slice literals was not -applied to map keys. -This has been corrected in Go 1.5. -An example will make this clear. -As of Go 1.5, this map literal, -
- --m := map[Point]string{ - Point{29.935523, 52.891566}: "Persepolis", - Point{-25.352594, 131.034361}: "Uluru", - Point{37.422455, -122.084306}: "Googleplex", -} -- --may be written as follows, without the
- -Point
type listed explicitly: --m := map[Point]string{ - {29.935523, 52.891566}: "Persepolis", - {-25.352594, 131.034361}: "Uluru", - {37.422455, -122.084306}: "Googleplex", -} -- -The Implementation
- -No more C
- --The compiler and runtime are now implemented in Go and assembler, without C. -The only C source left in the tree is related to testing or to
- -cgo
. -There was a C compiler in the tree in 1.4 and earlier. -It was used to build the runtime; a custom compiler was necessary in part to -guarantee the C code would work with the stack management of goroutines. -Since the runtime is in Go now, there is no need for this C compiler and it is gone. -Details of the process to eliminate C are discussed elsewhere. --The conversion from C was done with the help of custom tools created for the job. -Most important, the compiler was actually moved by automatic translation of -the C code into Go. -It is in effect the same program in a different language. -It is not a new implementation -of the compiler so we expect the process will not have introduced new compiler -bugs. -An overview of this process is available in the slides for -this presentation. -
- -Compiler and tools
- --Independent of but encouraged by the move to Go, the names of the tools have changed. -The old names
- -6g
,8g
and so on are gone; instead there -is just one binary, accessible asgo
tool
compile
, -that compiles Go source into binaries suitable for the architecture and operating system -specified by$GOARCH
and$GOOS
. -Similarly, there is now one linker (go
tool
link
) -and one assembler (go
tool
asm
). -The linker was translated automatically from the old C implementation, -but the assembler is a new native Go implementation discussed -in more detail below. --Similar to the drop of the names
- - -6g
,8g
, and so on, -the output of the compiler and assembler are now given a plain.o
suffix -rather than.8
,.6
, etc. -Garbage collector
- --The garbage collector has been re-engineered for 1.5 as part of the development -outlined in the design document. -Expected latencies are much lower than with the collector -in prior releases, through a combination of advanced algorithms, -better scheduling of the collector, -and running more of the collection in parallel with the user program. -The "stop the world" phase of the collector -will almost always be under 10 milliseconds and usually much less. -
- --For systems that benefit from low latency, such as user-responsive web sites, -the drop in expected latency with the new collector may be important. -
- --Details of the new collector were presented in a -talk at GopherCon 2015. -
- -Runtime
- --In Go 1.5, the order in which goroutines are scheduled has been changed. -The properties of the scheduler were never defined by the language, -but programs that depend on the scheduling order may be broken -by this change. -We have seen a few (erroneous) programs affected by this change. -If you have programs that implicitly depend on the scheduling -order, you will need to update them. -
- --Another potentially breaking change is that the runtime now -sets the default number of threads to run simultaneously, -defined by
- -GOMAXPROCS
, to the number -of cores available on the CPU. -In prior releases the default was 1. -Programs that do not expect to run with multiple cores may -break inadvertently. -They can be updated by removing the restriction or by setting -GOMAXPROCS
explicitly. -For a more detailed discussion of this change, see -the design document. -Build
- --Now that the Go compiler and runtime are implemented in Go, a Go compiler -must be available to compile the distribution from source. -Thus, to build the Go core, a working Go distribution must already be in place. -(Go programmers who do not work on the core are unaffected by this change.) -Any Go 1.4 or later distribution (including
- -gccgo
) will serve. -For details, see the design document. -Ports
- --Due mostly to the industry's move away from the 32-bit x86 architecture, -the set of binary downloads provided is reduced in 1.5. -A distribution for the OS X operating system is provided only for the -
- -amd64
architecture, not386
. -Similarly, the ports for Snow Leopard (Apple OS X 10.6) still work but are no -longer released as a download or maintained since Apple no longer maintains that version -of the operating system. -Also, thedragonfly/386
port is no longer supported at all -because DragonflyBSD itself no longer supports the 32-bit 386 architecture. --There are however several new ports available to be built from source. -These include
- -darwin/arm
anddarwin/arm64
. -The new portlinux/arm64
is mostly in place, butcgo
-is only supported using external linking. --Also available as experiments are
- -ppc64
-andppc64le
(64-bit PowerPC, big- and little-endian). -Both these ports supportcgo
but -only with internal linking. --On FreeBSD, Go 1.5 requires FreeBSD 8-STABLE+ because of its new use of the
- -SYSCALL
instruction. --On NaCl, Go 1.5 requires SDK version pepper-41. Later pepper versions are not -compatible due to the removal of the sRPC subsystem from the NaCl runtime. -
- --On Darwin, the use of the system X.509 certificate interface can be disabled -with the
- -ios
build tag. --The Solaris port now has full support for cgo and the packages -
- -net
and -crypto/x509
, -as well as a number of other fixes and improvements. -Tools
- -Translating
- --As part of the process to eliminate C from the tree, the compiler and -linker were translated from C to Go. -It was a genuine (machine assisted) translation, so the new programs are essentially -the old programs translated rather than new ones with new bugs. -We are confident the translation process has introduced few if any new bugs, -and in fact uncovered a number of previously unknown bugs, now fixed. -
- --The assembler is a new program, however; it is described below. -
- -Renaming
- --The suites of programs that were the compilers (
- -6g
,8g
, etc.), -the assemblers (6a
,8a
, etc.), -and the linkers (6l
,8l
, etc.) -have each been consolidated into a single tool that is configured -by the environment variablesGOOS
andGOARCH
. -The old names are gone; the new tools are available through thego
tool
-mechanism asgo tool compile
, -go tool asm
, -and go tool link
. -Also, the file suffixes.6
,.8
, etc. for the -intermediate object files are also gone; now they are just plain.o
files. --For example, to build and link a program on amd64 for Darwin -using the tools directly, rather than through
- -go build
, -one would run: --$ export GOOS=darwin GOARCH=amd64 -$ go tool compile program.go -$ go tool link program.o -- -Moving
- --Because the
- -go/types
package -has now moved into the main repository (see below), -thevet
and -cover
-tools have also been moved. -They are no longer maintained in the externalgolang.org/x/tools
repository, -although (deprecated) source still resides there for compatibility with old releases. -Compiler
- --As described above, the compiler in Go 1.5 is a single Go program, -translated from the old C source, that replaces
- -6g
,8g
, -and so on. -Its target is configured by the environment variablesGOOS
andGOARCH
. --The 1.5 compiler is mostly equivalent to the old, -but some internal details have changed. -One significant change is that evaluation of constants now uses -the
- -math/big
package -rather than a custom (and less well tested) implementation of high precision -arithmetic. -We do not expect this to affect the results. --For the amd64 architecture only, the compiler has a new option,
- --dynlink
, -that assists dynamic linking by supporting references to Go symbols -defined in external shared libraries. -Assembler
- --Like the compiler and linker, the assembler in Go 1.5 is a single program -that replaces the suite of assemblers (
- -6a
, -8a
, etc.) and the environment variables -GOARCH
andGOOS
-configure the architecture and operating system. -Unlike the other programs, the assembler is a wholly new program -written in Go. --The new assembler is very nearly compatible with the previous -ones, but there are a few changes that may affect some -assembler source files. -See the updated assembler guide -for more specific information about these changes. In summary: - -
- --First, the expression evaluation used for constants is a little -different. -It now uses unsigned 64-bit arithmetic and the precedence -of operators (
- -+
,-
,<<
, etc.) -comes from Go, not C. -We expect these changes to affect very few programs but -manual verification may be required. --Perhaps more important is that on machines where -
- -SP
orPC
is only an alias -for a numbered register, -such asR13
for the stack pointer and -R15
for the hardware program counter -on ARM, -a reference to such a register that does not include a symbol -is now illegal. -For example,SP
and4(SP)
are -illegal butsym+4(SP)
is fine. -On such machines, to refer to the hardware register use its -trueR
name. --One minor change is that some of the old assemblers -permitted the notation -
- --constant=value -- --to define a named constant. -Since this is always possible to do with the traditional -C-like
- -#define
notation, which is still -supported (the assembler includes an implementation -of a simplified C preprocessor), the feature was removed. -Linker
- --The linker in Go 1.5 is now one Go program, -that replaces
- -6l
,8l
, etc. -Its operating system and instruction set are specified -by the environment variablesGOOS
andGOARCH
. --There are several other changes. -The most significant is the addition of a
- --buildmode
option that -expands the style of linking; it now supports -situations such as building shared libraries and allowing other languages -to call into Go libraries. -Some of these were outlined in a design document. -For a list of the available build modes and their use, run --$ go help buildmode -- --Another minor change is that the linker no longer records build time stamps in -the header of Windows executables. -Also, although this may be fixed, Windows cgo executables are missing some -DWARF information. -
- --Finally, the
- --X
flag, which takes two arguments, -as in ---X importpath.name value -- --now also accepts a more common Go flag style with a single argument -that is itself a
- -name=value
pair: ---X importpath.name=value -- --Although the old syntax still works, it is recommended that uses of this -flag in scripts and the like be updated to the new form. -
- -Go command
- --The
- -go
command's basic operation -is unchanged, but there are a number of changes worth noting. --The previous release introduced the idea of a directory internal to a package -being unimportable through the
- -go
command. -In 1.4, it was tested with the introduction of some internal elements -in the core repository. -As suggested in the design document, -that change is now being made available to all repositories. -The rules are explained in the design document, but in summary any -package in or under a directory namedinternal
may -be imported by packages rooted in the same subtree. -Existing packages with directory elements namedinternal
may be -inadvertently broken by this change, which was why it was advertised -in the last release. --Another change in how packages are handled is the experimental -addition of support for "vendoring". -For details, see the documentation for the
- -go
command -and the design document. --There have also been several minor changes. -Read the documentation for full details. -
- -- -
- -- -SWIG support has been updated such that -
- -.swig
and.swigcxx
-now require SWIG 3.0.6 or later. -- -The
- -install
subcommand now removes the -binary created by thebuild
subcommand -in the source directory, if present, -to avoid problems having two binaries present in the tree. -- -The
- -std
(standard library) wildcard package name -now excludes commands. -A newcmd
wildcard covers the commands. -- -A new
- --asmflags
build option -sets flags to pass to the assembler. -However, -the-ccflags
build option has been dropped; -it was specific to the old, now deleted C compiler . -- -A new
- --buildmode
build option -sets the build mode, described above. -- -A new
- --pkgdir
build option -sets the location of installed package archives, -to help isolate custom builds. -- -A new
- --toolexec
build option -allows substitution of a different command to invoke -the compiler and so on. -This acts as a custom replacement forgo tool
. -- -The
- -test
subcommand now has a-count
-flag to specify how many times to run each test and benchmark. -Thetesting
package -does the work here, through the-test.count
flag. -- -The
- -generate
subcommand has a couple of new features. -The-run
option specifies a regular expression to select which directives -to execute; this was proposed but never implemented in 1.4. -The executing pattern now has access to two new environment variables: -$GOLINE
returns the source line number of the directive -and$DOLLAR
expands to a dollar sign. -- -The
- -get
subcommand now has a-insecure
-flag that must be enabled if fetching from an insecure repository, one that -does not encrypt the connection. -Go vet command
- --The
- -go tool vet
command now does -more thorough validation of struct tags. -Trace command
- --A new tool is available for dynamic execution tracing of Go programs. -The usage is analogous to how the test coverage tool works. -Generation of traces is integrated into
- -go test
, -and then a separate execution of the tracing tool itself analyzes the results: --$ go test -trace=trace.out path/to/package -$ go tool trace [flags] pkg.test trace.out -- --The flags enable the output to be displayed in a browser window. -For details, run
- -go tool trace -help
. -There is also a description of the tracing facility in this -talk -from GopherCon 2015. -Go doc command
- --A few releases back, the
- -go doc
-command was deleted as being unnecessary. -One could always run "godoc .
" instead. -The 1.5 release introduces a newgo doc
-command with a more convenient command-line interface than -godoc
's. -It is designed for command-line usage specifically, and provides a more -compact and focused presentation of the documentation for a package -or its elements, according to the invocation. -It also provides case-insensitive matching and -support for showing the documentation for unexported symbols. -For details run "go help doc
". -Cgo
- --When parsing
- -#cgo
lines, -the invocation${SRCDIR}
is now -expanded into the path to the source directory. -This allows options to be passed to the -compiler and linker that involve file paths relative to the -source code directory. Without the expansion the paths would be -invalid when the current working directory changes. --Solaris now has full cgo support. -
- --On Windows, cgo now uses external linking by default. -
- --When a C struct ends with a zero-sized field, but the struct itself is -not zero-sized, Go code can no longer refer to the zero-sized field. -Any such references will have to be rewritten. -
- -Performance
- --As always, the changes are so general and varied that precise statements -about performance are difficult to make. -The changes are even broader ranging than usual in this release, which -includes a new garbage collector and a conversion of the runtime to Go. -Some programs may run faster, some slower. -On average the programs in the Go 1 benchmark suite run a few percent faster in Go 1.5 -than they did in Go 1.4, -while as mentioned above the garbage collector's pauses are -dramatically shorter, and almost always under 10 milliseconds. -
- --Builds in Go 1.5 will be slower by a factor of about two. -The automatic translation of the compiler and linker from C to Go resulted in -unidiomatic Go code that performs poorly compared to well-written Go. -Analysis tools and refactoring helped to improve the code, but much remains to be done. -Further profiling and optimization will continue in Go 1.6 and future releases. -For more details, see these slides -and associated video. -
- -Core library
- -Flag
- --The flag package's -
- -PrintDefaults
-function, and method onFlagSet
, -have been modified to create nicer usage messages. -The format has been changed to be more human-friendly and in the usage -messages a word quoted with `backquotes` is taken to be the name of the -flag's operand to display in the usage message. -For instance, a flag created with the invocation, --cpuFlag = flag.Int("cpu", 1, "run `N` processes in parallel") -- --will show the help message, -
- ---cpu N - run N processes in parallel (default 1) -- --Also, the default is now listed only when it is not the zero value for the type. -
- -Floats in math/big
- --The
- -math/big
package -has a new, fundamental data type, -Float
, -which implements arbitrary-precision floating-point numbers. -AFloat
value is represented by a boolean sign, -a variable-length mantissa, and a 32-bit fixed-size signed exponent. -The precision of aFloat
(the mantissa size in bits) -can be specified explicitly or is otherwise determined by the first -operation that creates the value. -Once created, the size of aFloat
's mantissa may be modified with the -SetPrec
method. -Floats
support the concept of infinities, such as are created by -overflow, but values that would lead to the equivalent of IEEE 754 NaNs -trigger a panic. -Float
operations support all IEEE-754 rounding modes. -When the precision is set to 24 (53) bits, -operations that stay within the range of normalizedfloat32
-(float64
) -values produce the same results as the corresponding IEEE-754 -arithmetic on those values. -Go types
- --The
- -go/types
package -up to now has been maintained in thegolang.org/x
-repository; as of Go 1.5 it has been relocated to the main repository. -The code at the old location is now deprecated. -There is also a modest API change in the package, discussed below. --Associated with this move, the -
- -go/constant
-package also moved to the main repository; -it wasgolang.org/x/tools/exact
before. -Thego/importer
package -also moved to the main repository, -as well as some tools described above. -Net
- --The DNS resolver in the net package has almost always used
- -cgo
to access -the system interface. -A change in Go 1.5 means that on most Unix systems DNS resolution -will no longer requirecgo
, which simplifies execution -on those platforms. -Now, if the system's networking configuration permits, the native Go resolver -will suffice. -The important effect of this change is that each DNS resolution occupies a goroutine -rather than a thread, -so a program with multiple outstanding DNS requests will consume fewer operating -system resources. --The decision of how to run the resolver applies at run time, not build time. -The
- -netgo
build tag that has been used to enforce the use -of the Go resolver is no longer necessary, although it still works. -A newnetcgo
build tag forces the use of thecgo
resolver at -build time. -To forcecgo
resolution at run time set -GODEBUG=netdns=cgo
in the environment. -More debug options are documented here. --This change applies to Unix systems only. -Windows, Mac OS X, and Plan 9 systems behave as before. -
- -Reflect
- --The
- -reflect
package -has two new functions:ArrayOf
-andFuncOf
. -These functions, analogous to the extant -SliceOf
function, -create new types at runtime to describe arrays and functions. -Hardening
- --Several dozen bugs were found in the standard library -through randomized testing with the -
- -go-fuzz
tool. -Bugs were fixed in the -archive/tar
, -archive/zip
, -compress/flate
, -encoding/gob
, -fmt
, -html/template
, -image/gif
, -image/jpeg
, -image/png
, and -text/template
, -packages. -The fixes harden the implementation against incorrect and malicious inputs. -Minor changes to the library
- -- -
diff --git a/content/doc/go1.6.html b/content/doc/go1.6.html deleted file mode 100644 index 902a82d5..00000000 --- a/content/doc/go1.6.html +++ /dev/null @@ -1,923 +0,0 @@ - - - - - - -- -The
- -archive/zip
package's -Writer
type now has a -SetOffset
-method to specify the location within the output stream at which to write the archive. -- -The
- -Reader
in the -bufio
package now has a -Discard
-method to discard data from the input. -- -In the
- -bytes
package, -theBuffer
type -now has aCap
method -that reports the number of bytes allocated within the buffer. -Similarly, in both thebytes
-andstrings
packages, -theReader
-type now has aSize
-method that reports the original length of the underlying slice or string. -- -Both the
- -bytes
and -strings
packages -also now have aLastIndexByte
-function that locates the rightmost byte with that value in the argument. -- -The
- -crypto
package -has a new interface,Decrypter
, -that abstracts the behavior of a private key used in asymmetric decryption. -- -In the
- -crypto/cipher
package, -the documentation for theStream
-interface has been clarified regarding the behavior when the source and destination are -different lengths. -If the destination is shorter than the source, the method will panic. -This is not a change in the implementation, only the documentation. -- -Also in the
- -crypto/cipher
package, -there is now support for nonce lengths other than 96 bytes in AES's Galois/Counter mode (GCM), -which some protocols require. -- -In the
- -crypto/elliptic
package, -there is now aName
field in the -CurveParams
struct, -and the curves implemented in the package have been given names. -These names provide a safer way to select a curve, as opposed to -selecting its bit size, for cryptographic systems that are curve-dependent. -- -Also in the
- -crypto/elliptic
package, -theUnmarshal
function -now verifies that the point is actually on the curve. -(If it is not, the function returns nils). -This change guards against certain attacks. -- -The
- -crypto/sha512
-package now has support for the two truncated versions of -the SHA-512 hash algorithm, SHA-512/224 and SHA-512/256. -- -The
- -crypto/tls
package -minimum protocol version now defaults to TLS 1.0. -The old default, SSLv3, is still available throughConfig
if needed. -- -The
crypto/tls
package -now supports Signed Certificate Timestamps (SCTs) as specified in RFC 6962. -The server serves them if they are listed in the -Certificate
struct, -and the client requests them and exposes them, if present, -in itsConnectionState
struct. - -- -The stapled OCSP response to a
- -crypto/tls
client connection, -previously only available via the -OCSPResponse
method, -is now exposed in theConnectionState
struct. -- -The
- -crypto/tls
server implementation -will now always call the -GetCertificate
function in -theConfig
struct -to select a certificate for the connection when none is supplied. -- -Finally, the session ticket keys in the -
- -crypto/tls
package -can now be changed while the server is running. -This is done through the new -SetSessionTicketKeys
-method of the -Config
type. -- -In the
- -crypto/x509
package, -wildcards are now accepted only in the leftmost label as defined in -the specification. -- -Also in the
- -crypto/x509
package, -the handling of unknown critical extensions has been changed. -They used to cause parse errors but now they are parsed and caused errors only -inVerify
. -The new fieldUnhandledCriticalExtensions
of -Certificate
records these extensions. -- -The
- -DB
type of the -database/sql
package -now has aStats
method -to retrieve database statistics. -- -The
- -debug/dwarf
-package has extensive additions to better support DWARF version 4. -See for example the definition of the new type -Class
. -- -The
- -debug/dwarf
package -also now supports decoding of DWARF line tables. -- -The
- -debug/elf
-package now has support for the 64-bit PowerPC architecture. -- -The
- -encoding/base64
package -now supports unpadded encodings through two new encoding variables, -RawStdEncoding
and -RawURLEncoding
. -- -The
- -encoding/json
package -now returns anUnmarshalTypeError
-if a JSON value is not appropriate for the target variable or component -to which it is being unmarshaled. -- -The
- -encoding/json
's -Decoder
-type has a new method that provides a streaming interface for decoding -a JSON document: -Token
. -It also interoperates with the existing functionality ofDecode
, -which will continue a decode operation already started withDecoder.Token
. -- -The
- -flag
package -has a new function,UnquoteUsage
, -to assist in the creation of usage messages using the new convention -described above. -- -In the
- -fmt
package, -a value of typeValue
now -prints what it holds, rather than use thereflect.Value
'sStringer
-method, which produces things like<int Value>
. -- -The
- -EmptyStmt
type -in thego/ast
package now -has a booleanImplicit
field that records whether the -semicolon was implicitly added or was present in the source. -- -For forward compatibility the
- -go/build
package -reservesGOARCH
values for a number of architectures that Go might support one day. -This is not a promise that it will. -Also, thePackage
struct -now has aPkgTargetRoot
field that stores the -architecture-dependent root directory in which to install, if known. -- -The (newly migrated)
- -go/types
-package allows one to control the prefix attached to package-level names using -the newQualifier
-function type as an argument to several functions. This is an API change for -the package, but since it is new to the core, it is not breaking the Go 1 compatibility -rules since code that uses the package must explicitly ask for it at its new location. -To update, run -go fix
on your package. -- -In the
- -image
package, -theRectangle
type -now implements theImage
interface, -so aRectangle
can serve as a mask when drawing. -- -Also in the
- -image
package, -to assist in the handling of some JPEG images, -there is now support for 4:1:1 and 4:1:0 YCbCr subsampling and basic -CMYK support, represented by the newimage.CMYK
struct. -- -The
- -image/color
package -adds basic CMYK support, through the new -CMYK
struct, -theCMYKModel
color model, and the -CMYKToRGB
function, as -needed by some JPEG images. -- -Also in the
- -image/color
package, -the conversion of aYCbCr
-value toRGBA
has become more precise. -Previously, the low 8 bits were just an echo of the high 8 bits; -now they contain more accurate information. -Because of the echo property of the old code, the operation -uint8(r)
to extract an 8-bit red value worked, but is incorrect. -In Go 1.5, that operation may yield a different value. -The correct code is, and always was, to select the high 8 bits: -uint8(r>>8)
. -Incidentally, theimage/draw
package -provides better support for such conversions; see -this blog post -for more information. -- -Finally, as of Go 1.5 the closest match check in -
- -Index
-now honors the alpha channel. -- -The
- -image/gif
package -includes a couple of generalizations. -A multiple-frame GIF file can now have an overall bounds different -from all the contained single frames' bounds. -Also, theGIF
struct -now has aDisposal
field -that specifies the disposal method for each frame. -- -The
- -io
package -adds aCopyBuffer
function -that is likeCopy
but -uses a caller-provided buffer, permitting control of allocation and buffer size. -- -The
- -log
package -has a newLUTC
flag -that causes time stamps to be printed in the UTC time zone. -It also adds aSetOutput
method -for user-created loggers. -- -In Go 1.4,
- -Max
was not detecting all possible NaN bit patterns. -This is fixed in Go 1.5, so programs that usemath.Max
on data including NaNs may behave differently, -but now correctly according to the IEEE754 definition of NaNs. -- -The
- -math/big
package -adds a newJacobi
-function for integers and a new -ModSqrt
-method for theInt
type. -- -The mime package -adds a new
- -WordDecoder
type -to decode MIME headers containing RFC 204-encoded words. -It also providesBEncoding
and -QEncoding
-as implementations of the encoding schemes of RFC 2045 and RFC 2047. -- -The
- -mime
package also adds an -ExtensionsByType
-function that returns the MIME extensions know to be associated with a given MIME type. -- -There is a new
- -mime/quotedprintable
-package that implements the quoted-printable encoding defined by RFC 2045. -- -The
- -net
package will now -Dial
hostnames by trying each -IP address in order until one succeeds. -TheDialer.DualStack
-mode now implements Happy Eyeballs -(RFC 6555) by giving the -first address family a 300ms head start; this value can be overridden by -the newDialer.FallbackDelay
. -- -A number of inconsistencies in the types returned by errors in the -
- -net
package have been -tidied up. -Most now return an -OpError
value -with more information than before. -Also, theOpError
-type now includes aSource
field that holds the local -network address. -- -The
- -net/http
package now -has support for setting trailers from a serverHandler
. -For details, see the documentation for -ResponseWriter
. -- -There is a new method to cancel a
- -net/http
-Request
by setting the new -Request.Cancel
-field. -It is supported byhttp.Transport
. -TheCancel
field's type is compatible with the -context.Context.Done
-return value. -- -Also in the
- -net/http
package, -there is code to ignore the zeroTime
value -in theServeContent
function. -As of Go 1.5, it now also ignores a time value equal to the Unix epoch. -- -The
- -net/http/fcgi
package -exports two new errors, -ErrConnClosed
and -ErrRequestAborted
, -to report the corresponding error conditions. -- -The
- -net/http/cgi
package -had a bug that mishandled the values of the environment variables -REMOTE_ADDR
andREMOTE_HOST
. -This has been fixed. -Also, starting with Go 1.5 the package sets theREMOTE_PORT
-variable. -- -The
- -net/mail
package -adds anAddressParser
-type that can parse mail addresses. -- -The
- -net/smtp
package -now has aTLSConnectionState
-accessor to theClient
-type that returns the client's TLS state. -- -The
- -os
package -has a newLookupEnv
function -that is similar toGetenv
-but can distinguish between an empty environment variable and a missing one. -- -The
- -os/signal
package -adds newIgnore
and -Reset
functions. -- -The
- -runtime
, -runtime/trace
, -andnet/http/pprof
packages -each have new functions to support the tracing facilities described above: -ReadTrace
, -StartTrace
, -StopTrace
, -Start
, -Stop
, and -Trace
. -See the respective documentation for details. -- -The
- -runtime/pprof
package -by default now includes overall memory statistics in all memory profiles. -- -The
- -strings
package -has a newCompare
function. -This is present to provide symmetry with thebytes
package -but is otherwise unnecessary as strings support comparison natively. -- -The
- -WaitGroup
implementation in -packagesync
-now diagnoses code that races a call toAdd
-against a return fromWait
. -If it detects this condition, the implementation panics. -- -In the
- -syscall
package, -the LinuxSysProcAttr
struct now has a -GidMappingsEnableSetgroups
field, made necessary -by security changes in Linux 3.19. -On all Unix systems, the struct also has newForeground
andPgid
fields -to provide more control when exec'ing. -On Darwin, there is now aSyscall9
function -to support calls with too many arguments. -- -The
- -testing/quick
will now -generatenil
values for pointer types, -making it possible to use with recursive data structures. -Also, the package now supports generation of array types. -- -In the
- -text/template
and -html/template
packages, -integer constants too large to be represented as a Go integer now trigger a -parse error. Before, they were silently converted to floating point, losing -precision. -- -Also in the
- -text/template
and -html/template
packages, -a newOption
method -allows customization of the behavior of the template during execution. -The sole implemented option allows control over how a missing key is -handled when indexing a map. -The default, which can now be overridden, is as before: to continue with an invalid value. -- -The
- -time
package's -Time
type has a new method -AppendFormat
, -which can be used to avoid allocation when printing a time value. -- -The
- -unicode
package and associated -support throughout the system has been upgraded from version 7.0 to -Unicode 8.0. -Introduction to Go 1.6
- --The latest Go release, version 1.6, arrives six months after 1.5. -Most of its changes are in the implementation of the language, runtime, and libraries. -There are no changes to the language specification. -As always, the release maintains the Go 1 promise of compatibility. -We expect almost all Go programs to continue to compile and run as before. -
- --The release adds new ports to Linux on 64-bit MIPS and Android on 32-bit x86; -defined and enforced rules for sharing Go pointers with C; -transparent, automatic support for HTTP/2; -and a new mechanism for template reuse. -
- -Changes to the language
- --There are no language changes in this release. -
- -Ports
- --Go 1.6 adds experimental ports to -Linux on 64-bit MIPS (
- -linux/mips64
andlinux/mips64le
). -These ports supportcgo
but only with internal linking. --Go 1.6 also adds an experimental port to Android on 32-bit x86 (
- -android/386
). --On FreeBSD, Go 1.6 defaults to using
- -clang
, notgcc
, as the external C compiler. --On Linux on little-endian 64-bit PowerPC (
- -linux/ppc64le
), -Go 1.6 now supportscgo
with external linking and -is roughly feature complete. --On NaCl, Go 1.5 required SDK version pepper-41. -Go 1.6 adds support for later SDK versions. -
- --On 32-bit x86 systems using the
- --dynlink
or-shared
compilation modes, -the register CX is now overwritten by certain memory references and should -be avoided in hand-written assembly. -See the assembly documentation for details. -Tools
- -Cgo
- --There is one major change to
- -cgo
, along with one minor change. --The major change is the definition of rules for sharing Go pointers with C code, -to ensure that such C code can coexist with Go's garbage collector. -Briefly, Go and C may share memory allocated by Go -when a pointer to that memory is passed to C as part of a
- -cgo
call, -provided that the memory itself contains no pointers to Go-allocated memory, -and provided that C does not retain the pointer after the call returns. -These rules are checked by the runtime during program execution: -if the runtime detects a violation, it prints a diagnosis and crashes the program. -The checks can be disabled by setting the environment variable -GODEBUG=cgocheck=0
, but note that the vast majority of -code identified by the checks is subtly incompatible with garbage collection -in one way or another. -Disabling the checks will typically only lead to more mysterious failure modes. -Fixing the code in question should be strongly preferred -over turning off the checks. -See thecgo
documentation for more details. --The minor change is -the addition of explicit
- -C.complexfloat
andC.complexdouble
types, -separate from Go'scomplex64
andcomplex128
. -Matching the other numeric types, C's complex types and Go's complex type are -no longer interchangeable. -Compiler Toolchain
- --The compiler toolchain is mostly unchanged. -Internally, the most significant change is that the parser is now hand-written -instead of generated from yacc. -
- --The compiler, linker, and
- -go
command have a new flag-msan
, -analogous to-race
and only available on linux/amd64, -that enables interoperation with the Clang MemorySanitizer. -Such interoperation is useful mainly for testing a program containing suspect C or C++ code. --The linker has a new option
- --libgcc
to set the expected location -of the C compiler support library when linkingcgo
code. -The option is only consulted when using-linkmode=internal
, -and it may be set tonone
to disable the use of a support library. --The implementation of build modes started in Go 1.5 has been expanded to more systems. -This release adds support for the
- -c-shared
mode onandroid/386
,android/amd64
, -android/arm64
,linux/386
, andlinux/arm64
; -for theshared
mode onlinux/386
,linux/arm
,linux/amd64
, andlinux/ppc64le
; -and for the newpie
mode (generating position-independent executables) on -android/386
,android/amd64
,android/arm
,android/arm64
,linux/386
, -linux/amd64
,linux/arm
,linux/arm64
, andlinux/ppc64le
. -See the design document for details. --As a reminder, the linker's
- --X
flag changed in Go 1.5. -In Go 1.4 and earlier, it took two arguments, as in ---X importpath.name value -- --Go 1.5 added an alternative syntax using a single argument -that is itself a
- -name=value
pair: ---X importpath.name=value -- --In Go 1.5 the old syntax was still accepted, after printing a warning -suggesting use of the new syntax instead. -Go 1.6 continues to accept the old syntax and print the warning. -Go 1.7 will remove support for the old syntax. -
- -Gccgo
- --The release schedules for the GCC and Go projects do not coincide. -GCC release 5 contains the Go 1.4 version of gccgo. -The next release, GCC 6, will have the Go 1.6.1 version of gccgo. -
- -Go command
- --The
- -go
command's basic operation -is unchanged, but there are a number of changes worth noting. --Go 1.5 introduced experimental support for vendoring, -enabled by setting the
- -GO15VENDOREXPERIMENT
environment variable to1
. -Go 1.6 keeps the vendoring support, no longer considered experimental, -and enables it by default. -It can be disabled explicitly by setting -theGO15VENDOREXPERIMENT
environment variable to0
. -Go 1.7 will remove support for the environment variable. --The most likely problem caused by enabling vendoring by default happens -in source trees containing an existing directory named
- -vendor
that -does not expect to be interpreted according to new vendoring semantics. -In this case, the simplest fix is to rename the directory to anything other -thanvendor
and update any affected import paths. --For details about vendoring, -see the documentation for the
- -go
command -and the design document. --There is a new build flag,
- --msan
, -that compiles Go with support for the LLVM memory sanitizer. -This is intended mainly for use when linking against C or C++ code -that is being checked with the memory sanitizer. -Go doc command
- --Go 1.5 introduced the -
- -go doc
command, -which allows references to packages using only the package name, as in -go
doc
http
. -In the event of ambiguity, the Go 1.5 behavior was to use the package -with the lexicographically earliest import path. -In Go 1.6, ambiguity is resolved by preferring import paths with -fewer elements, breaking ties using lexicographic comparison. -An important effect of this change is that original copies of packages -are now preferred over vendored copies. -Successful searches also tend to run faster. -Go vet command
- --The
- -go vet
command now diagnoses -passing function or method values as arguments toPrintf
, -such as when passingf
wheref()
was intended. -Performance
- --As always, the changes are so general and varied that precise statements -about performance are difficult to make. -Some programs may run faster, some slower. -On average the programs in the Go 1 benchmark suite run a few percent faster in Go 1.6 -than they did in Go 1.5. -The garbage collector's pauses are even lower than in Go 1.5, -especially for programs using -a large amount of memory. -
- --There have been significant optimizations bringing more than 10% improvements -to implementations of the -
- -compress/bzip2
, -compress/gzip
, -crypto/aes
, -crypto/elliptic
, -crypto/ecdsa
, and -sort
packages. -Core library
- -HTTP/2
- --Go 1.6 adds transparent support in the -
- -net/http
package -for the new HTTP/2 protocol. -Go clients and servers will automatically use HTTP/2 as appropriate when using HTTPS. -There is no exported API specific to details of the HTTP/2 protocol handling, -just as there is no exported API specific to HTTP/1.1. --Programs that must disable HTTP/2 can do so by setting -
- -Transport.TLSNextProto
(for clients) -or -Server.TLSNextProto
(for servers) -to a non-nil, empty map. --Programs that must adjust HTTP/2 protocol-specific details can import and use -
- -golang.org/x/net/http2
, -in particular its -ConfigureServer -and -ConfigureTransport -functions. -Runtime
- --The runtime has added lightweight, best-effort detection of concurrent misuse of maps. -As always, if one goroutine is writing to a map, no other goroutine should be -reading or writing the map concurrently. -If the runtime detects this condition, it prints a diagnosis and crashes the program. -The best way to find out more about the problem is to run the program -under the -race detector, -which will more reliably identify the race -and give more detail. -
- --For program-ending panics, the runtime now by default -prints only the stack of the running goroutine, -not all existing goroutines. -Usually only the current goroutine is relevant to a panic, -so omitting the others significantly reduces irrelevant output -in a crash message. -To see the stacks from all goroutines in crash messages, set the environment variable -
- -GOTRACEBACK
toall
-or call -debug.SetTraceback
-before the crash, and rerun the program. -See the runtime documentation for details. --Updating: -Uncaught panics intended to dump the state of the entire program, -such as when a timeout is detected or when explicitly handling a received signal, -should now call
- -debug.SetTraceback("all")
before panicking. -Searching for uses of -signal.Notify
may help identify such code. --On Windows, Go programs in Go 1.5 and earlier forced -the global Windows timer resolution to 1ms at startup -by calling
- -timeBeginPeriod(1)
. -Go no longer needs this for good scheduler performance, -and changing the global timer resolution caused problems on some systems, -so the call has been removed. --When using
- --buildmode=c-archive
or --buildmode=c-shared
to build an archive or a shared -library, the handling of signals has changed. -In Go 1.5 the archive or shared library would install a signal handler -for most signals. -In Go 1.6 it will only install a signal handler for the -synchronous signals needed to handle run-time panics in Go code: -SIGBUS, SIGFPE, SIGSEGV. -See the os/signal package for more -details. -Reflect
- --The -
- -reflect
package has -resolved a long-standing incompatibility -between the gc and gccgo toolchains -regarding embedded unexported struct types containing exported fields. -Code that walks data structures using reflection, especially to implement -serialization in the spirit -of the -encoding/json
and -encoding/xml
packages, -may need to be updated. --The problem arises when using reflection to walk through -an embedded unexported struct-typed field -into an exported field of that struct. -In this case,
- -reflect
had incorrectly reported -the embedded field as exported, by returning an emptyField.PkgPath
. -Now it correctly reports the field as unexported -but ignores that fact when evaluating access to exported fields -contained within the struct. --Updating: -Typically, code that previously walked over structs and used -
- --f.PkgPath != "" -- --to exclude inaccessible fields -should now use -
- --f.PkgPath != "" && !f.Anonymous -- --For example, see the changes to the implementations of -
- -encoding/json
and -encoding/xml
. -Sorting
- --In the -
- -sort
-package, -the implementation of -Sort
-has been rewritten to make about 10% fewer calls to the -Interface
's -Less
andSwap
-methods, with a corresponding overall time savings. -The new algorithm does choose a different ordering than before -for values that compare equal (those pairs for whichLess(i,
j)
andLess(j,
i)
are false). --Updating: -The definition of
- -Sort
makes no guarantee about the final order of equal values, -but the new behavior may still break programs that expect a specific order. -Such programs should either refine theirLess
implementations -to report the desired order -or should switch to -Stable
, -which preserves the original input order -of equal values. -Templates
- --In the -text/template package, -there are two significant new features to make writing templates easier. -
- --First, it is now possible to trim spaces around template actions, -which can make template definitions more readable. -A minus sign at the beginning of an action says to trim space before the action, -and a minus sign at the end of an action says to trim space after the action. -For example, the template -
- --{{"{{"}}23 -}} - < -{{"{{"}}- 45}} -- --formats as
- -23<45
. --Second, the new
- -{{"{{"}}block}}
action, -combined with allowing redefinition of named templates, -provides a simple way to define pieces of a template that -can be replaced in different instantiations. -There is an example -in thetext/template
package that demonstrates this new feature. -Minor changes to the library
- -- -
- diff --git a/content/doc/go1.7.html b/content/doc/go1.7.html deleted file mode 100644 index db607027..00000000 --- a/content/doc/go1.7.html +++ /dev/null @@ -1,1281 +0,0 @@ - - - - - - - - -- -The
- -archive/tar
package's -implementation corrects many bugs in rare corner cases of the file format. -One visible change is that the -Reader
type's -Read
method -now presents the content of special file types as being empty, -returningio.EOF
immediately. -- -In the
- -archive/zip
package, the -Reader
type now has a -RegisterDecompressor
method, -and the -Writer
type now has a -RegisterCompressor
method, -enabling control over compression options for individual zip files. -These take precedence over the pre-existing global -RegisterDecompressor
and -RegisterCompressor
functions. -- -The
- -bufio
package's -Scanner
type now has a -Buffer
method, -to specify an initial buffer and maximum buffer size to use during scanning. -This makes it possible, when needed, to scan tokens larger than -MaxScanTokenSize
. -Also for theScanner
, the package now defines the -ErrFinalToken
error value, for use by -split functions to abort processing or to return a final empty token. -- -The
- -compress/flate
package -has deprecated its -ReadError
and -WriteError
error implementations. -In Go 1.5 they were only rarely returned when an error was encountered; -now they are never returned, although they remain defined for compatibility. -- -The
- -compress/flate
, -compress/gzip
, and -compress/zlib
packages -now report -io.ErrUnexpectedEOF
for truncated input streams, instead of -io.EOF
. -- -The
- -crypto/cipher
package now -overwrites the destination buffer in the event of a GCM decryption failure. -This is to allow the AESNI code to avoid using a temporary buffer. -- -The
- -crypto/tls
package -has a variety of minor changes. -It now allows -Listen
-to succeed when the -Config
-has a nilCertificates
, as long as theGetCertificate
callback is set, -it adds support for RSA with AES-GCM cipher suites, -and -it adds a -RecordHeaderError
-to allow clients (in particular, thenet/http
package) -to report a better error when attempting a TLS connection to a non-TLS server. -- -The
- -crypto/x509
package -now permits certificates to contain negative serial numbers -(technically an error, but unfortunately common in practice), -and it defines a new -InsecureAlgorithmError
-to give a better error message when rejecting a certificate -signed with an insecure algorithm like MD5. -- -The
- -debug/dwarf
and -debug/elf
packages -together add support for compressed DWARF sections. -User code needs no updating: the sections are decompressed automatically when read. -- -The
- -debug/elf
package -adds support for general compressed ELF sections. -User code needs no updating: the sections are decompressed automatically when read. -However, compressed -Sections
do not support random access: -they have a nilReaderAt
field. -- -The
- -encoding/asn1
package -now exports -tag and class constants -useful for advanced parsing of ASN.1 structures. -- -Also in the
- -encoding/asn1
package, -Unmarshal
now rejects various non-standard integer and length encodings. -- -The
- -encoding/base64
package's -Decoder
has been fixed -to process the final bytes of its input. Previously it processed as many four-byte tokens as -possible but ignored the remainder, up to three bytes. -TheDecoder
therefore now handles inputs in unpadded encodings (like -RawURLEncoding) correctly, -but it also rejects inputs in padded encodings that are truncated or end with invalid bytes, -such as trailing spaces. -- -The
- -encoding/json
package -now checks the syntax of a -Number
-before marshaling it, requiring that it conforms to the JSON specification for numeric values. -As in previous releases, the zeroNumber
(an empty string) is marshaled as a literal 0 (zero). -- -The
- -encoding/xml
package's -Marshal
-function now supports acdata
attribute, such aschardata
-but encoding its argument in one or more<![CDATA[ ... ]]>
tags. -- -Also in the
- -encoding/xml
package, -Decoder
's -Token
method -now reports an error when encountering EOF before seeing all open tags closed, -consistent with its general requirement that tags in the input be properly matched. -To avoid that requirement, use -RawToken
. -- -The
- -fmt
package now allows -any integer type as an argument to -Printf
's*
width and precision specification. -In previous releases, the argument to*
was required to have typeint
. -- -Also in the
- -fmt
package, -Scanf
can now scan hexadecimal strings using %X, as an alias for %x. -Both formats accept any mix of upper- and lower-case hexadecimal. -- -The
- -image
-and -image/color
packages -add -NYCbCrA
-and -NYCbCrA
-types, to support Y'CbCr images with non-premultiplied alpha. -- -The
- -io
package's -MultiWriter
-implementation now implements aWriteString
method, -for use by -WriteString
. -- -In the
- -math/big
package, -Int
adds -Append
-and -Text
-methods to give more control over printing. -- -Also in the
- -math/big
package, -Float
now implements -encoding.TextMarshaler
and -encoding.TextUnmarshaler
, -allowing it to be serialized in a natural form by the -encoding/json
and -encoding/xml
packages. -- -Also in the
- -math/big
package, -Float
's -Append
method now supports the special precision argument -1. -As in -strconv.ParseFloat
, -precision -1 means to use the smallest number of digits necessary such that -Parse
-reading the result into aFloat
of the same precision -will yield the original value. -- -The
- -math/rand
package -adds a -Read
-function, and likewise -Rand
adds a -Read
method. -These make it easier to generate pseudorandom test data. -Note that, like the rest of the package, -these should not be used in cryptographic settings; -for such purposes, use thecrypto/rand
package instead. -- -The
- - -net
package's -ParseMAC
function now accepts 20-byte IP-over-InfiniBand (IPoIB) link-layer addresses. -- -Also in the
- -net
package, -there have been a few changes to DNS lookups. -First, the -DNSError
error implementation now implements -Error
, -and in particular its new -IsTemporary
-method returns true for DNS server errors. -Second, DNS lookup functions such as -LookupAddr
-now return rooted domain names (with a trailing dot) -on Plan 9 and Windows, to match the behavior of Go on Unix systems. -- -The
- -net/http
package has -a number of minor additions beyond the HTTP/2 support already discussed. -First, the -FileServer
now sorts its generated directory listings by file name. -Second, the -ServeFile
function now refuses to serve a result -if the request's URL path contains “..” (dot-dot) as a path element. -Programs should typically useFileServer
and -Dir
-instead of callingServeFile
directly. -Programs that need to serve file content in response to requests for URLs containing dot-dot can -still callServeContent
. -Third, the -Client
now allows user code to set the -Expect:
100-continue
header (see -Transport.ExpectContinueTimeout
). -Fourth, there are -five new error codes: -StatusPreconditionRequired
(428), -StatusTooManyRequests
(429), -StatusRequestHeaderFieldsTooLarge
(431), and -StatusNetworkAuthenticationRequired
(511) from RFC 6585, -as well as the recently-approved -StatusUnavailableForLegalReasons
(451). -Fifth, the implementation and documentation of -CloseNotifier
-has been substantially changed. -TheHijacker
-interface now works correctly on connections that have previously -been used withCloseNotifier
. -The documentation now describes whenCloseNotifier
-is expected to work. -- -Also in the
- -net/http
package, -there are a few changes related to the handling of a -Request
data structure with itsMethod
field set to the empty string. -An emptyMethod
field has always been documented as an alias for"GET"
-and it remains so. -However, Go 1.6 fixes a few routines that did not treat an empty -Method
the same as an explicit"GET"
. -Most notably, in previous releases -Client
followed redirects only with -Method
set explicitly to"GET"
; -in Go 1.6Client
also follows redirects for the emptyMethod
. -Finally, -NewRequest
accepts amethod
argument that has not been -documented as allowed to be empty. -In past releases, passing an emptymethod
argument resulted -in aRequest
with an emptyMethod
field. -In Go 1.6, the resultingRequest
always has an initialized -Method
field: if its argument is an empty string,NewRequest
-sets theMethod
field in the returnedRequest
to"GET"
. -- -The
- -net/http/httptest
package's -ResponseRecorder
now initializes a default Content-Type header -using the same content-sniffing algorithm as in -http.Server
. -- -The
- -net/url
package's -Parse
is now stricter and more spec-compliant regarding the parsing -of host names. -For example, spaces in the host name are no longer accepted. -- -Also in the
- -net/url
package, -theError
type now implements -net.Error
. -- -The
- -os
package's -IsExist
, -IsNotExist
, -and -IsPermission
-now return correct results when inquiring about an -SyscallError
. -- -On Unix-like systems, when a write -to
- -os.Stdout
-oros.Stderr
(more precisely, anos.File
-opened for file descriptor 1 or 2) fails due to a broken pipe error, -the program will raise aSIGPIPE
signal. -By default this will cause the program to exit; this may be changed by -calling the -os/signal
-Notify
function -forsyscall.SIGPIPE
. -A write to a broken pipe on a file descriptor other 1 or 2 will simply -returnsyscall.EPIPE
(possibly wrapped in -os.PathError
-and/oros.SyscallError
) -to the caller. -The old behavior of raising an uncatchableSIGPIPE
signal -after 10 consecutive writes to a broken pipe no longer occurs. -- -In the
- -os/exec
package, -Cmd
's -Output
method continues to return an -ExitError
when a command exits with an unsuccessful status. -If standard error would otherwise have been discarded, -the returnedExitError
now holds a prefix and suffix -(currently 32 kB) of the failed command's standard error output, -for debugging or for inclusion in error messages. -TheExitError
's -String
-method does not show the captured standard error; -programs must retrieve it from the data structure -separately. -- -On Windows, the
- -path/filepath
package's -Join
function now correctly handles the case when the base is a relative drive path. -For example,Join(`c:`,
`a`)
now -returns`c:a`
instead of`c:\a`
as in past releases. -This may affect code that expects the incorrect result. -- -In the
- -regexp
package, -the -Regexp
type has always been safe for use by -concurrent goroutines. -It uses async.Mutex
to protect -a cache of scratch spaces used during regular expression searches. -Some high-concurrency servers using the sameRegexp
from many goroutines -have seen degraded performance due to contention on that mutex. -To help such servers,Regexp
now has a -Copy
method, -which makes a copy of aRegexp
that shares most of the structure -of the original but has its own scratch space cache. -Two goroutines can use different copies of aRegexp
-without mutex contention. -A copy does have additional space overhead, soCopy
-should only be used when contention has been observed. -- -The
- -strconv
package adds -IsGraphic
, -similar toIsPrint
. -It also adds -QuoteToGraphic
, -QuoteRuneToGraphic
, -AppendQuoteToGraphic
, -and -AppendQuoteRuneToGraphic
, -analogous to -QuoteToASCII
, -QuoteRuneToASCII
, -and so on. -TheASCII
family escapes all space characters except ASCII space (U+0020). -In contrast, theGraphic
family does not escape any Unicode space characters (category Zs). -- -In the
- -testing
package, -when a test calls -t.Parallel, -that test is paused until all non-parallel tests complete, and then -that test continues execution with all other parallel tests. -Go 1.6 changes the time reported for such a test: -previously the time counted only the parallel execution, -but now it also counts the time from the start of testing -until the call tot.Parallel
. -- -The
- -text/template
package -contains two minor changes, in addition to the major changes -described above. -First, it adds a new -ExecError
type -returned for any error during -Execute
-that does not originate in aWrite
to the underlying writer. -Callers can distinguish template usage errors from I/O errors by checking for -ExecError
. -Second, the -Funcs
method -now checks that the names used as keys in the -FuncMap
-are identifiers that can appear in a template function invocation. -If not,Funcs
panics. -- -The
- -time
package's -Parse
function has always rejected any day of month larger than 31, -such as January 32. -In Go 1.6,Parse
now also rejects February 29 in non-leap years, -February 30, February 31, April 31, June 31, September 31, and November 31. -Introduction to Go 1.7
- --The latest Go release, version 1.7, arrives six months after 1.6. -Most of its changes are in the implementation of the toolchain, runtime, and libraries. -There is one minor change to the language specification. -As always, the release maintains the Go 1 promise of compatibility. -We expect almost all Go programs to continue to compile and run as before. -
- --The release adds a port to IBM LinuxOne; -updates the x86-64 compiler back end to generate more efficient code; -includes the context package, promoted from the -x/net subrepository -and now used in the standard library; -and adds support in the testing package for -creating hierarchies of tests and benchmarks. -The release also finalizes the vendoring support -started in Go 1.5, making it a standard feature. -
- -Changes to the language
- --There is one tiny language change in this release. -The section on terminating statements -clarifies that to determine whether a statement list ends in a terminating statement, -the “final non-empty statement” is considered the end, -matching the existing behavior of the gc and gccgo compiler toolchains. -In earlier releases the definition referred only to the “final statement,” -leaving the effect of trailing empty statements at the least unclear. -The
- -go/types
-package has been updated to match the gc and gccgo compiler toolchains -in this respect. -This change has no effect on the correctness of existing programs. -Ports
- --Go 1.7 adds support for macOS 10.12 Sierra. -Binaries built with versions of Go before 1.7 will not work -correctly on Sierra. -
- --Go 1.7 adds an experimental port to Linux on z Systems (
- -linux/s390x
) -and the beginning of a port to Plan 9 on ARM (plan9/arm
). --The experimental ports to Linux on 64-bit MIPS (
- -linux/mips64
andlinux/mips64le
) -added in Go 1.6 now have full support for cgo and external linking. --The experimental port to Linux on little-endian 64-bit PowerPC (
- -linux/ppc64le
) -now requires the POWER8 architecture or later. -Big-endian 64-bit PowerPC (linux/ppc64
) only requires the -POWER5 architecture. --The OpenBSD port now requires OpenBSD 5.6 or later, for access to the getentropy(2) system call. -
- -Known Issues
- --There are some instabilities on FreeBSD that are known but not understood. -These can lead to program crashes in rare cases. -See issue 16136, -issue 15658, -and issue 16396. -Any help in solving these FreeBSD-specific issues would be appreciated. -
- -Tools
- -Assembler
- --For 64-bit ARM systems, the vector register names have been -corrected to
- -V0
throughV31
; -previous releases incorrectly referred to them asV32
throughV63
. --For 64-bit x86 systems, the following instructions have been added: -
- -PCMPESTRI
, -RORXL
, -RORXQ
, -VINSERTI128
, -VPADDD
, -VPADDQ
, -VPALIGNR
, -VPBLENDD
, -VPERM2F128
, -VPERM2I128
, -VPOR
, -VPSHUFB
, -VPSHUFD
, -VPSLLD
, -VPSLLDQ
, -VPSLLQ
, -VPSRLD
, -VPSRLDQ
, -and -VPSRLQ
. -Compiler Toolchain
- --This release includes a new code generation back end for 64-bit x86 systems, -following a proposal from 2015 -that has been under development since then. -The new back end, based on -SSA, -generates more compact, more efficient code -and provides a better platform for optimizations -such as bounds check elimination. -The new back end reduces the CPU time required by -our benchmark programs by 5-35%. -
- --For this release, the new back end can be disabled by passing -
- --ssa=0
to the compiler. -If you find that your program compiles or runs successfully -only with the new back end disabled, please -file a bug report. --The format of exported metadata written by the compiler in package archives has changed: -the old textual format has been replaced by a more compact binary format. -This results in somewhat smaller package archives and fixes a few -long-standing corner case bugs. -
- --For this release, the new export format can be disabled by passing -
- --newexport=0
to the compiler. -If you find that your program compiles or runs successfully -only with the new export format disabled, please -file a bug report. --The linker's
- --X
option no longer supports the unusual two-argument form --X
name
value
, -as announced in the Go 1.6 release -and in warnings printed by the linker. -Use-X
name=value
instead. --The compiler and linker have been optimized and run significantly faster in this release than in Go 1.6, -although they are still slower than we would like and will continue to be optimized in future releases. -
- --Due to changes across the compiler toolchain and standard library, -binaries built with this release should typically be smaller than binaries -built with Go 1.6, -sometimes by as much as 20-30%. -
- --On x86-64 systems, Go programs now maintain stack frame pointers -as expected by profiling tools like Linux's perf and Intel's VTune, -making it easier to analyze and optimize Go programs using these tools. -The frame pointer maintenance has a small run-time overhead that varies -but averages around 2%. We hope to reduce this cost in future releases. -To build a toolchain that does not use frame pointers, set -
- -GOEXPERIMENT=noframepointer
when running -make.bash
,make.bat
, ormake.rc
. -Cgo
- --Packages using cgo may now include -Fortran source files (in addition to C, C++, Objective C, and SWIG), -although the Go bindings must still use C language APIs. -
- --Go bindings may now use a new helper function
- -C.CBytes
. -In contrast toC.CString
, which takes a Gostring
-and returns a*C.byte
(a Cchar*
), -C.CBytes
takes a Go[]byte
-and returns anunsafe.Pointer
(a Cvoid*
). --Packages and binaries built using
- -cgo
have in past releases -produced different output on each build, -due to the embedding of temporary directory names. -When using this release with -new enough versions of GCC or Clang -(those that support the-fdebug-prefix-map
option), -those builds should finally be deterministic. -Gccgo
- --Due to the alignment of Go's semiannual release schedule with GCC's annual release schedule, -GCC release 6 contains the Go 1.6.1 version of gccgo. -The next release, GCC 7, will likely have the Go 1.8 version of gccgo. -
- -Go command
- --The
- -go
command's basic operation -is unchanged, but there are a number of changes worth noting. --This release removes support for the
- -GO15VENDOREXPERIMENT
environment variable, -as announced in the Go 1.6 release. -Vendoring support -is now a standard feature of thego
command and toolchain. --The
- -Package
data structure made available to -“go
list
” now includes a -StaleReason
field explaining why a particular package -is or is not considered stale (in need of rebuilding). -This field is available to the-f
or-json
-options and is useful for understanding why a target is being rebuilt. --The “
- -go
get
” command now supports -import paths referring togit.openstack.org
. --This release adds experimental, minimal support for building programs using -binary-only packages, -packages distributed in binary form -without the corresponding source code. -This feature is needed in some commercial settings -but is not intended to be fully integrated into the rest of the toolchain. -For example, tools that assume access to complete source code -will not work with such packages, and there are no plans to support -such packages in the “
- -go
get
” command. -Go doc
- --The “
- -go
doc
” command -now groups constructors with the type they construct, -followinggodoc
. -Go vet
- --The “
- -go
vet
” command -has more accurate analysis in its-copylock
and-printf
checks, -and a new-tests
check that checks the name and signature of likely test functions. -To avoid confusion with the new-tests
check, the old, unadvertised --test
option has been removed; it was equivalent to-all
-shadow
. --The
- -vet
command also has a new check, --lostcancel
, which detects failure to call the -cancelation function returned by theWithCancel
, -WithTimeout
, andWithDeadline
functions in -Go 1.7's newcontext
package (see below). -Failure to call the function prevents the newContext
-from being reclaimed until its parent is cancelled. -(The background context is never cancelled.) -Go tool dist
- --The new subcommand “
- -go
tool
dist
list
” -prints all supported operating system/architecture pairs. -Go tool trace
- --The “
- -go
tool
trace
” command, -introduced in Go 1.5, -has been refined in various ways. --First, collecting traces is significantly more efficient than in past releases. -In this release, the typical execution-time overhead of collecting a trace is about 25%; -in past releases it was at least 400%. -Second, trace files now include file and line number information, -making them more self-contained and making the -original executable optional when running the trace tool. -Third, the trace tool now breaks up large traces to avoid limits -in the browser-based viewer. -
- --Although the trace file format has changed in this release, -the Go 1.7 tools can still read traces from earlier releases. -
- -Performance
- --As always, the changes are so general and varied that precise statements -about performance are difficult to make. -Most programs should run a bit faster, -due to speedups in the garbage collector and -optimizations in the core library. -On x86-64 systems, many programs will run significantly faster, -due to improvements in generated code brought by the -new compiler back end. -As noted above, in our own benchmarks, -the code generation changes alone typically reduce program CPU time by 5-35%. -
- -- -There have been significant optimizations bringing more than 10% improvements -to implementations in the -
- -crypto/sha1
, -crypto/sha256
, -encoding/binary
, -fmt
, -hash/adler32
, -hash/crc32
, -hash/crc64
, -image/color
, -math/big
, -strconv
, -strings
, -unicode
, -and -unicode/utf16
-packages. --Garbage collection pauses should be significantly shorter than they -were in Go 1.6 for programs with large numbers of idle goroutines, -substantial stack size fluctuation, or large package-level variables. -
- -Core library
- -Context
- --Go 1.7 moves the
- -golang.org/x/net/context
package -into the standard library ascontext
. -This allows the use of contexts for cancelation, timeouts, and passing -request-scoped data in other standard library packages, -including -net, -net/http, -and -os/exec, -as noted below. --For more information about contexts, see the -package documentation -and the Go blog post -“Go Concurrent Patterns: Context.” -
- -HTTP Tracing
- --Go 1.7 introduces
- -net/http/httptrace
, -a package that provides mechanisms for tracing events within HTTP requests. -Testing
- --The
- -testing
package now supports the definition -of tests with subtests and benchmarks with sub-benchmarks. -This support makes it easy to write table-driven benchmarks -and to create hierarchical tests. -It also provides a way to share common setup and tear-down code. -See the package documentation for details. -Runtime
- --All panics started by the runtime now use panic values -that implement both the -builtin
- -error
, -and -runtime.Error
, -as -required by the language specification. --During panics, if a signal's name is known, it will be printed in the stack trace. -Otherwise, the signal's number will be used, as it was before Go1.7. -
- --The new function -
- -KeepAlive
-provides an explicit mechanism for declaring -that an allocated object must be considered reachable -at a particular point in a program, -typically to delay the execution of an associated finalizer. --The new function -
- -CallersFrames
-translates a PC slice obtained from -Callers
-into a sequence of frames corresponding to the call stack. -This new API should be preferred instead of direct use of -FuncForPC
, -because the frame sequence can more accurately describe -call stacks with inlined function calls. --The new function -
- -SetCgoTraceback
-facilitates tighter integration between Go and C code executing -in the same process called using cgo. --On 32-bit systems, the runtime can now use memory allocated -by the operating system anywhere in the address space, -eliminating the -“memory allocated by OS not in usable range” failure -common in some environments. -
- --The runtime can now return unused memory to the operating system on -all architectures. -In Go 1.6 and earlier, the runtime could not -release memory on ARM64, 64-bit PowerPC, or MIPS. -
- --On Windows, Go programs in Go 1.5 and earlier forced -the global Windows timer resolution to 1ms at startup -by calling
- - -timeBeginPeriod(1)
. -Changing the global timer resolution caused problems on some systems, -and testing suggested that the call was not needed for good scheduler performance, -so Go 1.6 removed the call. -Go 1.7 brings the call back: under some workloads the call -is still needed for good scheduler performance. -Minor changes to the library
- --As always, there are various minor changes and updates to the library, -made with the Go 1 promise of compatibility -in mind. -
- -- -
- bufio
- -- -
--In previous releases of Go, if -
-Reader
's -Peek
method -were asked for more bytes than fit in the underlying buffer, -it would return an empty slice and the errorErrBufferFull
. -Now it returns the entire underlying buffer, still accompanied by the errorErrBufferFull
. -- -
- bytes
- -- -
--The new functions -
- -ContainsAny
and -ContainsRune
-have been added for symmetry with -thestrings
package. --In previous releases of Go, if -
- -Reader
's -Read
method -were asked for zero bytes with no data remaining, it would -return a count of 0 and no error. -Now it returns a count of 0 and the error -io.EOF
. --The -
-Reader
type has a new method -Reset
to allow reuse of aReader
. -- -
- compress/flate
- -- -
--There are many performance optimizations throughout the package. -Decompression speed is improved by about 10%, -while compression for
- -DefaultCompression
is twice as fast. --In addition to those general improvements, -the -
- -BestSpeed
-compressor has been replaced entirely and uses an -algorithm similar to Snappy, -resulting in about a 2.5X speed increase, -although the output can be 5-10% larger than with the previous algorithm. --There is also a new compression level -
- -HuffmanOnly
-that applies Huffman but not Lempel-Ziv encoding. -Forgoing Lempel-Ziv encoding means that -HuffmanOnly
runs about 3X faster than the newBestSpeed
-but at the cost of producing compressed outputs that are 20-40% larger than those -generated by the newBestSpeed
. --It is important to note that both -
- -BestSpeed
andHuffmanOnly
produce a compressed output that is -RFC 1951 compliant. -In other words, any valid DEFLATE decompressor will continue to be able to decompress these outputs. --Lastly, there is a minor change to the decompressor's implementation of -
-io.Reader
. In previous versions, -the decompressor deferred reporting -io.EOF
until exactly no more bytes could be read. -Now, it reports -io.EOF
more eagerly when reading the last set of bytes. -- -
- crypto/tls
- -- -
--The TLS implementation sends the first few data packets on each connection -using small record sizes, gradually increasing to the TLS maximum record size. -This heuristic reduces the amount of data that must be received before -the first packet can be decrypted, improving communication latency over -low-bandwidth networks. -Setting -
- -Config
's -DynamicRecordSizingDisabled
field to true -forces the behavior of Go 1.6 and earlier, where packets are -as large as possible from the start of the connection. --The TLS client now has optional, limited support for server-initiated renegotiation, -enabled by setting the -
- -Config
's -Renegotiation
field. -This is needed for connecting to many Microsoft Azure servers. --The errors returned by the package now consistently begin with a -
- -tls:
prefix. -In past releases, some errors used acrypto/tls:
prefix, -some used atls:
prefix, and some had no prefix at all. --When generating self-signed certificates, the package no longer sets the -“Authority Key Identifier” field by default. -
-- -
- crypto/x509
- -- -
--The new function -
-SystemCertPool
-provides access to the entire system certificate pool if available. -There is also a new associated error type -SystemRootsError
. -- -
- debug/dwarf
- -- -
--The -
-Reader
type's new -SeekPC
method and the -Data
type's new -Ranges
method -help to find the compilation unit to pass to a -LineReader
-and to identify the specific function for a given program counter. -- -
- debug/elf
- -- -
--The new -
-R_390
relocation type -and its many predefined constants -support the S390 port. -- -
- encoding/asn1
- -- -
--The ASN.1 decoder now rejects non-minimal integer encodings. -This may cause the package to reject some invalid but formerly accepted ASN.1 data. -
-- -
- encoding/json
- -- -
--The -
- -Encoder
's new -SetIndent
method -sets the indentation parameters for JSON encoding, -like in the top-level -Indent
function. --The -
- -Encoder
's new -SetEscapeHTML
method -controls whether the -&
,<
, and>
-characters in quoted strings should be escaped as -\u0026
,\u003c
, and\u003e
, -respectively. -As in previous releases, the encoder defaults to applying this escaping, -to avoid certain problems that can arise when embedding JSON in HTML. --In earlier versions of Go, this package only supported encoding and decoding -maps using keys with string types. -Go 1.7 adds support for maps using keys with integer types: -the encoding uses a quoted decimal representation as the JSON key. -Go 1.7 also adds support for encoding maps using non-string keys that implement -the
- -MarshalText
-(see -encoding.TextMarshaler
) -method, -as well as support for decoding maps using non-string keys that implement -theUnmarshalText
-(see -encoding.TextUnmarshaler
) -method. -These methods are ignored for keys with string types in order to preserve -the encoding and decoding used in earlier versions of Go. --When encoding a slice of typed bytes, -
-Marshal
-now generates an array of elements encoded using -that byte type's -MarshalJSON
-or -MarshalText
-method if present, -only falling back to the default base64-encoded string data if neither method is available. -Earlier versions of Go accept both the original base64-encoded string encoding -and the array encoding (assuming the byte type also implements -UnmarshalJSON
-or -UnmarshalText
-as appropriate), -so this change should be semantically backwards compatible with earlier versions of Go, -even though it does change the chosen encoding. -- -
- go/build
- -- -
--To implement the go command's new support for binary-only packages -and for Fortran code in cgo-based packages, -the -
-Package
type -adds new fieldsBinaryOnly
,CgoFFLAGS
, andFFiles
. -- -
- go/doc
- -- -
--To support the corresponding change in
-go
test
described above, -Example
struct adds a Unordered field -indicating whether the example may generate its output lines in any order. -- -
- io
- -- -
--The package adds new constants -
-SeekStart
,SeekCurrent
, andSeekEnd
, -for use with -Seeker
-implementations. -These constants are preferred overos.SEEK_SET
,os.SEEK_CUR
, andos.SEEK_END
, -but the latter will be preserved for compatibility. -- -
- math/big
- -- -
--The -
-Float
type adds -GobEncode
and -GobDecode
methods, -so that values of typeFloat
can now be encoded and decoded using the -encoding/gob
-package. -- -
- math/rand
- -- -
--The -
- -Read
function and -Rand
's -Read
method -now produce a pseudo-random stream of bytes that is consistent and not -dependent on the size of the input buffer. --The documentation clarifies that -Rand's
-Seed
-andRead
methods -are not safe to call concurrently, though the global -functionsSeed
-andRead
are (and have -always been) safe. -- -
- mime/multipart
- -- -
--The -
-Writer
-implementation now emits each multipart section's header sorted by key. -Previously, iteration over a map caused the section header to use a -non-deterministic order. -- -
- net
- -- -
--As part of the introduction of context, the -
- -Dialer
type has a new method -DialContext
, like -Dial
but adding the -context.Context
-for the dial operation. -The context is intended to obsolete theDialer
's -Cancel
andDeadline
fields, -but the implementation continues to respect them, -for backwards compatibility. --The -
- -IP
type's -String
method has changed its result for invalidIP
addresses. -In past releases, if anIP
byte slice had length other than 0, 4, or 16,String
-returned"?"
. -Go 1.7 adds the hexadecimal encoding of the bytes, as in"?12ab"
. --The pure Go name resolution -implementation now respects
-nsswitch.conf
's -stated preference for the priority of DNS lookups compared to -local file (that is,/etc/hosts
) lookups. -- -
- net/http
- -- -
--
- -ResponseWriter
's -documentation now makes clear that beginning to write the response -may prevent future reads on the request body. -For maximal compatibility, implementations are encouraged to -read the request body completely before writing any part of the response. --As part of the introduction of context, the -
- -Request
has a new methods -Context
, to retrieve the associated context, and -WithContext
, to construct a copy ofRequest
-with a modified context. --In the -
- -Server
implementation, -Serve
records in the request context -both the underlying*Server
using the keyServerContextKey
-and the local address on which the request was received (a -Addr
) using the keyLocalAddrContextKey
. -For example, the address on which a request received is -req.Context().Value(http.LocalAddrContextKey).(net.Addr)
. --The server's
- -Serve
method -now only enables HTTP/2 support if theServer.TLSConfig
field isnil
-or includes"h2"
in itsTLSConfig.NextProtos
. --The server implementation now -pads response codes less than 100 to three digits -as required by the protocol, -so that
- -w.WriteHeader(5)
uses the HTTP response -status005
, not just5
. --The server implementation now correctly sends only one "Transfer-Encoding" header when "chunked" -is set explicitly, following RFC 7230. -
- --The server implementation is now stricter about rejecting requests with invalid HTTP versions. -Invalid requests claiming to be HTTP/0.x are now rejected (HTTP/0.9 was never fully supported), -and plaintext HTTP/2 requests other than the "PRI * HTTP/2.0" upgrade request are now rejected as well. -The server continues to handle encrypted HTTP/2 requests. -
- --In the server, a 200 status code is sent back by the timeout handler on an empty -response body, instead of sending back 0 as the status code. -
- --In the client, the -
- -Transport
implementation passes the request context -to any dial operation connecting to the remote server. -If a custom dialer is needed, the newTransport
field -DialContext
is preferred over the existingDial
field, -to allow the transport to supply a context. --The -
- -Transport
also adds fields -IdleConnTimeout
, -MaxIdleConns
, -and -MaxResponseHeaderBytes
-to help control client resources consumed -by idle or chatty servers. --A -
- -Client
's configuredCheckRedirect
function can now -returnErrUseLastResponse
to indicate that the -most recent redirect response should be returned as the -result of the HTTP request. -That response is now available to theCheckRedirect
function -asreq.Response
. --Since Go 1, the default behavior of the HTTP client is -to request server-side compression -using the
- -Accept-Encoding
request header -and then to decompress the response body transparently, -and this behavior is adjustable using the -Transport
'sDisableCompression
field. -In Go 1.7, to aid the implementation of HTTP proxies, the -Response
's new -Uncompressed
field reports whether -this transparent decompression took place. --
-DetectContentType
-adds support for a few new audio and video content types. -- -
- net/http/cgi
- -- -
--The -
-Handler
-adds a new field -Stderr
-that allows redirection of the child process's -standard error away from the host process's -standard error. -- -
- net/http/httptest
- -- -
--The new function -
- -NewRequest
-prepares a new -http.Request
-suitable for passing to an -http.Handler
during a test. --The -
-ResponseRecorder
's new -Result
method -returns the recorded -http.Response
. -Tests that need to check the response's headers or trailers -should callResult
and inspect the response fields -instead of accessing -ResponseRecorder
'sHeaderMap
directly. -- -
- net/http/httputil
- -- -
--The -
- -ReverseProxy
implementation now responds with “502 Bad Gateway” -when it cannot reach a back end; in earlier releases it responded with “500 Internal Server Error.” --Both -
-ClientConn
and -ServerConn
have been documented as deprecated. -They are low-level, old, and unused by Go's current HTTP stack -and will no longer be updated. -Programs should use -http.Client
, -http.Transport
, -and -http.Server
-instead. -- -
- net/http/pprof
- -- -
--The runtime trace HTTP handler, installed to handle the path
-/debug/pprof/trace
, -now accepts a fractional number in itsseconds
query parameter, -allowing collection of traces for intervals smaller than one second. -This is especially useful on busy servers. -- -
- net/mail
- -- -
--The address parser now allows unescaped UTF-8 text in addresses -following RFC 6532, -but it does not apply any normalization to the result. -For compatibility with older mail parsers, -the address encoder, namely -
- -Address
's -String
method, -continues to escape all UTF-8 text following RFC 5322. --The
-ParseAddress
-function and -theAddressParser.Parse
-method are stricter. -They used to ignore any characters following an e-mail address, but -will now return an error for anything other than whitespace. -- -
- net/url
- -- -
--The -
-URL
's -newForceQuery
field -records whether the URL must have a query string, -in order to distinguish URLs without query strings (like/search
) -from URLs with empty query strings (like/search?
). -- -
- os
- -- -
--
- -IsExist
now returns true forsyscall.ENOTEMPTY
, -on systems where that error exists. --On Windows, -
-Remove
now removes read-only files when possible, -making the implementation behave as on -non-Windows systems. -- -
- os/exec
- -- -
--As part of the introduction of context, -the new constructor -
-CommandContext
-is like -Command
but includes a context that can be used to cancel the command execution. -- -
- os/user
- -- -
--The -
- -Current
-function is now implemented even when cgo is not available. --The new -
-Group
type, -along with the lookup functions -LookupGroup
and -LookupGroupId
-and the new fieldGroupIds
in theUser
struct, -provides access to system-specific user group information. -- -
- reflect
- -- -
--Although -
- -Value
's -Field
method has always been documented to panic -if the given field numberi
is out of range, it has instead -silently returned a zero -Value
. -Go 1.7 changes the method to behave as documented. --The new -
- -StructOf
-function constructs a struct type at run time. -It completes the set of type constructors, joining -ArrayOf
, -ChanOf
, -FuncOf
, -MapOf
, -PtrTo
, -and -SliceOf
. --
- -StructTag
's -new method -Lookup
-is like -Get
-but distinguishes the tag not containing the given key -from the tag associating an empty string with the given key. --The -
-Method
and -NumMethod
-methods of -Type
and -Value
-no longer return or count unexported methods. -- -
- strings
- -- -
--In previous releases of Go, if -
- -Reader
's -Read
method -were asked for zero bytes with no data remaining, it would -return a count of 0 and no error. -Now it returns a count of 0 and the error -io.EOF
. --The -
-Reader
type has a new method -Reset
to allow reuse of aReader
. -- -
- time
- -- -
--
- -Duration
's -time.Duration.String method now reports the zero duration as"0s"
, not"0"
. -ParseDuration
continues to accept both forms. --The method call
- -time.Local.String()
now returns"Local"
on all systems; -in earlier releases, it returned an empty string on Windows. --The time zone database in -
-$GOROOT/lib/time
has been updated -to IANA release 2016d. -This fallback database is only used when the system time zone database -cannot be found, for example on Windows. -The Windows time zone abbreviation list has also been updated. -- - -
- syscall
- -- -
--On Linux, the -
-SysProcAttr
struct -(as used in -os/exec.Cmd
'sSysProcAttr
field) -has a newUnshareflags
field. -If the field is nonzero, the child process created by -ForkExec
-(as used inexec.Cmd
'sRun
method) -will call the -unshare(2) -system call before executing the new program. -diff --git a/content/doc/go1.8.html b/content/doc/go1.8.html deleted file mode 100644 index 611f5ee2..00000000 --- a/content/doc/go1.8.html +++ /dev/null @@ -1,1666 +0,0 @@ - - - - - - -
- unicode
- -- -
--The
-unicode
package and associated -support throughout the system has been upgraded from version 8.0 to -Unicode 9.0. -Introduction to Go 1.8
- --The latest Go release, version 1.8, arrives six months after Go 1.7. -Most of its changes are in the implementation of the toolchain, runtime, and libraries. -There are two minor changes to the language specification. -As always, the release maintains the Go 1 promise of compatibility. -We expect almost all Go programs to continue to compile and run as before. -
- --The release adds support for 32-bit MIPS, -updates the compiler back end to generate more efficient code, -reduces GC pauses by eliminating stop-the-world stack rescanning, -adds HTTP/2 Push support, -adds HTTP graceful shutdown, -adds more context support, -enables profiling mutexes, -and simplifies sorting slices. -
- -Changes to the language
- -- When explicitly converting a value from one struct type to another, - as of Go 1.8 the tags are ignored. Thus two structs that differ - only in their tags may be converted from one to the other: -
- --func example() { - type T1 struct { - X int `json:"foo"` - } - type T2 struct { - X int `json:"bar"` - } - var v1 T1 - var v2 T2 - v1 = T1(v2) // now legal -} -- - -- The language specification now only requires that implementations - support up to 16-bit exponents in floating-point constants. This does not affect - either the “
- -gc
” or -gccgo
compilers, both of - which still support 32-bit exponents. -Ports
- --Go now supports 32-bit MIPS on Linux for both big-endian -(
- -linux/mips
) and little-endian machines -(linux/mipsle
) that implement the MIPS32r1 instruction set with FPU -or kernel FPU emulation. Note that many common MIPS-based routers lack an FPU and -have firmware that doesn't enable kernel FPU emulation; Go won't run on such machines. --On DragonFly BSD, Go now requires DragonFly 4.4.4 or later. -
- --On OpenBSD, Go now requires OpenBSD 5.9 or later. -
- --The Plan 9 port's networking support is now much more complete -and matches the behavior of Unix and Windows with respect to deadlines -and cancelation. For Plan 9 kernel requirements, see the -Plan 9 wiki page. -
- -- Go 1.8 now only supports OS X 10.8 or later. This is likely the last - Go release to support 10.8. Compiling Go or running - binaries on older OS X versions is untested. -
- -- Go 1.8 will be the last release to support Linux on ARMv5E and ARMv6 processors: - Go 1.9 will likely require the ARMv6K (as found in the Raspberry Pi 1) or later. - To identify whether a Linux system is ARMv6K or later, run - “
- - -go
tool
dist
-check-armv6k
” - (to facilitate testing, it is also possible to just copy thedist
command to the - system without installing a full copy of Go 1.8) - and if the program terminates with output "ARMv6K supported." then the system - implements ARMv6K or later. - Go on non-Linux ARM systems already requires ARMv6K or later. -Known Issues
- --There are some instabilities on FreeBSD and NetBSD that are known but not understood. -These can lead to program crashes in rare cases. -See -issue 15658 and -issue 16511. -Any help in solving these issues would be appreciated. -
- -Tools
- -Assembler
- --For 64-bit x86 systems, the following instructions have been added: -
- -VBROADCASTSD
, -BROADCASTSS
, -MOVDDUP
, -MOVSHDUP
, -MOVSLDUP
, -VMOVDDUP
, -VMOVSHDUP
, and -VMOVSLDUP
. --For 64-bit PPC systems, the common vector scalar instructions have been -added: -
- -LXS
, -LXSDX
, -LXSI
, -LXSIWAX
, -LXSIWZX
, -LXV
, -LXVD2X
, -LXVDSX
, -LXVW4X
, -MFVSR
, -MFVSRD
, -MFVSRWZ
, -MTVSR
, -MTVSRD
, -MTVSRWA
, -MTVSRWZ
, -STXS
, -STXSDX
, -STXSI
, -STXSIWX
, -STXV
, -STXVD2X
, -STXVW4X
, -XSCV
, -XSCVDPSP
, -XSCVDPSPN
, -XSCVDPSXDS
, -XSCVDPSXWS
, -XSCVDPUXDS
, -XSCVDPUXWS
, -XSCVSPDP
, -XSCVSPDPN
, -XSCVSXDDP
, -XSCVSXDSP
, -XSCVUXDDP
, -XSCVUXDSP
, -XSCVX
, -XSCVXP
, -XVCV
, -XVCVDPSP
, -XVCVDPSXDS
, -XVCVDPSXWS
, -XVCVDPUXDS
, -XVCVDPUXWS
, -XVCVSPDP
, -XVCVSPSXDS
, -XVCVSPSXWS
, -XVCVSPUXDS
, -XVCVSPUXWS
, -XVCVSXDDP
, -XVCVSXDSP
, -XVCVSXWDP
, -XVCVSXWSP
, -XVCVUXDDP
, -XVCVUXDSP
, -XVCVUXWDP
, -XVCVUXWSP
, -XVCVX
, -XVCVXP
, -XXLAND
, -XXLANDC
, -XXLANDQ
, -XXLEQV
, -XXLNAND
, -XXLNOR
, -XXLOR
, -XXLORC
, -XXLORQ
, -XXLXOR
, -XXMRG
, -XXMRGHW
, -XXMRGLW
, -XXPERM
, -XXPERMDI
, -XXSEL
, -XXSI
, -XXSLDWI
, -XXSPLT
, and -XXSPLTW
. -Yacc
- --The
- -yacc
tool (previously available by running -“go
tool
yacc
”) has been removed. -As of Go 1.7 it was no longer used by the Go compiler. -It has moved to the “tools” repository and is now available at -golang.org/x/tools/cmd/goyacc
. -Fix
- -- The
- -fix
tool has a new “context
” - fix to change imports from “golang.org/x/net/context
” - to “context
”. -Pprof
- -- The
- -pprof
tool can now profile TLS servers - and skip certificate validation by using the “https+insecure
” - URL scheme. -- The callgrind output now has instruction-level granularity. -
- -Trace
- -- The
- -trace
tool has a new-pprof
flag for - producing pprof-compatible blocking and latency profiles from an - execution trace. -- Garbage collection events are now shown more clearly in the - execution trace viewer. Garbage collection activity is shown on its - own row and GC helper goroutines are annotated with their roles. -
- -Vet
- -Vet is stricter in some ways and looser where it - previously caused false positives.
- -Vet now checks for copying an array of locks, - duplicate JSON and XML struct field tags, - non-space-separated struct tags, - deferred calls to HTTP
- - -Response.Body.Close
- before checking errors, and - indexed arguments inPrintf
. - It also improves existing checks.Compiler Toolchain
- --Go 1.7 introduced a new compiler back end for 64-bit x86 systems. -In Go 1.8, that back end has been developed further and is now used for -all architectures. -
- --The new back end, based on -static single assignment form (SSA), -generates more compact, more efficient code -and provides a better platform for optimizations -such as bounds check elimination. -The new back end reduces the CPU time required by -our benchmark programs by 20-30% -on 32-bit ARM systems. For 64-bit x86 systems, which already used the SSA back end in -Go 1.7, the gains are a more modest 0-10%. Other architectures will likely -see improvements closer to the 32-bit ARM numbers. -
- -- The temporary
- --ssa=0
compiler flag introduced in Go 1.7 - to disable the new back end has been removed in Go 1.8. -- In addition to enabling the new compiler back end for all systems, - Go 1.8 also introduces a new compiler front end. The new compiler - front end should not be noticeable to users but is the foundation for - future performance work. -
- -- The compiler and linker have been optimized and run faster in this - release than in Go 1.7, although they are still slower than we would - like and will continue to be optimized in future releases. - Compared to the previous release, Go 1.8 is - about 15% faster. -
- -Cgo
- --The Go tool now remembers the value of the
- -CGO_ENABLED
environment -variable set duringmake.bash
and applies it to all future compilations -by default to fix issue #12808. -When doing native compilation, it is rarely necessary to explicitly set -theCGO_ENABLED
environment variable asmake.bash
-will detect the correct setting automatically. The main reason to explicitly -set theCGO_ENABLED
environment variable is when your environment -supports cgo, but you explicitly do not want cgo support, in which case, set -CGO_ENABLED=0
duringmake.bash
orall.bash
. --The environment variable
- -PKG_CONFIG
may now be used to -set the program to run to handle#cgo
pkg-config
-directives. The default ispkg-config
, the program -always used by earlier releases. This is intended to make it easier -to cross-compile -cgo code. --The cgo tool now supports a
- --srcdir
-option, which is used by the go command. --If cgo code calls
- -C.malloc
, and -malloc
returnsNULL
, the program will now -crash with an out of memory error. -C.malloc
will never returnnil
. -Unlike most C functions,C.malloc
may not be used in a -two-result form returning an errno value. --If cgo is used to call a C function passing a -pointer to a C union, and if the C union can contain any pointer -values, and if cgo pointer -checking is enabled (as it is by default), the union value is now -checked for Go pointers. -
- -Gccgo
- --Due to the alignment of Go's semiannual release schedule with GCC's -annual release schedule, -GCC release 6 contains the Go 1.6.1 version of gccgo. -We expect that the next release, GCC 7, will contain the Go 1.8 -version of gccgo. -
- -Default GOPATH
- -- The -
- -GOPATH
- environment variable now has a default value if it - is unset. It defaults to -$HOME/go
on Unix and -%USERPROFILE%/go
on Windows. -Go get
- -- The “
- -go
get
” command now always respects - HTTP proxy environment variables, regardless of whether - the-insecure
flag is used. In previous releases, the --insecure
flag had the side effect of not using proxies. -Go bug
- -- The new - “
- -go
bug
” - command starts a bug report on GitHub, prefilled - with information about the current system. -Go doc
- -- The - “
- -go
doc
” - command now groups constants and variables with their type, - following the behavior of -godoc
. -- In order to improve the readability of
- -doc
's - output, each summary of the first-level items is guaranteed to - occupy a single line. -- Documentation for a specific method in an interface definition can - now be requested, as in - “
- -go
doc
net.Conn.SetDeadline
”. -Plugins
- -- Go now provides early support for plugins with a “
- -plugin
” - build mode for generating plugins written in Go, and a - newplugin
package for - loading such plugins at run time. Plugin support is currently only - available on Linux. Please report any issues. -Runtime
- -Argument Liveness
- -- The garbage collector no longer considers - arguments live throughout the entirety of a function. For more - information, and for how to force a variable to remain live, see - the
- -runtime.KeepAlive
- function added in Go 1.7. -- Updating: - Code that sets a finalizer on an allocated object may need to add - calls to
- -runtime.KeepAlive
in functions or methods - using that object. - Read the -KeepAlive
- documentation and its example for more details. -Concurrent Map Misuse
- --In Go 1.6, the runtime -added lightweight, -best-effort detection of concurrent misuse of maps. This release -improves that detector with support for detecting programs that -concurrently write to and iterate over a map. -
--As always, if one goroutine is writing to a map, no other goroutine should be -reading (which includes iterating) or writing the map concurrently. -If the runtime detects this condition, it prints a diagnosis and crashes the program. -The best way to find out more about the problem is to run the program -under the -race detector, -which will more reliably identify the race -and give more detail. -
- -MemStats Documentation
- -- The
- -runtime.MemStats
- type has been more thoroughly documented. -Performance
- --As always, the changes are so general and varied that precise statements -about performance are difficult to make. -Most programs should run a bit faster, -due to speedups in the garbage collector and -optimizations in the standard library. -
- --There have been optimizations to implementations in the -
- -bytes
, -crypto/aes
, -crypto/cipher
, -crypto/elliptic
, -crypto/sha256
, -crypto/sha512
, -encoding/asn1
, -encoding/csv
, -encoding/hex
, -encoding/json
, -hash/crc32
, -image/color
, -image/draw
, -math
, -math/big
, -reflect
, -regexp
, -runtime
, -strconv
, -strings
, -syscall
, -text/template
, and -unicode/utf8
-packages. -Garbage Collector
- -- Garbage collection pauses should be significantly shorter than they - were in Go 1.7, usually under 100 microseconds and often as low as - 10 microseconds. - See the - document on eliminating stop-the-world stack re-scanning - for details. More work remains for Go 1.9. -
- -Defer
- - -- The overhead of deferred - function calls has been reduced by about half. -
- -Cgo
- -The overhead of calls from Go into C has been reduced by about half.
- -Standard library
- -Examples
- --Examples have been added to the documentation across many packages. -
- -Sort
- --The sort package -now includes a convenience function -
- -Slice
to sort a -slice given a less function. - -In many cases this means that writing a new sorter type is not -necessary. --Also new are -
- -SliceStable
and -SliceIsSorted
. -HTTP/2 Push
- --The net/http package now includes a -mechanism to -send HTTP/2 server pushes from a -
- -Handler
. -Similar to the existingFlusher
andHijacker
-interfaces, an HTTP/2 -ResponseWriter
-now implements the new -Pusher
interface. -HTTP Server Graceful Shutdown
- -- The HTTP Server now has support for graceful shutdown using the new -
- -Server.Shutdown
- method and abrupt shutdown using the new -Server.Close
- method. -More Context Support
- -- Continuing Go 1.7's adoption - of
- -context.Context
- into the standard library, Go 1.8 adds more context support - to existing packages: --
- -- The new
-Server.Shutdown
- takes a context argument.- There have been significant additions to the - database/sql package with context support.
-- All nine of the new
-Lookup
methods on the new -net.Resolver
now - take a context.Mutex Contention Profiling
- -- The runtime and tools now support profiling contended mutexes. -
- -- Most users will want to use the new
- --mutexprofile
- flag with “go
test
”, - and then use pprof on the resultant file. -- Lower-level support is also available via the new -
- -MutexProfile
- and -SetMutexProfileFraction
. -- A known limitation for Go 1.8 is that the profile only reports contention for -
- -sync.Mutex
, - not -sync.RWMutex
. -Minor changes to the library
- --As always, there are various minor changes and updates to the library, -made with the Go 1 promise of compatibility -in mind. The following sections list the user visible changes and additions. -Optimizations and minor bug fixes are not listed. -
- -- -
- archive/tar
-- - -
-- The tar implementation corrects many bugs in corner cases of the file format. - The
- -Reader
- is now able to process tar files in the PAX format with entries larger than 8GB. - TheWriter
- no longer produces invalid tar files in some situations involving long pathnames. -- - -
- compress/flate
-- - -
-- There have been some minor fixes to the encoder to improve the - compression ratio in certain situations. As a result, the exact - encoded output of
- -DEFLATE
may be different from Go 1.7. Since -DEFLATE
is the underlying compression of gzip, png, zlib, and zip, - those formats may have changed outputs. -- The encoder, when operating in -
- -NoCompression
- mode, now produces a consistent output that is not dependent on - the size of the slices passed to the -Write
- method. -- The decoder, upon encountering an error, now returns any - buffered data it had uncompressed along with the error. -
- -- -
- compress/gzip
-- - -
-- The
- -Writer
- now encodes a zeroMTIME
field when - theHeader.ModTime
- field is the zero value. - - In previous releases of Go, theWriter
would encode - a nonsensical value. - - Similarly, - theReader
- now reports a zero encodedMTIME
field as a zero -Header.ModTime
. -- -
- context
-- -
-- The
-DeadlineExceeded
- error now implements -net.Error
- and reports true for both theTimeout
and -Temporary
methods. -- -
- crypto/tls
-- -
-- The new method -
- -Conn.CloseWrite
- allows TLS connections to be half closed. -- The new method -
- -Config.Clone
- clones a TLS configuration. -- - The new
- -Config.GetConfigForClient
- callback allows selecting a configuration for a client dynamically, based - on the client's -ClientHelloInfo
. - - - TheClientHelloInfo
- struct now has new - fieldsConn
,SignatureSchemes
(using - the new - typeSignatureScheme
), -SupportedProtos
, andSupportedVersions
. -- The new
- -Config.GetClientCertificate
- callback allows selecting a client certificate based on the server's - TLSCertificateRequest
message, represented by the new -CertificateRequestInfo
. -- The new -
- -Config.KeyLogWriter
- allows debugging TLS connections - in WireShark and - similar tools. -- The new -
- -Config.VerifyPeerCertificate
- callback allows additional validation of a peer's presented certificate. -- The
- -crypto/tls
package now implements basic - countermeasures against CBC padding oracles. There should be - no explicit secret-dependent timings, but it does not attempt to - normalize memory accesses to prevent cache timing leaks. -- The
- -crypto/tls
package now supports - X25519 and - ChaCha20-Poly1305. - ChaCha20-Poly1305 is now prioritized unless - hardware support for AES-GCM is present. -- AES-128-CBC cipher suites with SHA-256 are also - now supported, but disabled by default. -
- -- -
- crypto/x509
-- -
-- PSS signatures are now supported. -
- --
- -UnknownAuthorityError
- now has aCert
field, reporting the untrusted - certificate. -- Certificate validation is more permissive in a few cases and - stricter in a few other cases. - -
- -- Root certificates will now also be looked for - at
- -/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem
- on Linux, to support RHEL and CentOS. -- -
- database/sql
-- -
-- The package now supports
-context.Context
. There are new methods - ending inContext
such as -DB.QueryContext
and -DB.PrepareContext
- that take context arguments. Using the newContext
methods ensures that - connections are closed and returned to the connection pool when the - request is done; enables canceling in-progress queries - should the driver support that; and allows the database - pool to cancel waiting for the next available connection. -- The
-IsolationLevel
- can now be set when starting a transaction by setting the isolation level - onTxOptions.Isolation
and passing - it toDB.BeginTx
. - An error will be returned if an isolation level is selected that the driver - does not support. A read-only attribute may also be set on the transaction - by settingTxOptions.ReadOnly
- to true. -- Queries now expose the SQL column type information for drivers that support it. - Rows can return
-ColumnTypes
- which can include SQL type information, column type lengths, and the Go type. -- A
-Rows
- can now represent multiple result sets. After -Rows.Next
returns false, -Rows.NextResultSet
- may be called to advance to the next result set. The existingRows
- should continue to be used after it advances to the next result set. --
NamedArg
may be used - as query arguments. The new functionNamed
- helps create aNamedArg
- more succinctly. -- If a driver supports the new -
-Pinger
- interface, the -DB.Ping
- and -DB.PingContext
- methods will use that interface to check whether a - database connection is still valid. -- The new
-Context
query methods work for all drivers, but -Context
cancelation is not responsive unless the driver has been - updated to use them. The other features require driver support in -database/sql/driver
. - Driver authors should review the new interfaces. Users of existing - driver should review the driver documentation to see what - it supports and any system specific documentation on each feature. -- -
- debug/pe
-- -
-- The package has been extended and is now used by - the Go linker to read
-gcc
-generated object files. - The new -File.StringTable
- and -Section.Relocs
- fields provide access to the COFF string table and COFF relocations. - The new -File.COFFSymbols
- allows low-level access to the COFF symbol table. -- - - -
- encoding/base64
-- -
-- The new -
-Encoding.Strict
- method returns anEncoding
that causes the decoder - to return an error when the trailing padding bits are not zero. -- -
- encoding/json
-- - -
--
- -UnmarshalTypeError
- now includes the struct and field name. -- A nil
- -Marshaler
- now marshals as a JSONnull
value. -- A
- -RawMessage
value now - marshals the same as its pointer type. --
- -Marshal
- encodes floating-point numbers using the same format as in ES6, - preferring decimal (not exponential) notation for a wider range of values. - In particular, all floating-point integers up to 264 format the - same as the equivalentint64
representation. -- In previous versions of Go, unmarshaling a JSON
- -null
into an -Unmarshaler
- was considered a no-op; now theUnmarshaler
's -UnmarshalJSON
method is called with the JSON literal -null
and can define the semantics of that case. -- -
- encoding/pem
-- -
--
-Decode
- is now strict about the format of the ending line. -- -
- encoding/xml
-- -
--
-Unmarshal
- now has wildcard support for collecting all attributes using - the new",any,attr"
struct tag. -- -
- expvar
-- -
-- The new methods -
- -Int.Value
, -String.Value
, -Float.Value
, and -Func.Value
- report the current value of an exported variable. -- The new - function
-Handler
- returns the package's HTTP handler, to enable installing it in - non-standard locations. -- -
- fmt
-- -
--
-Scanf
, -Fscanf
, and -Sscanf
now - handle spaces differently and more consistently than - previous releases. See the - scanning documentation - for details. -- -
- go/doc
-- -
-- The new
-IsPredeclared
- function reports whether a string is a predeclared identifier. -- -
- go/types
-- -
-- The new function -
- -Default
- returns the default "typed" type for an "untyped" type. -- The alignment of
-complex64
now matches - the Go compiler. -- -
- html/template
-- -
-- The package now validates - the
-"type"
attribute on - a<script>
tag. -- -
- image/png
-- -
--
-Decode
- (andDecodeConfig
) - now supports True Color and grayscale transparency. --
-Encoder
- is now faster and creates smaller output - when encoding paletted images. -- -
- math/big
-- -
-- The new method -
- -Int.Sqrt
- calculates ⌊√x⌋. -- The new method -
- -Float.Scan
- is a support routine for -fmt.Scanner
. --
- -Int.ModInverse
- now supports negative numbers. -- -
- math/rand
-- - -
-- The new
- -Rand.Uint64
- method returnsuint64
values. The - newSource64
- interface describes sources capable of generating such values - directly; otherwise theRand.Uint64
method - constructs auint64
from two calls - toSource
's -Int63
method. -- -
- mime
-- -
--
-ParseMediaType
- now preserves unnecessary backslash escapes as literals, - in order to support MSIE. - When MSIE sends a full file path (in “intranet mode”), it does not - escape backslashes: “C:\dev\go\foo.txt
”, not - “C:\\dev\\go\\foo.txt
”. - If we see an unnecessary backslash escape, we now assume it is from MSIE - and intended as a literal backslash. - No known MIME generators emit unnecessary backslash escapes - for simple token characters like numbers and letters. -- -
- mime/quotedprintable
-- - -
-- The -
- -Reader
's - parsing has been relaxed in two ways to accept - more input seen in the wild. - - - First, it accepts an equals sign (=
) not followed - by two hex digits as a literal equal sign. - - - Second, it silently ignores a trailing equals sign at the end of - an encoded input. -- -
- net
-- - -
-- The
-Conn
documentation - has been updated to clarify expectations of an interface - implementation. Updates in thenet/http
packages - depend on implementations obeying the documentation. -Updating: implementations of the
- -Conn
interface should verify - they implement the documented semantics. The - golang.org/x/net/nettest - package will exercise aConn
and validate it behaves properly. -- The new method -
- -UnixListener.SetUnlinkOnClose
- sets whether the underlying socket file should be removed from the file system when - the listener is closed. -- The new
- -Buffers
type permits - writing to the network more efficiently from multiple discontiguous buffers - in memory. On certain machines, for certain types of connections, - this is optimized into an OS-specific batch write operation (such aswritev
). -- The new
- -Resolver
looks up names and numbers - and supportscontext.Context
. - TheDialer
now has an optional -Resolver
field. --
- -Interfaces
is now supported on Solaris. -- The Go DNS resolver now supports
- -resolv.conf
's “rotate
” - and “option
ndots:0
” options. The “ndots
” option is - now respected in the same way aslibresolve
. -- -
- net/http
-- - -
-Server changes:
--
- -- The server now supports graceful shutdown support, mentioned above.
- -- - The
- -Server
- adds configuration options -ReadHeaderTimeout
andIdleTimeout
- and documentsWriteTimeout
. -- -
-FileServer
- and -ServeContent
- now support HTTPIf-Match
conditional requests, - in addition to the previousIf-None-Match
- support for ETags properly formatted according to RFC 7232, section 2.3. -- There are several additions to what a server's
- -Handler
can do: --
- -- - The
- -Context
- returned - byRequest.Context
- is canceled if the underlyingnet.Conn
- closes. For instance, if the user closes their browser in the - middle of a slow request, theHandler
can now - detect that the user is gone. This complements the - existingCloseNotifier
- support. This functionality requires that the underlying -net.Conn
implements - recently clarified interface documentation. -- - To serve trailers produced after the header has already been written, - see the new -
- -TrailerPrefix
- mechanism. -- - A
- -Handler
can now abort a response by panicking - with the error -ErrAbortHandler
. -- - A
- -Write
of zero bytes to a -ResponseWriter
- is now defined as a - way to test whether aResponseWriter
has been hijacked: - if so, theWrite
returns -ErrHijacked
- without printing an error - to the server's error log. -Client & Transport changes:
--
- -- - The
- -Client
- now copies most request headers on redirect. See - the documentation - on theClient
type for details. -- - The
- -Transport
- now supports international domain names. Consequently, so do - Get and other helpers. -- - The
- -Client
now supports 301, 307, and 308 redirects. - - For example,Client.Post
now follows 301 - redirects, converting them toGET
requests - without bodies, like it did for 302 and 303 redirect responses - previously. - - TheClient
now also follows 307 and 308 - redirects, preserving the original request method and body, if - any. If the redirect requires resending the request body, the - request must have the new -Request.GetBody
- field defined. -NewRequest
- setsRequest.GetBody
automatically for common - body types. -- - The
- -Transport
now rejects requests for URLs with - ports containing non-digit characters. -- - The
- -Transport
will now retry non-idempotent - requests if no bytes were written before a network failure - and the request has no body. -- - The - new
- -Transport.ProxyConnectHeader
- allows configuration of header values to send to a proxy - during aCONNECT
request. -- - The
- -DefaultTransport.Dialer
- now enablesDualStack
("Happy Eyeballs") support, - allowing the use of IPv4 as a backup if it looks like IPv6 might be - failing. -- - The
-Transport
- no longer reads a byte of a non-nil -Request.Body
- when the -Request.ContentLength
- is zero to determine whether theContentLength
- is actually zero or just undefined. - To explicitly signal that a body has zero length, - either set it tonil
, or set it to the new value -NoBody
. - The newNoBody
value is intended for use byRequest
- constructor functions; it is used by -NewRequest
. -- -
- net/http/httptrace
-- -
-- There is now support for tracing a client request's TLS handshakes with - the new -
-ClientTrace.TLSHandshakeStart
- and -ClientTrace.TLSHandshakeDone
. -- -
- net/http/httputil
-- -
-- The
- -ReverseProxy
- has a new optional hook, -ModifyResponse
, - for modifying the response from the back end before proxying it to the client. -- -
- net/mail
-- - -
-- Empty quoted strings are once again allowed in the name part of - an address. That is, Go 1.4 and earlier accepted -
- -""
<gopher@example.com>
, - but Go 1.5 introduced a bug that rejected this address. - The address is recognized again. -- The -
- -Header.Date
- method has always provided a way to parse - theDate:
header. - A new function -ParseDate
- allows parsing dates found in other - header lines, such as theResent-Date:
header. -- -
- net/smtp
-- - -
-- If an implementation of the -
- -Auth.Start
- method returns an emptytoServer
value, - the package no longer sends - trailing whitespace in the SMTPAUTH
command, - which some servers rejected. -- -
- net/url
-- - -
-- The new functions -
- -PathEscape
- and -PathUnescape
- are similar to the query escaping and unescaping functions but - for path elements. -- The new methods -
- -URL.Hostname
- and -URL.Port
- return the hostname and port fields of a URL, - correctly handling the case where the port may not be present. -- The existing method -
- -URL.ResolveReference
- now properly handles paths with escaped bytes without losing - the escaping. -- The
- -URL
type now implements -encoding.BinaryMarshaler
and -encoding.BinaryUnmarshaler
, - making it possible to process URLs in gob data. -- Following RFC 3986, -
- -Parse
- now rejects URLs likethis_that:other/thing
instead of - interpreting them as relative paths (this_that
is not a valid scheme). - To force interpretation as a relative path, - such URLs should be prefixed with “./
”. - TheURL.String
method now inserts this prefix as needed. -- -
- os
-- -
-- The new function -
- -Executable
returns - the path name of the running executable. -- An attempt to call a method on - an
- -os.File
that has - already been closed will now return the new error - valueos.ErrClosed
. - Previously it returned a system-specific error such - assyscall.EBADF
. -- On Unix systems,
- -os.Rename
- will now return an error when used to rename a directory to an - existing empty directory. - Previously it would fail when renaming to a non-empty directory - but succeed when renaming to an empty directory. - This makes the behavior on Unix correspond to that of other systems. -- On Windows, long absolute paths are now transparently converted to - extended-length paths (paths that start with “
- -\\?\
”). - This permits the package to work with files whose path names are - longer than 260 characters. -- On Windows,
- -os.IsExist
- will now returntrue
for the system - errorERROR_DIR_NOT_EMPTY
. - This roughly corresponds to the existing handling of the Unix - errorENOTEMPTY
. -- On Plan 9, files that are not served by
-#M
will now - haveModeDevice
set in - the value returned - byFileInfo.Mode
. -- -
- path/filepath
-- -
-- A number of bugs and corner cases on Windows were fixed: -
-Abs
now callsClean
as documented, -Glob
now matches - “\\?\c:\*
”, -EvalSymlinks
now - correctly handles “C:.
”, and -Clean
now properly - handles a leading “..
” in the path. -- -
- reflect
-- -
-- The new function -
-Swapper
was - added to supportsort.Slice
. -- -
- strconv
-- -
-- The
-Unquote
- function now strips carriage returns (\r
) in - backquoted raw strings, following the - Go language semantics. -- -
- syscall
-- -
-- The
- -Getpagesize
- now returns the system's size, rather than a constant value. - Previously it always returned 4KB. -- The signature - of
- -Utimes
has - changed on Solaris to match all the other Unix systems' - signature. Portable code should continue to use -os.Chtimes
instead. -- The
-X__cmsg_data
field has been removed from -Cmsghdr
. -- -
- text/template
-- -
--
- -Template.Execute
- can now take a -reflect.Value
as its data - argument, and -FuncMap
- functions can also accept and returnreflect.Value
. -- -
- time
-- - -
-The new function -
- -Until
complements - the analogousSince
function. --
- -ParseDuration
- now accepts long fractional parts. --
- -Parse
- now rejects dates before the start of a month, such as June 0; - it already rejected dates beyond the end of the month, such as - June 31 and July 32. -- The
- -tzdata
database has been updated to version - 2016j for systems that don't already have a local time zone - database. --
- -
- testing
-- -
-- The new method -
- -T.Name
- (andB.Name
) returns the name of the current - test or benchmark. -- The new function -
- -CoverMode
- reports the test coverage mode. -- Tests and benchmarks are now marked as failed if the race - detector is enabled and a data race occurs during execution. - Previously, individual test cases would appear to pass, - and only the overall execution of the test binary would fail. -
- -- The signature of the -
- -MainStart
- function has changed, as allowed by the documentation. It is an - internal detail and not part of the Go 1 compatibility promise. - If you're not callingMainStart
directly but see - errors, that likely means you set the - normally-emptyGOROOT
environment variable and it - doesn't match the version of yourgo
command's binary. -diff --git a/content/doc/go1.9.html b/content/doc/go1.9.html deleted file mode 100644 index fa50ae78..00000000 --- a/content/doc/go1.9.html +++ /dev/null @@ -1,1024 +0,0 @@ - - - - - - -
- unicode
-- -
--
-SimpleFold
- now returns its argument unchanged if the provided input was an invalid rune. - Previously, the implementation failed with an index bounds check panic. -Introduction to Go 1.9
- -- The latest Go release, version 1.9, arrives six months - after Go 1.8 and is the tenth release in - the Go 1.x - series. - There are two changes to the language: - adding support for type aliases and defining when implementations - may fuse floating point operations. - Most of the changes are in the implementation of the toolchain, - runtime, and libraries. - As always, the release maintains the Go 1 - promise of compatibility. - We expect almost all Go programs to continue to compile and run as - before. -
- -- The release - adds transparent monotonic time support, - parallelizes compilation of functions within a package, - better supports test helper functions, - includes a new bit manipulation package, - and has a new concurrent map type. -
- -Changes to the language
- -- There are two changes to the language. -
-- Go now supports type aliases to support gradual code repair while - moving a type between packages. - The type alias - design document - and an - article on refactoring cover the problem in detail. - In short, a type alias declaration has the form: -
- --type T1 = T2 -- -- This declaration introduces an alias name
- -T1
—an - alternate spelling—for the type denoted byT2
; that is, - bothT1
andT2
denote the same type. -- A smaller language change is that the - language specification - now states when implementations are allowed to fuse floating - point operations together, such as by using an architecture's "fused - multiply and add" (FMA) instruction to compute
- -x*y
+
z
- without rounding the intermediate resultx*y
. - To force the intermediate rounding, writefloat64(x*y)
+
z
. -Ports
- -- There are no new supported operating systems or processor - architectures in this release. -
- -ppc64x requires POWER8
- -- Both
GOARCH=ppc64
andGOARCH=ppc64le
now - require at least POWER8 support. In previous releases, - onlyGOARCH=ppc64le
required POWER8 and the big - endianppc64
architecture supported older - hardware. -- -
FreeBSD
- -- Go 1.9 is the last release that will run on FreeBSD 9.3, - which is already - unsupported by FreeBSD. - Go 1.10 will require FreeBSD 10.3+. -
- -OpenBSD 6.0
- -- Go 1.9 now enables PT_TLS generation for cgo binaries and thus - requires OpenBSD 6.0 or newer. Go 1.9 no longer supports - OpenBSD 5.9. -
- -
Known Issues
- -- There are some instabilities on FreeBSD that are known but not understood. - These can lead to program crashes in rare cases. - See issue 15658. - Any help in solving this FreeBSD-specific issue would be appreciated. -
- -- Go stopped running NetBSD builders during the Go 1.9 development - cycle due to NetBSD kernel crashes, up to and including NetBSD 7.1. - As Go 1.9 is being released, NetBSD 7.1.1 is being released with a fix. - However, at this time we have no NetBSD builders passing our test suite. - Any help investigating the - various NetBSD issues - would be appreciated. -
- -Tools
- -Parallel Compilation
- -- The Go compiler now supports compiling a package's functions in parallel, taking - advantage of multiple cores. This is in addition to the
- -go
command's - existing support for parallel compilation of separate packages. - Parallel compilation is on by default, but it can be disabled by setting the - environment variableGO19CONCURRENTCOMPILATION
to0
. -Vendor matching with ./...
- -- By popular request,
- -./...
no longer matches packages - invendor
directories in tools accepting package names, - such asgo
test
. To match vendor - directories, write./vendor/...
. -Moved GOROOT
- -- The go tool will now use the path from which it - was invoked to attempt to locate the root of the Go install tree. - This means that if the entire Go installation is moved to a new - location, the go tool should continue to work as usual. - This may be overridden by setting
- -GOROOT
in the environment, - which should only be done in unusual circumstances. - Note that this does not affect the result of - the runtime.GOROOT function, which - will continue to report the original installation location; - this may be fixed in later releases. -Compiler Toolchain
- -- Complex division is now C99-compatible. This has always been the - case in gccgo and is now fixed in the gc toolchain. -
- -- The linker will now generate DWARF information for cgo executables on Windows. -
- -- The compiler now includes lexical scopes in the generated DWARF if the -
- --N -l
flags are provided, allowing - debuggers to hide variables that are not in scope. The.debug_info
- section is now DWARF version 4. -- The values of
- -GOARM
andGO386
now affect a - compiled package's build ID, as used by thego
tool's - dependency caching. -Assembler
- -- The four-operand ARM
- -MULA
instruction is now assembled correctly, - with the addend register as the third argument and the result - register as the fourth and final argument. - In previous releases, the two meanings were reversed. - The three-operand form, in which the fourth argument is implicitly - the same as the third, is unaffected. - Code using four-operandMULA
instructions - will need to be updated, but we believe this form is very rarely used. -MULAWT
andMULAWB
were already - using the correct order in all forms and are unchanged. -- The assembler now supports
- -ADDSUBPS/PD
, completing the - two missing x86 SSE3 instructions. -Doc
- -- Long lists of arguments are now truncated. This improves the readability - of
- -go
doc
on some generated code. -- Viewing documentation on struct fields is now supported. - For example,
- -go
doc
http.Client.Jar
. -Env
- -- The new
- -go
env
-json
flag - enables JSON output, instead of the default OS-specific output - format. -Test
- -- The
- - -go
test
- command accepts a new-list
flag, which takes a regular - expression as an argument and prints to stdout the name of any - tests, benchmarks, or examples that match it, without running them. -Pprof
- -- Profiles produced by the
- -runtime/pprof
package now - include symbol information, so they can be viewed - ingo
tool
pprof
- without the binary that produced the profile. -- The
- -go
tool
pprof
command now - uses the HTTP proxy information defined in the environment, using -http.ProxyFromEnvironment
. -Vet
- - -- The
- -vet
command - has been better integrated into the -go
tool, - sogo
vet
now supports all standard build - flags whilevet
's own flags are now available - fromgo
vet
as well as - fromgo
tool
vet
. -Gccgo
- --Due to the alignment of Go's semiannual release schedule with GCC's -annual release schedule, -GCC release 7 contains the Go 1.8.3 version of gccgo. -We expect that the next release, GCC 8, will contain the Go 1.10 -version of gccgo. -
- -Runtime
- -Call stacks with inlined frames
- -- Users of -
- -runtime.Callers
- should avoid directly inspecting the resulting PC slice and instead use -runtime.CallersFrames
- to get a complete view of the call stack, or -runtime.Caller
- to get information about a single caller. - This is because an individual element of the PC slice cannot account - for inlined frames or other nuances of the call stack. -- Specifically, code that directly iterates over the PC slice and uses - functions such as -
- -runtime.FuncForPC
- to resolve each PC individually will miss inlined frames. - To get a complete view of the stack, such code should instead use -CallersFrames
. - Likewise, code should not assume that the length returned by -Callers
is any indication of the call depth. - It should instead count the number of frames returned by -CallersFrames
. -- Code that queries a single caller at a specific depth should use -
- -Caller
rather than passing a slice of length 1 to -Callers
. --
- -runtime.CallersFrames
- has been available since Go 1.7, so code can be updated prior to - upgrading to Go 1.9. -Performance
- -- As always, the changes are so general and varied that precise - statements about performance are difficult to make. Most programs - should run a bit faster, due to speedups in the garbage collector, - better generated code, and optimizations in the core library. -
- -Garbage Collector
- -- Library functions that used to trigger stop-the-world garbage - collection now trigger concurrent garbage collection. - - Specifically,
- -runtime.GC
, -debug.SetGCPercent
, - and -debug.FreeOSMemory
, - now trigger concurrent garbage collection, blocking only the calling - goroutine until the garbage collection is done. -- The -
- -debug.SetGCPercent
- function only triggers a garbage collection if one is immediately - necessary because of the new GOGC value. - This makes it possible to adjust GOGC on-the-fly. -- Large object allocation performance is significantly improved in - applications using large (>50GB) heaps containing many large - objects. -
- -- The
- -runtime.ReadMemStats
- function now takes less than 100µs even for very large heaps. -Core library
- -Transparent Monotonic Time support
- -- The
- -time
package now transparently - tracks monotonic time in eachTime
- value, making computing durations between twoTime
values - a safe operation in the presence of wall clock adjustments. - See the package docs and - design document - for details. -New bit manipulation package
- -- Go 1.9 includes a new package, -
- -math/bits
, with optimized - implementations for manipulating bits. On most architectures, - functions in this package are additionally recognized by the - compiler and treated as intrinsics for additional performance. -Test Helper Functions
- -- The - new
- -(*T).Helper
- and(*B).Helper
- methods mark the calling function as a test helper function. When - printing file and line information, that function will be skipped. - This permits writing test helper functions while still having useful - line numbers for users. -Concurrent Map
- -- The new
- -Map
type - in thesync
package - is a concurrent map with amortized-constant-time loads, stores, and - deletes. It is safe for multiple goroutines to call aMap
's methods - concurrently. -Profiler Labels
- -- The
- - - - -runtime/pprof
package - now supports adding labels topprof
profiler records. - Labels form a key-value map that is used to distinguish calls of the - same function in different contexts when looking at profiles - with thepprof
command. - Thepprof
package's - newDo
function - runs code associated with some provided labels. Other new functions - in the package help work with labels. -Minor changes to the library
- -- As always, there are various minor changes and updates to the library, - made with the Go 1 promise of compatibility - in mind. -
- -- -
- archive/zip
-- -
- The - ZIP
- -Writer
- now sets the UTF-8 bit in - theFileHeader.Flags
- when appropriate. -- -
- crypto/rand
-- -
- On Linux, Go now calls the
- -getrandom
system call - without theGRND_NONBLOCK
flag; it will now block - until the kernel has sufficient randomness. On kernels predating - thegetrandom
system call, Go continues to read - from/dev/urandom
. -- -
- crypto/x509
-- -
- - On Unix systems the environment - variables
- -SSL_CERT_FILE
- andSSL_CERT_DIR
can now be used to override the - system default locations for the SSL certificate file and SSL - certificate files directory, respectively. -The FreeBSD file
- -/usr/local/etc/ssl/cert.pem
is - now included in the certificate search path. -- - The package now supports excluded domains in name constraints. - In addition to enforcing such constraints, -
- -CreateCertificate
- will create certificates with excluded name constraints - if the provided template certificate has the new - field -ExcludedDNSDomains
- populated. -- - If any SAN extension, including with no DNS names, is present - in the certificate, then the Common Name from -
- -Subject
is ignored. - In previous releases, the code tested only whether DNS-name SANs were - present in a certificate. -- -
- database/sql
-- -
- The package will now use a cached
- -Stmt
if - available inTx.Stmt
. - This prevents statements from being re-prepared each time -Tx.Stmt
is called. -- The package now allows drivers to implement their own argument checkers by implementing -
- -driver.NamedValueChecker
. - This also allows drivers to supportOUTPUT
andINOUT
parameter types. -Out
should be used to return output parameters - when supported by the driver. --
- -Rows.Scan
can now scan user-defined string types. - Previously the package supported scanning into numeric types liketype
Int
int64
. It now also supports - scanning into string types liketype
String
string
. -- The new
- -DB.Conn
method returns the new -Conn
type representing an - exclusive connection to the database from the connection pool. All queries run on - aConn
will use the same underlying - connection untilConn.Close
is called - to return the connection to the connection pool. -- -
- encoding/asn1
-- -
- The new -
- -NullBytes
- and -NullRawValue
- represent the ASN.1 NULL type. -- -
- encoding/base32
-- -
- The new Encoding.WithPadding - method adds support for custom padding characters and disabling padding. -
- -- -
- encoding/csv
-- -
- The new field -
- -Reader.ReuseRecord
- controls whether calls to -Read
- may return a slice sharing the backing array of the previous - call's returned slice for improved performance. -- -
- fmt
-- -
- The sharp flag ('
- -#
') is now supported when printing - floating point and complex numbers. It will always print a - decimal point - for%e
,%E
,%f
,%F
,%g
- and%G
; it will not remove trailing zeros - for%g
and%G
. -- -
- hash/fnv
-- -
- The package now includes 128-bit FNV-1 and FNV-1a hash support with -
- -New128
and -New128a
, respectively. -- -
- html/template
-- -
- The package now reports an error if a predefined escaper (one of - "html", "urlquery" and "js") is found in a pipeline and does not match - what the auto-escaper would have decided on its own. - This avoids certain security or correctness issues. - Now use of one of these escapers is always either a no-op or an error. - (The no-op case eases migration from text/template.) -
- -- -
- image
-- -
- The
- -Rectangle.Intersect
- method now returns a zeroRectangle
when called on - adjacent but non-overlapping rectangles, as documented. In - earlier releases it would incorrectly return an empty but - non-zeroRectangle
. -- -
- image/color
-- -
- The YCbCr to RGBA conversion formula has been tweaked to ensure - that rounding adjustments span the complete [0, 0xffff] RGBA - range. -
- -- -
- image/png
-- -
- The new
- -Encoder.BufferPool
- field allows specifying anEncoderBufferPool
, - that will be used by the encoder to get temporaryEncoderBuffer
- buffers when encoding a PNG image. - - The use of aBufferPool
reduces the number of - memory allocations performed while encoding multiple images. -- The package now supports the decoding of transparent 8-bit - grayscale ("Gray8") images. -
- -- -
- math/big
-- -
- The new -
- -IsInt64
- and -IsUint64
- methods report whether anInt
- may be represented as anint64
oruint64
- value. -- -
- mime/multipart
-- -
- The new -
- -FileHeader.Size
- field describes the size of a file in a multipart message. -- -
- net
-- -
- The new -
- -Resolver.StrictErrors
- provides control over how Go's built-in DNS resolver handles - temporary errors during queries composed of multiple sub-queries, - such as an A+AAAA address lookup. -- The new -
- -Resolver.Dial
- allows aResolver
to use a custom dial function. --
- -JoinHostPort
now only places an address in square brackets if the host contains a colon. - In previous releases it would also wrap addresses in square brackets if they contained a percent ('%
') sign. -- The new methods -
- -TCPConn.SyscallConn
, -IPConn.SyscallConn
, -UDPConn.SyscallConn
, - and -UnixConn.SyscallConn
- provide access to the connections' underlying file descriptors. -- It is now safe to call
- -Dial
with the address obtained from -(*TCPListener).String()
after creating the listener with -Listen("tcp", ":0")
. - Previously it failed on some machines with half-configured IPv6 stacks. -- -
- net/http
-- - -
- The
- -Cookie.String
method, used for -Cookie
andSet-Cookie
headers, now encloses values in double quotes - if the value contains either a space or a comma. -Server changes:
--
- -- -
- -ServeMux
now ignores ports in the host - header when matching handlers. The host is matched unmodified forCONNECT
requests. -- - The new
- -Server.ServeTLS
method wraps -Server.Serve
with added TLS support. -- -
- -Server.WriteTimeout
- now applies to HTTP/2 connections and is enforced per-stream. -- - HTTP/2 now uses the priority write scheduler by default. - Frames are scheduled by following HTTP/2 priorities as described in - RFC 7540 Section 5.3. -
- -- - The HTTP handler returned by
- -StripPrefix
- now calls its provided handler with a modified clone of the original*http.Request
. - Any code storing per-request state in maps keyed by*http.Request
should - use -Request.Context
, -Request.WithContext
, - and -context.WithValue
instead. -- -
-LocalAddrContextKey
now contains - the connection's actual network address instead of the interface address used by the listener. -Client & Transport changes:
--
- -- - The
-Transport
- now supports making requests via SOCKS5 proxy when the URL returned by -Transport.Proxy
- has the schemesocks5
. -- -
- net/http/fcgi
-- -
- The new -
- -ProcessEnv
- function returns FastCGI environment variables associated with an HTTP request - for which there are no appropriate -http.Request
- fields, such asREMOTE_USER
. -- -
- net/http/httptest
-- -
- The new -
- -Server.Client
- method returns an HTTP client configured for making requests to the test server. -- The new -
- -Server.Certificate
- method returns the test server's TLS certificate, if any. -- -
- net/http/httputil
-- -
- The
- -ReverseProxy
- now proxies all HTTP/2 response trailers, even those not declared in the initial response - header. Such undeclared trailers are used by the gRPC protocol. -- -
- os
-- -
- The
- -os
package now uses the internal runtime poller - for file I/O. - This reduces the number of threads required for read/write - operations on pipes, and it eliminates races when one goroutine - closes a file while another is using the file for I/O. -- -
- On Windows, -
- -Args
- is now populated withoutshell32.dll
, improving process start-up time by 1-7 ms. -- -
- os/exec
-- -
- The
- -os/exec
package now prevents child processes from being created with - any duplicate environment variables. - IfCmd.Env
- contains duplicate environment keys, only the last - value in the slice for each duplicate key is used. -- -
- os/user
-- -
-
- -Lookup
and -LookupId
now - work on Unix systems whenCGO_ENABLED=0
by reading - the/etc/passwd
file. --
- -LookupGroup
and -LookupGroupId
now - work on Unix systems whenCGO_ENABLED=0
by reading - the/etc/group
file. -- -
- reflect
-- -
- The new -
- -MakeMapWithSize
- function creates a map with a capacity hint. -- -
- runtime
-- -
- Tracebacks generated by the runtime and recorded in profiles are - now accurate in the presence of inlining. - To retrieve tracebacks programmatically, applications should use -
- -runtime.CallersFrames
- rather than directly iterating over the results of -runtime.Callers
. -- On Windows, Go no longer forces the system timer to run at high - resolution when the program is idle. - This should reduce the impact of Go programs on battery life. -
- -- On FreeBSD,
- -GOMAXPROCS
and -runtime.NumCPU
- are now based on the process' CPU mask, rather than the total - number of CPUs. -- The runtime has preliminary support for Android O. -
- -- -
- runtime/debug
-- -
- Calling -
- -SetGCPercent
- with a negative value no longer runs an immediate garbage collection. -- -
- runtime/trace
-- -
- The execution trace now displays mark assist events, which - indicate when an application goroutine is forced to assist - garbage collection because it is allocating too quickly. -
- -- "Sweep" events now encompass the entire process of finding free - space for an allocation, rather than recording each individual - span that is swept. - This reduces allocation latency when tracing allocation-heavy - programs. - The sweep event shows how many bytes were swept and how many - were reclaimed. -
- -- -
- sync
-- -
-
- -Mutex
is now more fair. -- - -
- syscall
-- -
- The new field -
- -Credential.NoSetGroups
- controls whether Unix systems make asetgroups
system call - to set supplementary groups when starting a new process. -- The new field -
- -SysProcAttr.AmbientCaps
- allows setting ambient capabilities on Linux 4.3+ when creating - a new process. -- On 64-bit x86 Linux, process creation latency has been optimized with - use of
- -CLONE_VFORK
andCLONE_VM
. -- The new -
- -Conn
- interface describes some types in the -net
- package that can provide access to their underlying file descriptor - using the new -RawConn
- interface. -- -
- testing/quick
-- -
- The package now chooses values in the full range when - generating
- -int64
anduint64
random - numbers; in earlier releases generated values were always - limited to the [-262, 262) range. -- In previous releases, using a nil -
- -Config.Rand
- value caused a fixed deterministic random number generator to be used. - It now uses a random number generator seeded with the current time. - For the old behavior, setConfig.Rand
torand.New(rand.NewSource(0))
. -- -
- text/template
-- -
- The handling of empty blocks, which was broken by a Go 1.8 - change that made the result dependent on the order of templates, - has been fixed, restoring the old Go 1.7 behavior. -
- -diff --git a/content/doc/go1.html b/content/doc/go1.html deleted file mode 100644 index 34e305b9..00000000 --- a/content/doc/go1.html +++ /dev/null @@ -1,2038 +0,0 @@ - - -
- time
-- -
- The new methods -
- -Duration.Round
- and -Duration.Truncate
- handle rounding and truncating durations to multiples of a given duration. -- Retrieving the time and sleeping now work correctly under Wine. -
- -- If a
- -Time
value has a monotonic clock reading, its - string representation (as returned byString
) now includes a - final field"m=±value"
, wherevalue
is the - monotonic clock reading formatted as a decimal number of seconds. -- The included
- -tzdata
timezone database has been - updated to version 2017b. As always, it is only used if the - system does not already have the database available. -Introduction to Go 1
- --Go version 1, Go 1 for short, defines a language and a set of core libraries -that provide a stable foundation for creating reliable products, projects, and -publications. -
- --The driving motivation for Go 1 is stability for its users. People should be able to -write Go programs and expect that they will continue to compile and run without -change, on a time scale of years, including in production environments such as -Google App Engine. Similarly, people should be able to write books about Go, be -able to say which version of Go the book is describing, and have that version -number still be meaningful much later. -
- --Code that compiles in Go 1 should, with few exceptions, continue to compile and -run throughout the lifetime of that version, even as we issue updates and bug -fixes such as Go version 1.1, 1.2, and so on. Other than critical fixes, changes -made to the language and library for subsequent releases of Go 1 may -add functionality but will not break existing Go 1 programs. -The Go 1 compatibility document -explains the compatibility guidelines in more detail. -
- --Go 1 is a representation of Go as it used today, not a wholesale rethinking of -the language. We avoided designing new features and instead focused on cleaning -up problems and inconsistencies and improving portability. There are a number -changes to the Go language and packages that we had considered for some time and -prototyped but not released primarily because they are significant and -backwards-incompatible. Go 1 was an opportunity to get them out, which is -helpful for the long term, but also means that Go 1 introduces incompatibilities -for old programs. Fortunately, the
- -go
fix
tool can -automate much of the work needed to bring programs up to the Go 1 standard. --This document outlines the major changes in Go 1 that will affect programmers -updating existing code; its reference point is the prior release, r60 (tagged as -r60.3). It also explains how to update code from r60 to run under Go 1. -
- -Changes to the language
- -Append
- --The
- -{{code "/doc/progs/go1.go" `/greeting := ..byte/` `/append.*hello/`}} - -append
predeclared variadic function makes it easy to grow a slice -by adding elements to the end. -A common use is to add bytes to the end of a byte slice when generating output. -However,append
did not provide a way to append a string to a[]byte
, -which is another common case. --By analogy with the similar property of
- -{{code "/doc/progs/go1.go" `/append.*world/`}} - -copy
, Go 1 -permits a string to be appended (byte-wise) directly to a byte -slice, reducing the friction between strings and byte slices. -The conversion is no longer necessary: --Updating: -This is a new feature, so existing code needs no changes. -
- -Close
- --The
- -close
predeclared function provides a mechanism -for a sender to signal that no more values will be sent. -It is important to the implementation offor
range
-loops over channels and is helpful in other situations. -Partly by design and partly because of race conditions that can occur otherwise, -it is intended for use only by the goroutine sending on the channel, -not by the goroutine receiving data. -However, before Go 1 there was no compile-time checking thatclose
-was being used correctly. --To close this gap, at least in part, Go 1 disallows
- -close
on receive-only channels. -Attempting to close such a channel is a compile-time error. -- var c chan int - var csend chan<- int = c - var crecv <-chan int = c - close(c) // legal - close(csend) // legal - close(crecv) // illegal -- --Updating: -Existing code that attempts to close a receive-only channel was -erroneous even before Go 1 and should be fixed. The compiler will -now reject such code. -
- -Composite literals
- --In Go 1, a composite literal of array, slice, or map type can elide the -type specification for the elements' initializers if they are of pointer type. -All four of the initializations in this example are legal; the last one was illegal before Go 1. -
- -{{code "/doc/progs/go1.go" `/type Date struct/` `/STOP/`}} - --Updating: -This change has no effect on existing code, but the command -
- - -gofmt
-s
applied to existing source -will, among other things, elide explicit element types wherever permitted. -Goroutines during init
- --The old language defined that
- -go
statements executed during initialization created goroutines but that they did not begin to run until initialization of the entire program was complete. -This introduced clumsiness in many places and, in effect, limited the utility -of theinit
construct: -if it was possible for another package to use the library during initialization, the library -was forced to avoid goroutines. -This design was done for reasons of simplicity and safety but, -as our confidence in the language grew, it seemed unnecessary. -Running goroutines during initialization is no more complex or unsafe than running them during normal execution. --In Go 1, code that uses goroutines can be called from -
- -{{code "/doc/progs/go1.go" `/PackageGlobal/` `/^}/`}} - -init
routines and global initialization expressions -without introducing a deadlock. --Updating: -This is a new feature, so existing code needs no changes, -although it's possible that code that depends on goroutines not starting before
- -main
will break. -There was no such code in the standard repository. -The rune type
- --The language spec allows the
- -int
type to be 32 or 64 bits wide, but current implementations setint
to 32 bits even on 64-bit platforms. -It would be preferable to haveint
be 64 bits on 64-bit platforms. -(There are important consequences for indexing large slices.) -However, this change would waste space when processing Unicode characters with -the old language because theint
type was also used to hold Unicode code points: each code point would waste an extra 32 bits of storage ifint
grew from 32 bits to 64. --To make changing to 64-bit
- -int
feasible, -Go 1 introduces a new basic type,rune
, to represent -individual Unicode code points. -It is an alias forint32
, analogous tobyte
-as an alias foruint8
. --Character literals such as
- -'a'
,'語'
, and'\u0345'
-now have default typerune
, -analogous to1.0
having default typefloat64
. -A variable initialized to a character constant will therefore -have typerune
unless otherwise specified. --Libraries have been updated to use
- -{{code "/doc/progs/go1.go" `/STARTRUNE/` `/ENDRUNE/`}} - -rune
rather thanint
-when appropriate. For instance, the functionsunicode.ToLower
and -relatives now take and return arune
. --Updating: -Most source code will be unaffected by this because the type inference from -
- -:=
initializers introduces the new type silently, and it propagates -from there. -Some code may get type errors that a trivial conversion will resolve. -The error type
- --Go 1 introduces a new built-in type,
- -error
, which has the following definition: -- type error interface { - Error() string - } -- --Since the consequences of this type are all in the package library, -it is discussed below. -
- -Deleting from maps
- --In the old language, to delete the entry with key
- -k
from mapm
, one wrote the statement, -- m[k] = value, false -- --This syntax was a peculiar special case, the only two-to-one assignment. -It required passing a value (usually ignored) that is evaluated but discarded, -plus a boolean that was nearly always the constant
- -false
. -It did the job but was odd and a point of contention. --In Go 1, that syntax has gone; instead there is a new built-in -function,
- -{{code "/doc/progs/go1.go" `/delete\(m, k\)/`}} - -delete
. The call --will delete the map entry retrieved by the expression
- -m[k]
. -There is no return value. Deleting a non-existent entry is a no-op. --Updating: -Running
- -go
fix
will convert expressions of the formm[k] = value, -false
intodelete(m, k)
when it is clear that -the ignored value can be safely discarded from the program and -false
refers to the predefined boolean constant. -The fix tool -will flag other uses of the syntax for inspection by the programmer. -Iterating in maps
- --The old language specification did not define the order of iteration for maps, -and in practice it differed across hardware platforms. -This caused tests that iterated over maps to be fragile and non-portable, with the -unpleasant property that a test might always pass on one machine but break on another. -
- --In Go 1, the order in which elements are visited when iterating -over a map using a
- -for
range
statement -is defined to be unpredictable, even if the same loop is run multiple -times with the same map. -Code should not assume that the elements are visited in any particular order. --This change means that code that depends on iteration order is very likely to break early and be fixed long before it becomes a problem. -Just as important, it allows the map implementation to ensure better map balancing even when programs are using range loops to select an element from a map. -
- -{{code "/doc/progs/go1.go" `/Sunday/` `/^ }/`}} - --Updating: -This is one change where tools cannot help. Most existing code -will be unaffected, but some programs may break or misbehave; we -recommend manual checking of all range statements over maps to -verify they do not depend on iteration order. There were a few such -examples in the standard repository; they have been fixed. -Note that it was already incorrect to depend on the iteration order, which -was unspecified. This change codifies the unpredictability. -
- -Multiple assignment
- --The language specification has long guaranteed that in assignments -the right-hand-side expressions are all evaluated before any left-hand-side expressions are assigned. -To guarantee predictable behavior, -Go 1 refines the specification further. -
- --If the left-hand side of the assignment -statement contains expressions that require evaluation, such as -function calls or array indexing operations, these will all be done -using the usual left-to-right rule before any variables are assigned -their value. Once everything is evaluated, the actual assignments -proceed in left-to-right order. -
- --These examples illustrate the behavior. -
- -{{code "/doc/progs/go1.go" `/sa :=/` `/then sc.0. = 2/`}} - --Updating: -This is one change where tools cannot help, but breakage is unlikely. -No code in the standard repository was broken by this change, and code -that depended on the previous unspecified behavior was already incorrect. -
- -Returns and shadowed variables
- --A common mistake is to use
- -return
(without arguments) after an assignment to a variable that has the same name as a result variable but is not the same variable. -This situation is called shadowing: the result variable has been shadowed by another variable with the same name declared in an inner scope. --In functions with named return values, -the Go 1 compilers disallow return statements without arguments if any of the named return values is shadowed at the point of the return statement. -(It isn't part of the specification, because this is one area we are still exploring; -the situation is analogous to the compilers rejecting functions that do not end with an explicit return statement.) -
- --This function implicitly returns a shadowed return value and will be rejected by the compiler: -
- -- func Bug() (i, j, k int) { - for i = 0; i < 5; i++ { - for j := 0; j < 5; j++ { // Redeclares j. - k += i*j - if k > 100 { - return // Rejected: j is shadowed here. - } - } - } - return // OK: j is not shadowed here. - } -- --Updating: -Code that shadows return values in this way will be rejected by the compiler and will need to be fixed by hand. -The few cases that arose in the standard repository were mostly bugs. -
- -Copying structs with unexported fields
- --The old language did not allow a package to make a copy of a struct value containing unexported fields belonging to a different package. -There was, however, a required exception for a method receiver; -also, the implementations of
- -copy
andappend
have never honored the restriction. --Go 1 will allow packages to copy struct values containing unexported fields from other packages. -Besides resolving the inconsistency, -this change admits a new kind of API: a package can return an opaque value without resorting to a pointer or interface. -The new implementations of
- -time.Time
and -reflect.Value
are examples of types taking advantage of this new property. --As an example, if package
- -p
includes the definitions, -- type Struct struct { - Public int - secret int - } - func NewStruct(a int) Struct { // Note: not a pointer. - return Struct{a, f(a)} - } - func (s Struct) String() string { - return fmt.Sprintf("{%d (secret %d)}", s.Public, s.secret) - } -- --a package that imports
- -p
can assign and copy values of type -p.Struct
at will. -Behind the scenes the unexported fields will be assigned and copied just -as if they were exported, -but the client code will never be aware of them. The code -- import "p" - - myStruct := p.NewStruct(23) - copyOfMyStruct := myStruct - fmt.Println(myStruct, copyOfMyStruct) -- --will show that the secret field of the struct has been copied to the new value. -
- --Updating: -This is a new feature, so existing code needs no changes. -
- -Equality
- --Before Go 1, the language did not define equality on struct and array values. -This meant, -among other things, that structs and arrays could not be used as map keys. -On the other hand, Go did define equality on function and map values. -Function equality was problematic in the presence of closures -(when are two closures equal?) -while map equality compared pointers, not the maps' content, which was usually -not what the user would want. -
- --Go 1 addressed these issues. -First, structs and arrays can be compared for equality and inequality -(
- -{{code "/doc/progs/go1.go" `/type Day struct/` `/Printf/`}} - -==
and!=
), -and therefore be used as map keys, -provided they are composed from elements for which equality is also defined, -using element-wise comparison. --Second, Go 1 removes the definition of equality for function values, -except for comparison with
- -nil
. -Finally, map equality is gone too, also except for comparison withnil
. --Note that equality is still undefined for slices, for which the -calculation is in general infeasible. Also note that the ordered -comparison operators (
<
<=
->
>=
) are still undefined for -structs and arrays. - --Updating: -Struct and array equality is a new feature, so existing code needs no changes. -Existing code that depends on function or map equality will be -rejected by the compiler and will need to be fixed by hand. -Few programs will be affected, but the fix may require some -redesign. -
- -The package hierarchy
- --Go 1 addresses many deficiencies in the old standard library and -cleans up a number of packages, making them more internally consistent -and portable. -
- --This section describes how the packages have been rearranged in Go 1. -Some have moved, some have been renamed, some have been deleted. -New packages are described in later sections. -
- -The package hierarchy
- --Go 1 has a rearranged package hierarchy that groups related items -into subdirectories. For instance,
- -utf8
and -utf16
now occupy subdirectories ofunicode
. -Also, some packages have moved into -subrepositories of -code.google.com/p/go
-while others have been deleted outright. --
- -- - - -Old path -New path -- -- - asn1 encoding/asn1 - csv encoding/csv - gob encoding/gob - json encoding/json - xml encoding/xml - -- - exp/template/html html/template - -- - big math/big - cmath math/cmplx - rand math/rand - -- - http net/http - http/cgi net/http/cgi - http/fcgi net/http/fcgi - http/httptest net/http/httptest - http/pprof net/http/pprof - net/mail - rpc net/rpc - rpc/jsonrpc net/rpc/jsonrpc - smtp net/smtp - url net/url - -- - exec os/exec - -- - scanner text/scanner - tabwriter text/tabwriter - template text/template - template/parse text/template/parse - -- - utf8 unicode/utf8 - utf16 unicode/utf16 -Note that the package names for the old
- -cmath
and -exp/template/html
packages have changed tocmplx
-andtemplate
. --Updating: -Running
- -go
fix
will update all imports and package renames for packages that -remain inside the standard repository. Programs that import packages -that are no longer in the standard repository will need to be edited -by hand. -The package tree exp
- --Because they are not standardized, the packages under the
- -exp
directory will not be available in the -standard Go 1 release distributions, although they will be available in source code form -in the repository for -developers who wish to use them. --Several packages have moved under
- -exp
at the time of Go 1's release: --
- -- -
ebnf
- -
html
†- -
go/types
-(†The
- -EscapeString
andUnescapeString
types remain -in packagehtml
.) --All these packages are available under the same names, with the prefix
- -exp/
:exp/ebnf
etc. --Also, the
- -utf8.String
type has been moved to its own package,exp/utf8string
. --Finally, the
- -gotype
command now resides inexp/gotype
, while -ebnflint
is now inexp/ebnflint
. -If they are installed, they now reside in$GOROOT/bin/tool
. --Updating: -Code that uses packages in
- -exp
will need to be updated by hand, -or else compiled from an installation that hasexp
available. -Thego
fix
tool or the compiler will complain about such uses. -The package tree old
- --Because they are deprecated, the packages under the
- -old
directory will not be available in the -standard Go 1 release distributions, although they will be available in source code form for -developers who wish to use them. --The packages in their new locations are: -
- --
- -- -
old/netchan
-Updating: -Code that uses packages now in
- -old
will need to be updated by hand, -or else compiled from an installation that hasold
available. -Thego
fix
tool will warn about such uses. -Deleted packages
- --Go 1 deletes several packages outright: -
- --
- -- -
container/vector
- -
exp/datafmt
- -
go/typechecker
- -
old/regexp
- -
old/template
- -
try
-and also the command
- -gotry
. --Updating: -Code that uses
- -container/vector
should be updated to use -slices directly. See -the Go -Language Community Wiki for some suggestions. -Code that uses the other packages (there should be almost zero) will need to be rethought. -Packages moving to subrepositories
- --Go 1 has moved a number of packages into other repositories, usually sub-repositories of -the main Go repository. -This table lists the old and new import paths: - -
-
- -- - - -Old -New -- -- - crypto/bcrypt code.google.com/p/go.crypto/bcrypt - crypto/blowfish code.google.com/p/go.crypto/blowfish - crypto/cast5 code.google.com/p/go.crypto/cast5 - crypto/md4 code.google.com/p/go.crypto/md4 - crypto/ocsp code.google.com/p/go.crypto/ocsp - crypto/openpgp code.google.com/p/go.crypto/openpgp - crypto/openpgp/armor code.google.com/p/go.crypto/openpgp/armor - crypto/openpgp/elgamal code.google.com/p/go.crypto/openpgp/elgamal - crypto/openpgp/errors code.google.com/p/go.crypto/openpgp/errors - crypto/openpgp/packet code.google.com/p/go.crypto/openpgp/packet - crypto/openpgp/s2k code.google.com/p/go.crypto/openpgp/s2k - crypto/ripemd160 code.google.com/p/go.crypto/ripemd160 - crypto/twofish code.google.com/p/go.crypto/twofish - crypto/xtea code.google.com/p/go.crypto/xtea - exp/ssh code.google.com/p/go.crypto/ssh - -- - image/bmp code.google.com/p/go.image/bmp - image/tiff code.google.com/p/go.image/tiff - -- - net/dict code.google.com/p/go.net/dict - net/websocket code.google.com/p/go.net/websocket - exp/spdy code.google.com/p/go.net/spdy - -- - encoding/git85 code.google.com/p/go.codereview/git85 - patch code.google.com/p/go.codereview/patch - -- - exp/wingui code.google.com/p/gowingui -Updating: -Running
- -go
fix
will update imports of these packages to use the new import paths. -Installations that depend on these packages will need to install them using -ago get
command. -Major changes to the library
- --This section describes significant changes to the core libraries, the ones that -affect the most programs. -
- -The error type and errors package
- --The placement of
- -os.Error
in packageos
is mostly historical: errors first came up when implementing packageos
, and they seemed system-related at the time. -Since then it has become clear that errors are more fundamental than the operating system. For example, it would be nice to useErrors
in packages thatos
depends on, likesyscall
. -Also, havingError
inos
introduces many dependencies onos
that would otherwise not exist. --Go 1 solves these problems by introducing a built-in
- -error
interface type and a separateerrors
package (analogous tobytes
andstrings
) that contains utility functions. -It replacesos.NewError
with -errors.New
, -giving errors a more central place in the environment. --So the widely-used
- -String
method does not cause accidental satisfaction -of theerror
interface, theerror
interface uses instead -the nameError
for that method: -- type error interface { - Error() string - } -- --The
- -{{code "/doc/progs/go1.go" `/START ERROR EXAMPLE/` `/END ERROR EXAMPLE/`}} - -fmt
library automatically invokesError
, as it already -does forString
, for easy printing of error values. --All standard packages have been updated to use the new interface; the old
- -os.Error
is gone. --A new package,
- -errors
, contains the function --func New(text string) error -- --to turn a string into an error. It replaces the old
- -{{code "/doc/progs/go1.go" `/ErrSyntax/`}} - -os.NewError
. --Updating: -Running
- -go
fix
will update almost all code affected by the change. -Code that defines error types with aString
method will need to be updated -by hand to rename the methods toError
. -System call errors
- --The old
- -syscall
package, which predatedos.Error
-(and just about everything else), -returned errors asint
values. -In turn, theos
package forwarded many of these errors, such -asEINVAL
, but using a different set of errors on each platform. -This behavior was unpleasant and unportable. --In Go 1, the -
- -syscall
-package instead returns anerror
for system call errors. -On Unix, the implementation is done by a -syscall.Errno
type -that satisfieserror
and replaces the oldos.Errno
. --The changes affecting
os.EINVAL
and relatives are -described elsewhere. - --Updating: -Running
- -go
fix
will update almost all code affected by the change. -Regardless, most code should use theos
package -rather thansyscall
and so will be unaffected. -Time
- --Time is always a challenge to support well in a programming language. -The old Go
- -time
package hadint64
units, no -real type safety, -and no distinction between absolute times and durations. --One of the most sweeping changes in the Go 1 library is therefore a -complete redesign of the -
- -time
package. -Instead of an integer number of nanoseconds as anint64
, -and a separate*time.Time
type to deal with human -units such as hours and years, -there are now two fundamental types: -time.Time
-(a value, so the*
is gone), which represents a moment in time; -andtime.Duration
, -which represents an interval. -Both have nanosecond resolution. -ATime
can represent any time into the ancient -past and remote future, while aDuration
can -span plus or minus only about 290 years. -There are methods on these types, plus a number of helpful -predefined constant durations such astime.Second
. --Among the new methods are things like -
- -Time.Add
, -which adds aDuration
to aTime
, and -Time.Sub
, -which subtracts twoTimes
to yield aDuration
. --The most important semantic change is that the Unix epoch (Jan 1, 1970) is now -relevant only for those functions and methods that mention Unix: -
- -{{code "/doc/progs/go1.go" `/sleepUntil/` `/^}/`}} - -time.Unix
-and theUnix
-andUnixNano
methods -of theTime
type. -In particular, -time.Now
-returns atime.Time
value rather than, in the old -API, an integer nanosecond count since the Unix epoch. --The new types, methods, and constants have been propagated through -all the standard packages that use time, such as
- -os
and -its representation of file time stamps. --Updating: -The
- -go
fix
tool will update many uses of the oldtime
package to use the new -types and methods, although it does not replace values such as1e9
-representing nanoseconds per second. -Also, because of type changes in some of the values that arise, -some of the expressions rewritten by the fix tool may require -further hand editing; in such cases the rewrite will include -the correct function or method for the old functionality, but -may have the wrong type or require further analysis. -Minor changes to the library
- --This section describes smaller changes, such as those to less commonly -used packages or that affect -few programs beyond the need to run
- -go
fix
. -This category includes packages that are new in Go 1. -Collectively they improve portability, regularize behavior, and -make the interfaces more modern and Go-like. -The archive/zip package
- --In Go 1,
- -*zip.Writer
no -longer has aWrite
method. Its presence was a mistake. --Updating: -What little code is affected will be caught by the compiler and must be updated by hand. -
- -The bufio package
- --In Go 1,
- -bufio.NewReaderSize
-and -bufio.NewWriterSize
-functions no longer return an error for invalid sizes. -If the argument size is too small or invalid, it is adjusted. --Updating: -Running
- -go
fix
will update calls that assign the error to _. -Calls that aren't fixed will be caught by the compiler and must be updated by hand. -The compress/flate, compress/gzip and compress/zlib packages
- --In Go 1, the
- -NewWriterXxx
functions in -compress/flate
, -compress/gzip
and -compress/zlib
-all return(*Writer, error)
if they take a compression level, -and*Writer
otherwise. Packagegzip
's -Compressor
andDecompressor
types have been renamed -toWriter
andReader
. Packageflate
's -WrongValueError
type has been removed. --Updating -Running
- -go
fix
will update old names and calls that assign the error to _. -Calls that aren't fixed will be caught by the compiler and must be updated by hand. -The crypto/aes and crypto/des packages
- --In Go 1, the
- -Reset
method has been removed. Go does not guarantee -that memory is not copied and therefore this method was misleading. --The cipher-specific types
- -*aes.Cipher
,*des.Cipher
, -and*des.TripleDESCipher
have been removed in favor of -cipher.Block
. --Updating: -Remove the calls to Reset. Replace uses of the specific cipher types with -cipher.Block. -
- -The crypto/elliptic package
- --In Go 1,
- -elliptic.Curve
-has been made an interface to permit alternative implementations. The curve -parameters have been moved to the -elliptic.CurveParams
-structure. --Updating: -Existing users of
- -*elliptic.Curve
will need to change to -simplyelliptic.Curve
. Calls toMarshal
, -Unmarshal
andGenerateKey
are now functions -incrypto/elliptic
that take anelliptic.Curve
-as their first argument. -The crypto/hmac package
- --In Go 1, the hash-specific functions, such as
- -hmac.NewMD5
, have -been removed fromcrypto/hmac
. Instead,hmac.New
takes -a function that returns ahash.Hash
, such asmd5.New
. --Updating: -Running
- -go
fix
will perform the needed changes. -The crypto/x509 package
- --In Go 1, the -
- -CreateCertificate
-function and -CreateCRL
-method incrypto/x509
have been altered to take an -interface{}
where they previously took a*rsa.PublicKey
-or*rsa.PrivateKey
. This will allow other public key algorithms -to be implemented in the future. --Updating: -No changes will be needed. -
- -The encoding/binary package
- --In Go 1, the
- -binary.TotalSize
function has been replaced by -Size
, -which takes aninterface{}
argument rather than -areflect.Value
. --Updating: -What little code is affected will be caught by the compiler and must be updated by hand. -
- -The encoding/xml package
- --In Go 1, the
- -xml
package -has been brought closer in design to the other marshaling packages such -asencoding/gob
. --The old
- -Parser
type is renamed -Decoder
and has a new -Decode
method. An -Encoder
type was also introduced. --The functions
- -Marshal
-andUnmarshal
-work with[]byte
values now. To work with streams, -use the newEncoder
-andDecoder
types. --When marshaling or unmarshaling values, the format of supported flags in -field tags has changed to be closer to the -
- -json
package -(`xml:"name,flag"`
). The matching done between field tags, field -names, and the XML attribute and element names is now case-sensitive. -TheXMLName
field tag, if present, must also match the name -of the XML element being marshaled. --Updating: -Running
- -go
fix
will update most uses of the package except for some calls to -Unmarshal
. Special care must be taken with field tags, -since the fix tool will not update them and if not fixed by hand they will -misbehave silently in some cases. For example, the old -"attr"
is now written",attr"
while plain -"attr"
remains valid but with a different meaning. -The expvar package
- --In Go 1, the
- -RemoveAll
function has been removed. -TheIter
function and Iter method on*Map
have -been replaced by -Do
-and -(*Map).Do
. --Updating: -Most code using
- -expvar
will not need changing. The rare code that used -Iter
can be updated to pass a closure toDo
to achieve the same effect. -The flag package
- --In Go 1, the interface
- -flag.Value
has changed slightly. -TheSet
method now returns anerror
instead of -abool
to indicate success or failure. --There is also a new kind of flag,
- -{{code "/doc/progs/go1.go" `/timeout/`}} - -Duration
, to support argument -values specifying time intervals. -Values for such flags must be given units, just astime.Duration
-formats them:10s
,1h30m
, etc. --Updating: -Programs that implement their own flags will need minor manual fixes to update their -
- - -Set
methods. -TheDuration
flag is new and affects no existing code. -The go/* packages
- --Several packages under
- -go
have slightly revised APIs. --A concrete
- -Mode
type was introduced for configuration mode flags -in the packages -go/scanner
, -go/parser
, -go/printer
, and -go/doc
. --The modes
- -AllowIllegalChars
andInsertSemis
have been removed -from thego/scanner
package. They were mostly -useful for scanning text other then Go source files. Instead, the -text/scanner
package should be used -for that purpose. --The
- -ErrorHandler
provided -to the scanner'sInit
method is -now simply a function rather than an interface. TheErrorVector
type has -been removed in favor of the (existing)ErrorList
-type, and theErrorVector
methods have been migrated. Instead of embedding -anErrorVector
in a client of the scanner, now a client should maintain -anErrorList
. --The set of parse functions provided by the
- -go/parser
-package has been reduced to the primary parse function -ParseFile
, and a couple of -convenience functionsParseDir
-andParseExpr
. --The
- -go/printer
package supports an additional -configuration modeSourcePos
; -if set, the printer will emit//line
comments such that the generated -output contains the original source code position information. The new type -CommentedNode
can be -used to provide comments associated with an arbitrary -ast.Node
(until now only -ast.File
carried comment information). --The type names of the
- -go/doc
package have been -streamlined by removing theDoc
suffix:PackageDoc
-is nowPackage
,ValueDoc
isValue
, etc. -Also, all types now consistently have aName
field (orNames
, -in the case of typeValue
) andType.Factories
has become -Type.Funcs
. -Instead of callingdoc.NewPackageDoc(pkg, importpath)
, -documentation for a package is created with: -- doc.New(pkg, importpath, mode) -- --where the new
- -mode
parameter specifies the operation mode: -if set toAllDecls
, all declarations -(not just exported ones) are considered. -The functionNewFileDoc
was removed, and the function -CommentText
has become the method -Text
of -ast.CommentGroup
. --In package
- -go/token
, the -token.FileSet
methodFiles
-(which originally returned a channel of*token.File
s) has been replaced -with the iteratorIterate
that -accepts a function argument instead. --In package
- -go/build
, the API -has been nearly completely replaced. -The package still computes Go package information -but it does not run the build: theCmd
andScript
-types are gone. -(To build code, use the new -go
command instead.) -TheDirInfo
type is now named -Package
. -FindTree
andScanDir
are replaced by -Import
-and -ImportDir
. --Updating: -Code that uses packages in
- -go
will have to be updated by hand; the -compiler will reject incorrect uses. Templates used in conjunction with any of the -go/doc
types may need manual fixes; the renamed fields will lead -to run-time errors. -The hash package
- --In Go 1, the definition of
- -hash.Hash
includes -a new method,BlockSize
. This new method is used primarily in the -cryptographic libraries. --The
- -Sum
method of the -hash.Hash
interface now takes a -[]byte
argument, to which the hash value will be appended. -The previous behavior can be recreated by adding anil
argument to the call. --Updating: -Existing implementations of
- -hash.Hash
will need to add a -BlockSize
method. Hashes that process the input one byte at -a time can implementBlockSize
to return 1. -Runninggo
fix
will update calls to theSum
methods of the various -implementations ofhash.Hash
. --Updating: -Since the package's functionality is new, no updating is necessary. -
- -The http package
- --In Go 1 the
- -http
package is refactored, -putting some of the utilities into a -httputil
subdirectory. -These pieces are only rarely needed by HTTP clients. -The affected items are: --
- -- ClientConn
-- DumpRequest
-- DumpRequestOut
-- DumpResponse
-- NewChunkedReader
-- NewChunkedWriter
-- NewClientConn
-- NewProxyClientConn
-- NewServerConn
-- NewSingleHostReverseProxy
-- ReverseProxy
-- ServerConn
--The
- -Request.RawURL
field has been removed; it was a -historical artifact. --The
- -Handle
andHandleFunc
-functions, and the similarly-named methods ofServeMux
, -now panic if an attempt is made to register the same pattern twice. --Updating: -Running
- -go
fix
will update the few programs that are affected except for -uses ofRawURL
, which must be fixed by hand. -The image package
- --The
- -image
package has had a number of -minor changes, rearrangements and renamings. --Most of the color handling code has been moved into its own package, -
- -image/color
. -For the elements that moved, a symmetry arises; for instance, -each pixel of an -image.RGBA
-is a -color.RGBA
. --The old
- -image/ycbcr
package has been folded, with some -renamings, into the -image
-and -image/color
-packages. --The old
- -image.ColorImage
type is still in theimage
-package but has been renamed -image.Uniform
, -whileimage.Tiled
has been removed. --This table lists the renamings. -
- --
- -- - - -Old -New -- -- - image.Color color.Color - image.ColorModel color.Model - image.ColorModelFunc color.ModelFunc - image.PalettedColorModel color.Palette - -- - image.RGBAColor color.RGBA - image.RGBA64Color color.RGBA64 - image.NRGBAColor color.NRGBA - image.NRGBA64Color color.NRGBA64 - image.AlphaColor color.Alpha - image.Alpha16Color color.Alpha16 - image.GrayColor color.Gray - image.Gray16Color color.Gray16 - -- - image.RGBAColorModel color.RGBAModel - image.RGBA64ColorModel color.RGBA64Model - image.NRGBAColorModel color.NRGBAModel - image.NRGBA64ColorModel color.NRGBA64Model - image.AlphaColorModel color.AlphaModel - image.Alpha16ColorModel color.Alpha16Model - image.GrayColorModel color.GrayModel - image.Gray16ColorModel color.Gray16Model - -- - ycbcr.RGBToYCbCr color.RGBToYCbCr - ycbcr.YCbCrToRGB color.YCbCrToRGB - ycbcr.YCbCrColorModel color.YCbCrModel - ycbcr.YCbCrColor color.YCbCr - ycbcr.YCbCr image.YCbCr - -- - ycbcr.SubsampleRatio444 image.YCbCrSubsampleRatio444 - ycbcr.SubsampleRatio422 image.YCbCrSubsampleRatio422 - ycbcr.SubsampleRatio420 image.YCbCrSubsampleRatio420 - -- - image.ColorImage image.Uniform -The image package's
- -New
functions -(NewRGBA
, -NewRGBA64
, etc.) -take animage.Rectangle
as an argument -instead of four integers. --Finally, there are new predefined
- -color.Color
variables -color.Black
, -color.White
, -color.Opaque
-and -color.Transparent
. --Updating: -Running
- -go
fix
will update almost all code affected by the change. -The log/syslog package
- --In Go 1, the
- -syslog.NewLogger
-function returns an error as well as alog.Logger
. --Updating: -What little code is affected will be caught by the compiler and must be updated by hand. -
- -The mime package
- --In Go 1, the
- -FormatMediaType
function -of themime
package has been simplified to make it -consistent with -ParseMediaType
. -It now takes"text/html"
rather than"text"
and"html"
. --Updating: -What little code is affected will be caught by the compiler and must be updated by hand. -
- -The net package
- --In Go 1, the various
- -SetTimeout
, -SetReadTimeout
, andSetWriteTimeout
methods -have been replaced with -SetDeadline
, -SetReadDeadline
, and -SetWriteDeadline
, -respectively. Rather than taking a timeout value in nanoseconds that -apply to any activity on the connection, the new methods set an -absolute deadline (as atime.Time
value) after which -reads and writes will time out and no longer block. --There are also new functions -
- -net.DialTimeout
-to simplify timing out dialing a network address and -net.ListenMulticastUDP
-to allow multicast UDP to listen concurrently across multiple listeners. -Thenet.ListenMulticastUDP
function replaces the old -JoinGroup
andLeaveGroup
methods. --Updating: -Code that uses the old methods will fail to compile and must be updated by hand. -The semantic change makes it difficult for the fix tool to update automatically. -
- -The os package
- --The
- -Time
function has been removed; callers should use -theTime
type from the -time
package. --The
- -Exec
function has been removed; callers should use -Exec
from thesyscall
package, where available. --The
- -ShellExpand
function has been renamed toExpandEnv
. --The
- -NewFile
function -now takes auintptr
fd, instead of anint
. -TheFd
method on files now -also returns auintptr
. --There are no longer error constants such as
- -EINVAL
-in theos
package, since the set of values varied with -the underlying operating system. There are new portable functions like -IsPermission
-to test common error properties, plus a few new error values -with more Go-like names, such as -ErrPermission
-and -ErrNotExist
. --The
- - -Getenverror
function has been removed. To distinguish -between a non-existent environment variable and an empty string, -useos.Environ
or -syscall.Getenv
. --The
- -Process.Wait
method has -dropped its option argument and the associated constants are gone -from the package. -Also, the functionWait
is gone; only the method of -theProcess
type persists. --The
- -Waitmsg
type returned by -Process.Wait
-has been replaced with a more portable -ProcessState
-type with accessor methods to recover information about the -process. -Because of changes toWait
, theProcessState
-value always describes an exited process. -Portability concerns simplified the interface in other ways, but the values returned by the -ProcessState.Sys
and -ProcessState.SysUsage
-methods can be type-asserted to underlying system-specific data structures such as -syscall.WaitStatus
and -syscall.Rusage
on Unix. --Updating: -Running
- -go
fix
will drop a zero argument toProcess.Wait
. -All other changes will be caught by the compiler and must be updated by hand. -The os.FileInfo type
- --Go 1 redefines the
- -os.FileInfo
type, -changing it from a struct to an interface: -- type FileInfo interface { - Name() string // base name of the file - Size() int64 // length in bytes - Mode() FileMode // file mode bits - ModTime() time.Time // modification time - IsDir() bool // abbreviation for Mode().IsDir() - Sys() interface{} // underlying data source (can return nil) - } -- --The file mode information has been moved into a subtype called -
- -os.FileMode
, -a simple integer type withIsDir
,Perm
, andString
-methods. --The system-specific details of file modes and properties such as (on Unix) -i-number have been removed from
- -FileInfo
altogether. -Instead, each operating system'sos
package provides an -implementation of theFileInfo
interface, which -has aSys
method that returns the -system-specific representation of file metadata. -For instance, to discover the i-number of a file on a Unix system, unpack -theFileInfo
like this: -- fi, err := os.Stat("hello.go") - if err != nil { - log.Fatal(err) - } - // Check that it's a Unix file. - unixStat, ok := fi.Sys().(*syscall.Stat_t) - if !ok { - log.Fatal("hello.go: not a Unix file") - } - fmt.Printf("file i-number: %d\n", unixStat.Ino) -- --Assuming (which is unwise) that
- -"hello.go"
is a Unix file, -the i-number expression could be contracted to -- fi.Sys().(*syscall.Stat_t).Ino -- --The vast majority of uses of
- -FileInfo
need only the methods -of the standard interface. --The
- -{{code "/doc/progs/go1.go" `/os\.Open/` `/}/`}} - -os
package no longer contains wrappers for the POSIX errors -such asENOENT
. -For the few programs that need to verify particular error conditions, there are -now the boolean functions -IsExist
, -IsNotExist
-and -IsPermission
. --Updating: -Running
- -go
fix
will update code that uses the old equivalent of the currentos.FileInfo
-andos.FileMode
API. -Code that needs system-specific file details will need to be updated by hand. -Code that uses the old POSIX error values from theos
package -will fail to compile and will also need to be updated by hand. -The os/signal package
- --The
- -os/signal
package in Go 1 replaces the -Incoming
function, which returned a channel -that received all incoming signals, -with the selectiveNotify
function, which asks -for delivery of specific signals on an existing channel. --Updating: -Code must be updated by hand. -A literal translation of -
--c := signal.Incoming() ---is -
--c := make(chan os.Signal) -signal.Notify(c) // ask for all signals ---but most code should list the specific signals it wants to handle instead: -
--c := make(chan os.Signal) -signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT) -- -The path/filepath package
- --In Go 1, the
- -Walk
function of the -path/filepath
package -has been changed to take a function value of type -WalkFunc
-instead of aVisitor
interface value. -WalkFunc
unifies the handling of both files and directories. -- type WalkFunc func(path string, info os.FileInfo, err error) error -- --The
- -{{code "/doc/progs/go1.go" `/STARTWALK/` `/ENDWALK/`}} - -WalkFunc
function will be called even for files or directories that could not be opened; -in such cases the error argument will describe the failure. -If a directory's contents are to be skipped, -the function should return the valuefilepath.SkipDir
--Updating: -The change simplifies most code but has subtle consequences, so affected programs -will need to be updated by hand. -The compiler will catch code using the old interface. -
- -The regexp package
- --The
- -regexp
package has been rewritten. -It has the same interface but the specification of the regular expressions -it supports has changed from the old "egrep" form to that of -RE2. --Updating: -Code that uses the package should have its regular expressions checked by hand. -
- -The runtime package
- --In Go 1, much of the API exported by package -
- -runtime
has been removed in favor of -functionality provided by other packages. -Code using theruntime.Type
interface -or its specific concrete type implementations should -now use packagereflect
. -Code usingruntime.Semacquire
orruntime.Semrelease
-should use channels or the abstractions in packagesync
. -Theruntime.Alloc
,runtime.Free
, -andruntime.Lookup
functions, an unsafe API created for -debugging the memory allocator, have no replacement. --Before,
- -runtime.MemStats
was a global variable holding -statistics about memory allocation, and calls toruntime.UpdateMemStats
-ensured that it was up to date. -In Go 1,runtime.MemStats
is a struct type, and code should use -runtime.ReadMemStats
-to obtain the current statistics. --The package adds a new function, -
- -runtime.NumCPU
, that returns the number of CPUs available -for parallel execution, as reported by the operating system kernel. -Its value can inform the setting ofGOMAXPROCS
. -Theruntime.Cgocalls
andruntime.Goroutines
functions -have been renamed toruntime.NumCgoCall
andruntime.NumGoroutine
. --Updating: -Running
- -go
fix
will update code for the function renamings. -Other code will need to be updated by hand. -The strconv package
- --In Go 1, the -
- -strconv
-package has been significantly reworked to make it more Go-like and less C-like, -althoughAtoi
lives on (it's similar to -int(ParseInt(x, 10, 0))
, as does -Itoa(x)
(FormatInt(int64(x), 10)
). -There are also new variants of some of the functions that append to byte slices rather than -return strings, to allow control over allocation. --This table summarizes the renamings; see the -package documentation -for full details. -
- --
- -- - - -Old call -New call -- -- - Atob(x) ParseBool(x) - -- - Atof32(x) ParseFloat(x, 32)§ - Atof64(x) ParseFloat(x, 64) - AtofN(x, n) ParseFloat(x, n) - -- - Atoi(x) Atoi(x) - Atoi(x) ParseInt(x, 10, 0)§ - Atoi64(x) ParseInt(x, 10, 64) - -- - Atoui(x) ParseUint(x, 10, 0)§ - Atoui64(x) ParseUint(x, 10, 64) - -- - Btoi64(x, b) ParseInt(x, b, 64) - Btoui64(x, b) ParseUint(x, b, 64) - -- - Btoa(x) FormatBool(x) - -- - Ftoa32(x, f, p) FormatFloat(float64(x), f, p, 32) - Ftoa64(x, f, p) FormatFloat(x, f, p, 64) - FtoaN(x, f, p, n) FormatFloat(x, f, p, n) - -- - Itoa(x) Itoa(x) - Itoa(x) FormatInt(int64(x), 10) - Itoa64(x) FormatInt(x, 10) - -- - Itob(x, b) FormatInt(int64(x), b) - Itob64(x, b) FormatInt(x, b) - -- - Uitoa(x) FormatUint(uint64(x), 10) - Uitoa64(x) FormatUint(x, 10) - -- - Uitob(x, b) FormatUint(uint64(x), b) - Uitob64(x, b) FormatUint(x, b) -Updating: -Running
- - -go
fix
will update almost all code affected by the change. -
-§Atoi
persists butAtoui
andAtof32
do not, so -they may require -a cast that must be added by hand; thego
fix
tool will warn about it. -The template packages
- --The
- -template
andexp/template/html
packages have moved to -text/template
and -html/template
. -More significant, the interface to these packages has been simplified. -The template language is the same, but the concept of "template set" is gone -and the functions and methods of the packages have changed accordingly, -often by elimination. --Instead of sets, a
- -Template
object -may contain multiple named template definitions, -in effect constructing -name spaces for template invocation. -A template can invoke any other template associated with it, but only those -templates associated with it. -The simplest way to associate templates is to parse them together, something -made easier with the new structure of the packages. --Updating: -The imports will be updated by fix tool. -Single-template uses will be otherwise be largely unaffected. -Code that uses multiple templates in concert will need to be updated by hand. -The examples in -the documentation for
- -text/template
can provide guidance. -The testing package
- --The testing package has a type,
- -{{code "/doc/progs/go1.go" `/func.*Benchmark/` `/^}/`}} - -B
, passed as an argument to benchmark functions. -In Go 1,B
has new methods, analogous to those ofT
, enabling -logging and failure reporting. --Updating: -Existing code is unaffected, although benchmarks that use
- -println
-orpanic
should be updated to use the new methods. -The testing/script package
- --The testing/script package has been deleted. It was a dreg. -
- --Updating: -No code is likely to be affected. -
- -The unsafe package
- --In Go 1, the functions -
- -unsafe.Typeof
,unsafe.Reflect
, -unsafe.Unreflect
,unsafe.New
, and -unsafe.NewArray
have been removed; -they duplicated safer functionality provided by -packagereflect
. --Updating: -Code using these functions must be rewritten to use -package
- -reflect
. -The changes to encoding/gob and the protocol buffer library -may be helpful as examples. -The url package
- --In Go 1 several fields from the
- -url.URL
type -were removed or replaced. --The
- -String
method now -predictably rebuilds an encoded URL string using all ofURL
's -fields as necessary. The resulting string will also no longer have -passwords escaped. --The
- -Raw
field has been removed. In most cases theString
-method may be used in its place. --The old
- -RawUserinfo
field is replaced by theUser
-field, of type*net.Userinfo
. -Values of this type may be created using the newnet.User
-andnet.UserPassword
-functions. TheEscapeUserinfo
andUnescapeUserinfo
-functions are also gone. --The
- -RawAuthority
field has been removed. The same information is -available in theHost
andUser
fields. --The
- -RawPath
field and theEncodedPath
method have -been removed. The path information in rooted URLs (with a slash following the -schema) is now available only in decoded form in thePath
field. -Occasionally, the encoded data may be required to obtain information that -was lost in the decoding process. These cases must be handled by accessing -the data the URL was built from. --URLs with non-rooted paths, such as
- -"mailto:dev@golang.org?subject=Hi"
, -are also handled differently. TheOpaquePath
boolean field has been -removed and a newOpaque
string field introduced to hold the encoded -path for such URLs. In Go 1, the cited URL parses as: -- URL{ - Scheme: "mailto", - Opaque: "dev@golang.org", - RawQuery: "subject=Hi", - } -- --A new
- -RequestURI
method was -added toURL
. --The
- -ParseWithReference
function has been renamed toParseWithFragment
. --Updating: -Code that uses the old fields will fail to compile and must be updated by hand. -The semantic changes make it difficult for the fix tool to update automatically. -
- -The go command
- --Go 1 introduces the go command, a tool for fetching, -building, and installing Go packages and commands. The
- -go
command -does away with makefiles, instead using Go source code to find dependencies and -determine build conditions. Most existing Go programs will no longer require -makefiles to be built. --See How to Write Go Code for a primer on the -
- -go
command and the go command documentation -for the full details. --Updating: -Projects that depend on the Go project's old makefile-based build -infrastructure (
- -Make.pkg
,Make.cmd
, and so on) should -switch to using thego
command for building Go code and, if -necessary, rewrite their makefiles to perform any auxiliary build tasks. -The cgo command
- --In Go 1, the cgo command -uses a different
- -_cgo_export.h
-file, which is generated for packages containing//export
lines. -The_cgo_export.h
file now begins with the C preamble comment, -so that exported function definitions can use types defined there. -This has the effect of compiling the preamble multiple times, so a -package using//export
must not put function definitions -or variable initializations in the C preamble. -Packaged releases
- --One of the most significant changes associated with Go 1 is the availability -of prepackaged, downloadable distributions. -They are available for many combinations of architecture and operating system -(including Windows) and the list will grow. -Installation details are described on the -Getting Started page, while -the distributions themselves are listed on the -downloads page. diff --git a/content/doc/go1compat.html b/content/doc/go1compat.html deleted file mode 100644 index a5624ef5..00000000 --- a/content/doc/go1compat.html +++ /dev/null @@ -1,202 +0,0 @@ - - -
Introduction
--The release of Go version 1, Go 1 for short, is a major milestone -in the development of the language. Go 1 is a stable platform for -the growth of programs and projects written in Go. -
- --Go 1 defines two things: first, the specification of the language; -and second, the specification of a set of core APIs, the "standard -packages" of the Go library. The Go 1 release includes their -implementation in the form of two compiler suites (gc and gccgo), -and the core libraries themselves. -
- --It is intended that programs written to the Go 1 specification will -continue to compile and run correctly, unchanged, over the lifetime -of that specification. At some indefinite point, a Go 2 specification -may arise, but until that time, Go programs that work today should -continue to work even as future "point" releases of Go 1 arise (Go -1.1, Go 1.2, etc.). -
- --Compatibility is at the source level. Binary compatibility for -compiled packages is not guaranteed between releases. After a point -release, Go source will need to be recompiled to link against the -new release. -
- --The APIs may grow, acquiring new packages and features, but not in -a way that breaks existing Go 1 code. -
- -Expectations
- --Although we expect that the vast majority of programs will maintain -this compatibility over time, it is impossible to guarantee that -no future change will break any program. This document is an attempt -to set expectations for the compatibility of Go 1 software in the -future. There are a number of ways in which a program that compiles -and runs today may fail to do so after a future point release. They -are all unlikely but worth recording. -
- --
- -- -Security. A security issue in the specification or implementation -may come to light whose resolution requires breaking compatibility. -We reserve the right to address such security issues. -
- -- -Unspecified behavior. The Go specification tries to be explicit -about most properties of the language, but there are some aspects -that are undefined. Programs that depend on such unspecified behavior -may break in future releases. -
- -- -Specification errors. If it becomes necessary to address an -inconsistency or incompleteness in the specification, resolving the -issue could affect the meaning or legality of existing programs. -We reserve the right to address such issues, including updating the -implementations. Except for security issues, no incompatible changes -to the specification would be made. -
- -- -Bugs. If a compiler or library has a bug that violates the -specification, a program that depends on the buggy behavior may -break if the bug is fixed. We reserve the right to fix such bugs. -
- -- -Struct literals. For the addition of features in later point -releases, it may be necessary to add fields to exported structs in -the API. Code that uses unkeyed struct literals (such as pkg.T{3, -"x"}) to create values of these types would fail to compile after -such a change. However, code that uses keyed literals (pkg.T{A: -3, B: "x"}) will continue to compile after such a change. We will -update such data structures in a way that allows keyed struct -literals to remain compatible, although unkeyed literals may fail -to compile. (There are also more intricate cases involving nested -data structures or interfaces, but they have the same resolution.) -We therefore recommend that composite literals whose type is defined -in a separate package should use the keyed notation. -
- -- -Methods. As with struct fields, it may be necessary to add methods -to types. -Under some circumstances, such as when the type is embedded in -a struct along with another type, -the addition of the new method may break -the struct by creating a conflict with an existing method of the other -embedded type. -We cannot protect against this rare case and do not guarantee compatibility -should it arise. -
- -- -Dot imports. If a program imports a standard package -using
- -import . "path"
, additional names defined in the -imported package in future releases may conflict with other names -defined in the program. We do not recommend the use ofimport .
-outside of tests, and using it may cause a program to fail -to compile in future releases. -- -Use of package
- -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. --Of course, for all of these possibilities, should they arise, we -would endeavor whenever feasible to update the specification, -compilers, or libraries without affecting existing code. -
- --These same considerations apply to successive point releases. For -instance, code that runs under Go 1.2 should be compatible with Go -1.2.1, Go 1.3, Go 1.4, etc., although not necessarily with Go 1.1 -since it may use features added only in Go 1.2 -
- --Features added between releases, available in the source repository -but not part of the numbered binary releases, are under active -development. No promise of compatibility is made for software using -such features until they have been released. -
- --Finally, although it is not a correctness issue, it is possible -that the performance of a program may be affected by -changes in the implementation of the compilers or libraries upon -which it depends. -No guarantee can be made about the performance of a -given program between releases. -
- --Although these expectations apply to Go 1 itself, we hope similar -considerations would be made for the development of externally -developed software based on Go 1. -
- -Sub-repositories
- --Code in sub-repositories of the main go tree, such as -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. -
- -Operating systems
- --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, thesyscall
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. -Tools
- --Finally, the Go toolchain (compilers, linkers, build tools, and so -on) is under active development and may change behavior. This -means, for instance, that scripts that depend on the location and -properties of the tools may be broken by a point release. -
- --These caveats aside, we believe that Go 1 will be a firm foundation -for the development of Go and its ecosystem. -
diff --git a/content/doc/go_faq.html b/content/doc/go_faq.html deleted file mode 100644 index 305878f2..00000000 --- a/content/doc/go_faq.html +++ /dev/null @@ -1,2475 +0,0 @@ - - -Origins
- --What is the purpose of the project?
- --At the time of Go's inception, only a decade ago, the programming world was different from today. -Production software was usually written in C++ or Java, -GitHub did not exist, most computers were not yet multiprocessors, -and other than Visual Studio and Eclipse there were few IDEs or other high-level tools available -at all, let alone for free on the Internet. -
- --Meanwhile, we had become frustrated by the undue complexity required to use -the languages we worked with to develop server software. -Computers had become enormously quicker since languages such as -C, C++ and Java were first developed but the act of programming had not -itself advanced nearly as much. -Also, it was clear that multiprocessors were becoming universal but -most languages offered little help to program them efficiently -and safely. -
- --We decided to take a step back and think about what major issues were -going to dominate software engineering in the years ahead as technology -developed, and how a new language might help address them. -For instance, the rise of multicore CPUs argued that a language should -provide first-class support for some sort of concurrency or parallelism. -And to make resource management tractable in a large concurrent program, -garbage collection, or at least some sort of safe automatic memory management was required. -
- --These considerations led to -a -series of discussions from which Go arose, first as a set of ideas and -desiderata, then as a language. -An overarching goal was that Go do more to help the working programmer -by enabling tooling, automating mundane tasks such as code formatting, -and removing obstacles to working on large code bases. -
- --A much more expansive description of the goals of Go and how -they are met, or at least approached, is available in the article, -Go at Google: -Language Design in the Service of Software Engineering. -
- --What is the history of the project?
--Robert Griesemer, Rob Pike and Ken Thompson started sketching the -goals for a new language on the white board on September 21, 2007. -Within a few days the goals had settled into a plan to do something -and a fair idea of what it would be. Design continued part-time in -parallel with unrelated work. By January 2008, Ken had started work -on a compiler with which to explore ideas; it generated C code as its -output. By mid-year the language had become a full-time project and -had settled enough to attempt a production compiler. In May 2008, -Ian Taylor independently started on a GCC front end for Go using the -draft specification. Russ Cox joined in late 2008 and helped move the language -and libraries from prototype to reality. -
- --Go became a public open source project on November 10, 2009. -Countless people from the community have contributed ideas, discussions, and code. -
- --There are now millions of Go programmers—gophers—around the world, -and there are more every day. -Go's success has far exceeded our expectations. -
- --What's the origin of the gopher mascot?
- --The mascot and logo were designed by -Renée French, who also designed -Glenda, -the Plan 9 bunny. -A blog post -about the gopher explains how it was -derived from one she used for a WFMU -T-shirt design some years ago. -The logo and mascot are covered by the -Creative Commons Attribution 3.0 -license. -
- --The gopher has a -model sheet -illustrating his characteristics and how to represent them correctly. -The model sheet was first shown in a -talk -by Renée at Gophercon in 2016. -He has unique features; he's the Go gopher, not just any old gopher. -
- --Is the language called Go or Golang?
- --The language is called Go. -The "golang" moniker arose because the web site is -golang.org, not -go.org, which was not available to us. -Many use the golang name, though, and it is handy as -a label. -For instance, the Twitter tag for the language is "#golang". -The language's name is just plain Go, regardless. -
- --A side note: Although the -official logo -has two capital letters, the language name is written Go, not GO. -
- --Why did you create a new language?
- --Go was born out of frustration with existing languages and -environments for the work we were doing at Google. -Programming had become too -difficult and the choice of languages was partly to blame. One had to -choose either efficient compilation, efficient execution, or ease of -programming; all three were not available in the same mainstream -language. Programmers who could were choosing ease over -safety and efficiency by moving to dynamically typed languages such as -Python and JavaScript rather than C++ or, to a lesser extent, Java. -
- --We were not alone in our concerns. -After many years with a pretty quiet landscape for programming languages, -Go was among the first of several new languages—Rust, -Elixir, Swift, and more—that have made programming language development -an active, almost mainstream field again. -
- --Go addressed these issues by attempting to combine the ease of programming of an interpreted, -dynamically typed -language with the efficiency and safety of a statically typed, compiled language. -It also aimed to be modern, with support for networked and multicore -computing. Finally, working with Go is intended to be fast: it should take -at most a few seconds to build a large executable on a single computer. -To meet these goals required addressing a number of -linguistic issues: an expressive but lightweight type system; -concurrency and garbage collection; rigid dependency specification; -and so on. These cannot be addressed well by libraries or tools; a new -language was called for. -
- --The article Go at Google -discusses the background and motivation behind the design of the Go language, -as well as providing more detail about many of the answers presented in this FAQ. -
- - --What are Go's ancestors?
--Go is mostly in the C family (basic syntax), -with significant input from the Pascal/Modula/Oberon -family (declarations, packages), -plus some ideas from languages -inspired by Tony Hoare's CSP, -such as Newsqueak and Limbo (concurrency). -However, it is a new language across the board. -In every respect the language was designed by thinking -about what programmers do and how to make programming, at least the -kind of programming we do, more effective, which means more fun. -
- --What are the guiding principles in the design?
- --When Go was designed, Java and C++ were the most commonly -used languages for writing servers, at least at Google. -We felt that these languages required -too much bookkeeping and repetition. -Some programmers reacted by moving towards more dynamic, -fluid languages like Python, at the cost of efficiency and -type safety. -We felt it should be possible to have the efficiency, -the safety, and the fluidity in a single language. -
- --Go attempts to reduce the amount of typing in both senses of the word. -Throughout its design, we have tried to reduce clutter and -complexity. There are no forward declarations and no header files; -everything is declared exactly once. Initialization is expressive, -automatic, and easy to use. Syntax is clean and light on keywords. -Stuttering (
-foo.Foo* myFoo = new(foo.Foo)
) is reduced by -simple type derivation using the:=
-declare-and-initialize construct. And perhaps most radically, there -is no type hierarchy: types just are, they don't have to -announce their relationships. These simplifications allow Go to be -expressive yet comprehensible without sacrificing, well, sophistication. --Another important principle is to keep the concepts orthogonal. -Methods can be implemented for any type; structures represent data while -interfaces represent abstraction; and so on. Orthogonality makes it -easier to understand what happens when things combine. -
- -Usage
- --Is Google using Go internally?
- --Yes. Go is used widely in production inside Google. -One easy example is the server behind -golang.org. -It's just the
- -godoc
-document server running in a production configuration on -Google App Engine. --A more significant instance is Google's download server,
- -dl.google.com
, -which delivers Chrome binaries and other large installables such asapt-get
-packages. --Go is not the only language used at Google, far from it, but it is a key language -for a number of areas including -site reliability -engineering (SRE) -and large-scale data processing. -
- --What other companies use Go?
- --Go usage is growing worldwide, especially but by no means exclusively -in the cloud computing space. -A couple of major cloud infrastructure projects written in Go are -Docker and Kubernetes, -but there are many more. -
- --It's not just cloud, though. -The Go Wiki includes a -page, -updated regularly, that lists some of the many companies using Go. -
- --The Wiki also has a page with links to -success stories -about companies and projects that are using the language. -
- --Do Go programs link with C/C++ programs?
- --It is possible to use C and Go together in the same address space, -but it is not a natural fit and can require special interface software. -Also, linking C with Go code gives up the memory -safety and stack management properties that Go provides. -Sometimes it's absolutely necessary to use C libraries to solve a problem, -but doing so always introduces an element of risk not present with -pure Go code, so do so with care. -
- --If you do need to use C with Go, how to proceed depends on the Go -compiler implementation. -There are three Go compiler implementations supported by the -Go team. -These are
- -gc
, the default compiler, -gccgo
, which uses the GCC back end, -and a somewhat less maturegollvm
, which uses the LLVM infrastructure. --
- -Gc
uses a different calling convention and linker from C and -therefore cannot be called directly from C programs, or vice versa. -Thecgo
program provides the mechanism for a -“foreign function interface” to allow safe calling of -C libraries from Go code. -SWIG extends this capability to C++ libraries. --You can also use
- -cgo
and SWIG withGccgo
andgollvm
. -Since they use a traditional API, it's also possible, with great care, -to link code from these compilers directly with GCC/LLVM-compiled C or C++ programs. -However, doing so safely requires an understanding of the calling conventions for -all languages concerned, as well as concern for stack limits when calling C or C++ -from Go. --What IDEs does Go support?
- --The Go project does not include a custom IDE, but the language and -libraries have been designed to make it easy to analyze source code. -As a consequence, most well-known editors and IDEs support Go well, -either directly or through a plugin. -
- --The list of well-known IDEs and editors that have good Go support -available includes Emacs, Vim, VSCode, Atom, Eclipse, Sublime, IntelliJ -(through a custom variant called Goland), and many more. -Chances are your favorite environment is a productive one for -programming in Go. -
- --Does Go support Google's protocol buffers?
- --A separate open source project provides the necessary compiler plugin and library. -It is available at -github.com/golang/protobuf/. -
- - --Can I translate the Go home page into another language?
- --Absolutely. We encourage developers to make Go Language sites in their own languages. -However, if you choose to add the Google logo or branding to your site -(it does not appear on golang.org), -you will need to abide by the guidelines at -www.google.com/permissions/guidelines.html -
- -Design
- --Does Go have a runtime?
- --Go does have an extensive library, called the runtime, -that is part of every Go program. -The runtime library implements garbage collection, concurrency, -stack management, and other critical features of the Go language. -Although it is more central to the language, Go's runtime is analogous -to
- -libc
, the C library. --It is important to understand, however, that Go's runtime does not -include a virtual machine, such as is provided by the Java runtime. -Go programs are compiled ahead of time to native machine code -(or JavaScript or WebAssembly, for some variant implementations). -Thus, although the term is often used to describe the virtual -environment in which a program runs, in Go the word “runtime” -is just the name given to the library providing critical language services. -
- --What's up with Unicode identifiers?
- --When designing Go, we wanted to make sure that it was not -overly ASCII-centric, -which meant extending the space of identifiers from the -confines of 7-bit ASCII. -Go's rule—identifier characters must be -letters or digits as defined by Unicode—is simple to understand -and to implement but has restrictions. -Combining characters are -excluded by design, for instance, -and that excludes some languages such as Devanagari. -
- --This rule has one other unfortunate consequence. -Since an exported identifier must begin with an -upper-case letter, identifiers created from characters -in some languages can, by definition, not be exported. -For now the -only solution is to use something like
- -X日本語
, which -is clearly unsatisfactory. --Since the earliest version of the language, there has been considerable -thought into how best to expand the identifier space to accommodate -programmers using other native languages. -Exactly what to do remains an active topic of discussion, and a future -version of the language may be more liberal in its definition -of an identifier. -For instance, it might adopt some of the ideas from the Unicode -organization's recommendations -for identifiers. -Whatever happens, it must be done compatibly while preserving -(or perhaps expanding) the way letter case determines visibility of -identifiers, which remains one of our favorite features of Go. -
- --For the time being, we have a simple rule that can be expanded later -without breaking programs, one that avoids bugs that would surely arise -from a rule that admits ambiguous identifiers. -
- -Why does Go not have feature X?
- --Every language contains novel features and omits someone's favorite -feature. Go was designed with an eye on felicity of programming, speed of -compilation, orthogonality of concepts, and the need to support features -such as concurrency and garbage collection. Your favorite feature may be -missing because it doesn't fit, because it affects compilation speed or -clarity of design, or because it would make the fundamental system model -too difficult. -
- --If it bothers you that Go is missing feature X, -please forgive us and investigate the features that Go does have. You might find that -they compensate in interesting ways for the lack of X. -
- --Why does Go not have generic types?
--Generics may well be added at some point. We don't feel an urgency for -them, although we understand some programmers do. -
- --Go was intended as a language for writing server programs that would be -easy to maintain over time. -(See this -article for more background.) -The design concentrated on things like scalability, readability, and -concurrency. -Polymorphic programming did not seem essential to the language's -goals at the time, and so was left out for simplicity. -
- --The language is more mature now, and there is scope to consider -some form of generic programming. -However, there remain some caveats. -
- --Generics are convenient but they come at a cost in -complexity in the type system and run-time. We haven't yet found a -design that gives value proportionate to the complexity, although we -continue to think about it. Meanwhile, Go's built-in maps and slices, -plus the ability to use the empty interface to construct containers -(with explicit unboxing) mean in many cases it is possible to write -code that does what generics would enable, if less smoothly. -
- --The topic remains open. -For a look at several previous unsuccessful attempts to -design a good generics solution for Go, see -this proposal. -
- --Why does Go not have exceptions?
--We believe that coupling exceptions to a control -structure, as in the
- -try-catch-finally
idiom, results in -convoluted code. It also tends to encourage programmers to label -too many ordinary errors, such as failing to open a file, as -exceptional. --Go takes a different approach. For plain error handling, Go's multi-value -returns make it easy to report an error without overloading the return value. -A canonical error type, coupled -with Go's other features, makes error handling pleasant but quite different -from that in other languages. -
- --Go also has a couple -of built-in functions to signal and recover from truly exceptional -conditions. The recovery mechanism is executed only as part of a -function's state being torn down after an error, which is sufficient -to handle catastrophe but requires no extra control structures and, -when used well, can result in clean error-handling code. -
- --See the Defer, Panic, and Recover article for details. -Also, the Errors are values blog post -describes one approach to handling errors cleanly in Go by demonstrating that, -since errors are just values, the full power of Go can deployed in error handling. -
- --Why does Go not have assertions?
- --Go doesn't provide assertions. They are undeniably convenient, but our -experience has been that programmers use them as a crutch to avoid thinking -about proper error handling and reporting. Proper error handling means that -servers continue to operate instead of crashing after a non-fatal error. -Proper error reporting means that errors are direct and to the point, -saving the programmer from interpreting a large crash trace. Precise -errors are particularly important when the programmer seeing the errors is -not familiar with the code. -
- --We understand that this is a point of contention. There are many things in -the Go language and libraries that differ from modern practices, simply -because we feel it's sometimes worth trying a different approach. -
- --Why build concurrency on the ideas of CSP?
--Concurrency and multi-threaded programming have over time -developed a reputation for difficulty. We believe this is due partly to complex -designs such as -pthreads -and partly to overemphasis on low-level details -such as mutexes, condition variables, and memory barriers. -Higher-level interfaces enable much simpler code, even if there are still -mutexes and such under the covers. -
- --One of the most successful models for providing high-level linguistic support -for concurrency comes from Hoare's Communicating Sequential Processes, or CSP. -Occam and Erlang are two well known languages that stem from CSP. -Go's concurrency primitives derive from a different part of the family tree -whose main contribution is the powerful notion of channels as first class objects. -Experience with several earlier languages has shown that the CSP model -fits well into a procedural language framework. -
- --Why goroutines instead of threads?
--Goroutines are part of making concurrency easy to use. The idea, which has -been around for a while, is to multiplex independently executing -functions—coroutines—onto a set of threads. -When a coroutine blocks, such as by calling a blocking system call, -the run-time automatically moves other coroutines on the same operating -system thread to a different, runnable thread so they won't be blocked. -The programmer sees none of this, which is the point. -The result, which we call goroutines, can be very cheap: they have little -overhead beyond the memory for the stack, which is just a few kilobytes. -
- --To make the stacks small, Go's run-time uses resizable, bounded stacks. A newly -minted goroutine is given a few kilobytes, which is almost always enough. -When it isn't, the run-time grows (and shrinks) the memory for storing -the stack automatically, allowing many goroutines to live in a modest -amount of memory. -The CPU overhead averages about three cheap instructions per function call. -It is practical to create hundreds of thousands of goroutines in the same -address space. -If goroutines were just threads, system resources would -run out at a much smaller number. -
- --Why are map operations not defined to be atomic?
- --After long discussion it was decided that the typical use of maps did not require -safe access from multiple goroutines, and in those cases where it did, the map was -probably part of some larger data structure or computation that was already -synchronized. Therefore requiring that all map operations grab a mutex would slow -down most programs and add safety to few. This was not an easy decision, -however, since it means uncontrolled map access can crash the program. -
- --The language does not preclude atomic map updates. When required, such -as when hosting an untrusted program, the implementation could interlock -map access. -
- --Map access is unsafe only when updates are occurring. -As long as all goroutines are only reading—looking up elements in the map, -including iterating through it using a -
- -for
range
loop—and not changing the map -by assigning to elements or doing deletions, -it is safe for them to access the map concurrently without synchronization. --As an aid to correct map use, some implementations of the language -contain a special check that automatically reports at run time when a map is modified -unsafely by concurrent execution. -
- --Will you accept my language change?
- --People often suggest improvements to the language—the -mailing list -contains a rich history of such discussions—but very few of these changes have -been accepted. -
- --Although Go is an open source project, the language and libraries are protected -by a compatibility promise that prevents -changes that break existing programs, at least at the source code level -(programs may need to be recompiled occasionally to stay current). -If your proposal violates the Go 1 specification we cannot even entertain the -idea, regardless of its merit. -A future major release of Go may be incompatible with Go 1, but discussions -on that topic have only just begun and one thing is certain: -there will be very few such incompatibilities introduced in the process. -Moreover, the compatibility promise encourages us to provide an automatic path -forward for old programs to adapt should that situation arise. -
- --Even if your proposal is compatible with the Go 1 spec, it might -not be in the spirit of Go's design goals. -The article Go -at Google: Language Design in the Service of Software Engineering -explains Go's origins and the motivation behind its design. -
- -Types
- --Is Go an object-oriented language?
- --Yes and no. Although Go has types and methods and allows an -object-oriented style of programming, there is no type hierarchy. -The concept of “interface” in Go provides a different approach that -we believe is easy to use and in some ways more general. There are -also ways to embed types in other types to provide something -analogous—but not identical—to subclassing. -Moreover, methods in Go are more general than in C++ or Java: -they can be defined for any sort of data, even built-in types such -as plain, “unboxed” integers. -They are not restricted to structs (classes). -
- --Also, the lack of a type hierarchy makes “objects” in Go feel much more -lightweight than in languages such as C++ or Java. -
- --How do I get dynamic dispatch of methods?
- --The only way to have dynamically dispatched methods is through an -interface. Methods on a struct or any other concrete type are always resolved statically. -
- --Why is there no type inheritance?
--Object-oriented programming, at least in the best-known languages, -involves too much discussion of the relationships between types, -relationships that often could be derived automatically. Go takes a -different approach. -
- --Rather than requiring the programmer to declare ahead of time that two -types are related, in Go a type automatically satisfies any interface -that specifies a subset of its methods. Besides reducing the -bookkeeping, this approach has real advantages. Types can satisfy -many interfaces at once, without the complexities of traditional -multiple inheritance. -Interfaces can be very lightweight—an interface with -one or even zero methods can express a useful concept. -Interfaces can be added after the fact if a new idea comes along -or for testing—without annotating the original types. -Because there are no explicit relationships between types -and interfaces, there is no type hierarchy to manage or discuss. -
- --It's possible to use these ideas to construct something analogous to -type-safe Unix pipes. For instance, see how
- -fmt.Fprintf
-enables formatted printing to any output, not just a file, or how the -bufio
package can be completely separate from file I/O, -or how theimage
packages generate compressed -image files. All these ideas stem from a single interface -(io.Writer
) representing a single method -(Write
). And that's only scratching the surface. -Go's interfaces have a profound influence on how programs are structured. --It takes some getting used to but this implicit style of type -dependency is one of the most productive things about Go. -
- --Why is
-len
a function and not a method?-We debated this issue but decided -implementing
- -len
and friends as functions was fine in practice and -didn't complicate questions about the interface (in the Go type sense) -of basic types. --Why does Go not support overloading of methods and operators?
--Method dispatch is simplified if it doesn't need to do type matching as well. -Experience with other languages told us that having a variety of -methods with the same name but different signatures was occasionally useful -but that it could also be confusing and fragile in practice. Matching only by name -and requiring consistency in the types was a major simplifying decision -in Go's type system. -
- --Regarding operator overloading, it seems more a convenience than an absolute -requirement. Again, things are simpler without it. -
- --Why doesn't Go have "implements" declarations?
- --A Go type satisfies an interface by implementing the methods of that interface, -nothing more. This property allows interfaces to be defined and used without -needing to modify existing code. It enables a kind of -structural typing that -promotes separation of concerns and improves code re-use, and makes it easier -to build on patterns that emerge as the code develops. -The semantics of interfaces is one of the main reasons for Go's nimble, -lightweight feel. -
- --See the question on type inheritance for more detail. -
- --How can I guarantee my type satisfies an interface?
- --You can ask the compiler to check that the type
- -T
implements the -interfaceI
by attempting an assignment using the zero value for -T
or pointer toT
, as appropriate: --type T struct{} -var _ I = T{} // Verify that T implements I. -var _ I = (*T)(nil) // Verify that *T implements I. -- --If
- -T
(or*T
, accordingly) doesn't implement -I
, the mistake will be caught at compile time. --If you wish the users of an interface to explicitly declare that they implement -it, you can add a method with a descriptive name to the interface's method set. -For example: -
- --type Fooer interface { - Foo() - ImplementsFooer() -} -- --A type must then implement the
- -ImplementsFooer
method to be a -Fooer
, clearly documenting the fact and announcing it in -go doc's output. --type Bar struct{} -func (b Bar) ImplementsFooer() {} -func (b Bar) Foo() {} -- --Most code doesn't make use of such constraints, since they limit the utility of -the interface idea. Sometimes, though, they're necessary to resolve ambiguities -among similar interfaces. -
- --Why doesn't type T satisfy the Equal interface?
- --Consider this simple interface to represent an object that can compare -itself with another value: -
- --type Equaler interface { - Equal(Equaler) bool -} -- --and this type,
- -T
: --type T int -func (t T) Equal(u T) bool { return t == u } // does not satisfy Equaler -- --Unlike the analogous situation in some polymorphic type systems, -
- -T
does not implementEqualer
. -The argument type ofT.Equal
isT
, -not literally the required typeEqualer
. --In Go, the type system does not promote the argument of -
- -Equal
; that is the programmer's responsibility, as -illustrated by the typeT2
, which does implement -Equaler
: --type T2 int -func (t T2) Equal(u Equaler) bool { return t == u.(T2) } // satisfies Equaler -- --Even this isn't like other type systems, though, because in Go any -type that satisfies
- -Equaler
could be passed as the -argument toT2.Equal
, and at run time we must -check that the argument is of typeT2
. -Some languages arrange to make that guarantee at compile time. --A related example goes the other way: -
- --type Opener interface { - Open() Reader -} - -func (t T3) Open() *os.File -- --In Go,
- -T3
does not satisfyOpener
, -although it might in another language. --While it is true that Go's type system does less for the programmer -in such cases, the lack of subtyping makes the rules about -interface satisfaction very easy to state: are the function's names -and signatures exactly those of the interface? -Go's rule is also easy to implement efficiently. -We feel these benefits offset the lack of -automatic type promotion. Should Go one day adopt some form of polymorphic -typing, we expect there would be a way to express the idea of these -examples and also have them be statically checked. -
- --Can I convert a []T to an []interface{}?
- --Not directly. -It is disallowed by the language specification because the two types -do not have the same representation in memory. -It is necessary to copy the elements individually to the destination -slice. This example converts a slice of
- -int
to a slice of -interface{}
: --t := []int{1, 2, 3, 4} -s := make([]interface{}, len(t)) -for i, v := range t { - s[i] = v -} -- --Can I convert []T1 to []T2 if T1 and T2 have the same underlying type?
- -This last line of this code sample does not compile. - --type T1 int -type T2 int -var t1 T1 -var x = T2(t1) // OK -var st1 []T1 -var sx = ([]T2)(st1) // NOT OK -- --In Go, types are closely tied to methods, in that every named type has -a (possibly empty) method set. -The general rule is that you can change the name of the type being -converted (and thus possibly change its method set) but you can't -change the name (and method set) of elements of a composite type. -Go requires you to be explicit about type conversions. -
- --Why is my nil error value not equal to nil? -
- --Under the covers, interfaces are implemented as two elements, a type
- -T
-and a valueV
. -V
is a concrete value such as anint
, -struct
or pointer, never an interface itself, and has -typeT
. -For instance, if we store theint
value 3 in an interface, -the resulting interface value has, schematically, -(T=int
,V=3
). -The valueV
is also known as the interface's -dynamic value, -since a given interface variable might hold different valuesV
-(and corresponding typesT
) -during the execution of the program. --An interface value is
- -nil
only if theV
andT
-are both unset, (T=nil
,V
is not set), -In particular, anil
interface will always hold anil
type. -If we store anil
pointer of type*int
inside -an interface value, the inner type will be*int
regardless of the value of the pointer: -(T=*int
,V=nil
). -Such an interface value will therefore be non-nil
-even when the pointer valueV
inside isnil
. --This situation can be confusing, and arises when a
- -nil
value is -stored inside an interface value such as anerror
return: --func returnsError() error { - var p *MyError = nil - if bad() { - p = ErrBad - } - return p // Will always return a non-nil error. -} -- --If all goes well, the function returns a
- - -nil
p
, -so the return value is anerror
interface -value holding (T=*MyError
,V=nil
). -This means that if the caller compares the returned error tonil
, -it will always look as if there was an error even if nothing bad happened. -To return a propernil
error
to the caller, -the function must return an explicitnil
: --func returnsError() error { - if bad() { - return ErrBad - } - return nil -} -- --It's a good idea for functions -that return errors always to use the
- -error
type in -their signature (as we did above) rather than a concrete type such -as*MyError
, to help guarantee the error is -created correctly. As an example, -os.Open
-returns anerror
even though, if notnil
, -it's always of concrete type -*os.PathError
. --Similar situations to those described here can arise whenever interfaces are used. -Just keep in mind that if any concrete value -has been stored in the interface, the interface will not be
- - -nil
. -For more information, see -The Laws of Reflection. --Why are there no untagged unions, as in C?
- --Untagged unions would violate Go's memory safety -guarantees. -
- --Why does Go not have variant types?
- --Variant types, also known as algebraic types, provide a way to specify -that a value might take one of a set of other types, but only those -types. A common example in systems programming would specify that an -error is, say, a network error, a security error or an application -error and allow the caller to discriminate the source of the problem -by examining the type of the error. Another example is a syntax tree -in which each node can be a different type: declaration, statement, -assignment and so on. -
- --We considered adding variant types to Go, but after discussion -decided to leave them out because they overlap in confusing ways -with interfaces. What would happen if the elements of a variant type -were themselves interfaces? -
- --Also, some of what variant types address is already covered by the -language. The error example is easy to express using an interface -value to hold the error and a type switch to discriminate cases. The -syntax tree example is also doable, although not as elegantly. -
- --Why does Go not have covariant result types?
- --Covariant result types would mean that an interface like -
- --type Copyable interface { - Copy() interface{} -} -- --would be satisfied by the method -
- --func (v Value) Copy() Value -- -because
- -Value
implements the empty interface. -In Go method types must match exactly, soValue
does not -implementCopyable
. -Go separates the notion of what a -type does—its methods—from the type's implementation. -If two methods return different types, they are not doing the same thing. -Programmers who want covariant result types are often trying to -express a type hierarchy through interfaces. -In Go it's more natural to have a clean separation between interface -and implementation. -Values
- --Why does Go not provide implicit numeric conversions?
- --The convenience of automatic conversion between numeric types in C is -outweighed by the confusion it causes. When is an expression unsigned? -How big is the value? Does it overflow? Is the result portable, independent -of the machine on which it executes? -It also complicates the compiler; “the usual arithmetic conversions” -are not easy to implement and inconsistent across architectures. -For reasons of portability, we decided to make things clear and straightforward -at the cost of some explicit conversions in the code. -The definition of constants in Go—arbitrary precision values free -of signedness and size annotations—ameliorates matters considerably, -though. -
- --A related detail is that, unlike in C,
- -int
andint64
-are distinct types even ifint
is a 64-bit type. Theint
-type is generic; if you care about how many bits an integer holds, Go -encourages you to be explicit. --How do constants work in Go?
- --Although Go is strict about conversion between variables of different -numeric types, constants in the language are much more flexible. -Literal constants such as
- -23
,3.14159
-andmath.Pi
-occupy a sort of ideal number space, with arbitrary precision and -no overflow or underflow. -For instance, the value ofmath.Pi
is specified to 63 places -in the source code, and constant expressions involving the value keep -precision beyond what afloat64
could hold. -Only when the constant or constant expression is assigned to a -variable—a memory location in the program—does -it become a "computer" number with -the usual floating-point properties and precision. --Also, -because they are just numbers, not typed values, constants in Go can be -used more freely than variables, thereby softening some of the awkwardness -around the strict conversion rules. -One can write expressions such as -
- --sqrt2 := math.Sqrt(2) -- --without complaint from the compiler because the ideal number
- -2
-can be converted safely and accurately -to afloat64
for the call tomath.Sqrt
. --A blog post titled Constants -explores this topic in more detail. -
- --Why are maps built in?
--The same reason strings are: they are such a powerful and important data -structure that providing one excellent implementation with syntactic support -makes programming more pleasant. We believe that Go's implementation of maps -is strong enough that it will serve for the vast majority of uses. -If a specific application can benefit from a custom implementation, it's possible -to write one but it will not be as convenient syntactically; this seems a reasonable tradeoff. -
- --Why don't maps allow slices as keys?
--Map lookup requires an equality operator, which slices do not implement. -They don't implement equality because equality is not well defined on such types; -there are multiple considerations involving shallow vs. deep comparison, pointer vs. -value comparison, how to deal with recursive types, and so on. -We may revisit this issue—and implementing equality for slices -will not invalidate any existing programs—but without a clear idea of what -equality of slices should mean, it was simpler to leave it out for now. -
- --In Go 1, unlike prior releases, equality is defined for structs and arrays, so such -types can be used as map keys. Slices still do not have a definition of equality, though. -
- --Why are maps, slices, and channels references while arrays are values?
--There's a lot of history on that topic. Early on, maps and channels -were syntactically pointers and it was impossible to declare or use a -non-pointer instance. Also, we struggled with how arrays should work. -Eventually we decided that the strict separation of pointers and -values made the language harder to use. Changing these -types to act as references to the associated, shared data structures resolved -these issues. This change added some regrettable complexity to the -language but had a large effect on usability: Go became a more -productive, comfortable language when it was introduced. -
- -Writing Code
- --How are libraries documented?
- --There is a program,
- -godoc
, written in Go, that extracts -package documentation from the source code and serves it as a web -page with links to declarations, files, and so on. -An instance is running at -golang.org/pkg/. -In fact,godoc
implements the full site at -golang.org/. --A
- -godoc
instance may be configured to provide rich, -interactive static analyses of symbols in the programs it displays; details are -listed here. --For access to documentation from the command line, the -go tool has a -doc -subcommand that provides a textual interface to the same information. -
- --Is there a Go programming style guide?
- --There is no explicit style guide, although there is certainly -a recognizable "Go style". -
- --Go has established conventions to guide decisions around -naming, layout, and file organization. -The document Effective Go -contains some advice on these topics. -More directly, the program
- -gofmt
is a pretty-printer -whose purpose is to enforce layout rules; it replaces the usual -compendium of do's and don'ts that allows interpretation. -All the Go code in the repository, and the vast majority in the -open source world, has been run throughgofmt
. --The document titled -Go Code Review Comments -is a collection of very short essays about details of Go idiom that are often -missed by programmers. -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 the
- -src
directory of the repository. -If you want to make a significant change, please discuss on the mailing list before embarking. --See the document -Contributing to the Go project -for more information about how to proceed. -
- --Why does "go get" use HTTPS when cloning a repository?
- --Companies often permit outgoing traffic only on the standard TCP ports 80 (HTTP) -and 443 (HTTPS), blocking outgoing traffic on other ports, including TCP port 9418 -(git) and TCP port 22 (SSH). -When using HTTPS instead of HTTP,
- -git
enforces certificate validation by -default, providing protection against man-in-the-middle, eavesdropping and tampering attacks. -Thego get
command therefore uses HTTPS for safety. --
-Git
can be configured to authenticate over HTTPS or to use SSH in place of HTTPS. -To authenticate over HTTPS, you can add a line -to the$HOME/.netrc
file that git consults: --machine github.com login USERNAME password APIKEY ---For GitHub accounts, the password can be a -personal access token. -
- --
-Git
can also be configured to use SSH in place of HTTPS for URLs matching a given prefix. -For example, to use SSH for all GitHub access, -add these lines to your~/.gitconfig
: --[url "ssh://git@github.com/"] - insteadOf = https://github.com/ -- --How should I manage package versions using "go get"?
- --Since the inception of the project, Go has had no explicit concept of package versions, -but that is changing. -Versioning is a source of significant complexity, especially in large code bases, -and it has taken some time to develop an -approach that works well at scale in a large enough -variety of situations to be appropriate to supply to all Go users. -
- --The Go 1.11 release adds new, experimental support -for package versioning to the
- -go
command, -in the form of Go modules. -For more information, see the Go 1.11 release notes -and thego
command documentation. --Regardless of the actual package management technology, -"go get" and the larger Go toolchain does provide isolation of -packages with different import paths. -For example, the standard library's
- -html/template
andtext/template
-coexist even though both are "package template". -This observation leads to some advice for package authors and package users. --Packages intended for public use should try to maintain backwards compatibility as they evolve. -The Go 1 compatibility guidelines are a good reference here: -don't remove exported names, encourage tagged composite literals, and so on. -If different functionality is required, add a new name instead of changing an old one. -If a complete break is required, create a new package with a new import path. -
- --If you're using an externally supplied package and worry that it might change in -unexpected ways, but are not yet using Go modules, -the simplest solution is to copy it to your local repository. -This is the approach Google takes internally and is supported by the -
- -go
command through a technique called "vendoring". -This involves -storing a copy of the dependency under a new import path that identifies it as a local copy. -See the design -document for details. -Pointers and Allocation
- --When are function parameters passed by value?
- --As in all languages in the C family, everything in Go is passed by value. -That is, a function always gets a copy of the -thing being passed, as if there were an assignment statement assigning the -value to the parameter. For instance, passing an
- -int
value -to a function makes a copy of theint
, and passing a pointer -value makes a copy of the pointer, but not the data it points to. -(See a later -section for a discussion of how this affects method receivers.) --Map and slice values behave like pointers: they are descriptors that -contain pointers to the underlying map or slice data. Copying a map or -slice value doesn't copy the data it points to. Copying an interface value -makes a copy of the thing stored in the interface value. If the interface -value holds a struct, copying the interface value makes a copy of the -struct. If the interface value holds a pointer, copying the interface value -makes a copy of the pointer, but again not the data it points to. -
- --Note that this discussion is about the semantics of the operations. -Actual implementations may apply optimizations to avoid copying -as long as the optimizations do not change the semantics. -
- --When should I use a pointer to an interface?
- --Almost never. Pointers to interface values arise only in rare, tricky situations involving -disguising an interface value's type for delayed evaluation. -
- --It is a common mistake to pass a pointer to an interface value -to a function expecting an interface. The compiler will complain about this -error but the situation can still be confusing, because sometimes a -pointer -is necessary to satisfy an interface. -The insight is that although a pointer to a concrete type can satisfy -an interface, with one exception a pointer to an interface can never satisfy an interface. -
- --Consider the variable declaration, -
- --var w io.Writer -- --The printing function
- -fmt.Fprintf
takes as its first argument -a value that satisfiesio.Writer
—something that implements -the canonicalWrite
method. Thus we can write --fmt.Fprintf(w, "hello, world\n") -- --If however we pass the address of
- -w
, the program will not compile. --fmt.Fprintf(&w, "hello, world\n") // Compile-time error. -- --The one exception is that any value, even a pointer to an interface, can be assigned to -a variable of empty interface type (
- -interface{}
). -Even so, it's almost certainly a mistake if the value is a pointer to an interface; -the result can be confusing. --Should I define methods on values or pointers?
- --func (s *MyStruct) pointerMethod() { } // method on pointer -func (s MyStruct) valueMethod() { } // method on value -- --For programmers unaccustomed to pointers, the distinction between these -two examples can be confusing, but the situation is actually very simple. -When defining a method on a type, the receiver (
- -s
in the above -examples) behaves exactly as if it were an argument to the method. -Whether to define the receiver as a value or as a pointer is the same -question, then, as whether a function argument should be a value or -a pointer. -There are several considerations. --First, and most important, does the method need to modify the -receiver? -If it does, the receiver must be a pointer. -(Slices and maps act as references, so their story is a little -more subtle, but for instance to change the length of a slice -in a method the receiver must still be a pointer.) -In the examples above, if
- -pointerMethod
modifies -the fields ofs
, -the caller will see those changes, butvalueMethod
-is called with a copy of the caller's argument (that's the definition -of passing a value), so changes it makes will be invisible to the caller. --By the way, in Java method receivers are always pointers, -although their pointer nature is somewhat disguised -(and there is a proposal to add value receivers to the language). -It is the value receivers in Go that are unusual. -
- --Second is the consideration of efficiency. If the receiver is large, -a big
- -struct
for instance, it will be much cheaper to -use a pointer receiver. --Next is consistency. If some of the methods of the type must have -pointer receivers, the rest should too, so the method set is -consistent regardless of how the type is used. -See the section on method sets -for details. -
- --For types such as basic types, slices, and small
- - -structs
, -a value receiver is very cheap so unless the semantics of the method -requires a pointer, a value receiver is efficient and clear. --What's the difference between new and make?
- --In short:
- -new
allocates memory, whilemake
initializes -the slice, map, and channel types. --See the relevant section -of Effective Go for more details. -
- --What is the size of an
- -int
on a 64 bit machine?-The sizes of
- -int
anduint
are implementation-specific -but the same as each other on a given platform. -For portability, code that relies on a particular -size of value should use an explicitly sized type, likeint64
. -On 32-bit machines the compilers use 32-bit integers by default, -while on 64-bit machines integers have 64 bits. -(Historically, this was not always true.) --On the other hand, floating-point scalars and complex -types are always sized (there are no
- -float
orcomplex
basic types), -because programmers should be aware of precision when using floating-point numbers. -The default type used for an (untyped) floating-point constant isfloat64
. -Thusfoo
:=
3.0
declares a variablefoo
-of typefloat64
. -For afloat32
variable initialized by an (untyped) constant, the variable type -must be specified explicitly in the variable declaration: --var foo float32 = 3.0 -- --Alternatively, the constant must be given a type with a conversion as in -
- -foo := float32(3.0)
. --How do I know whether a variable is allocated on the heap or the stack?
- --From a correctness standpoint, you don't need to know. -Each variable in Go exists as long as there are references to it. -The storage location chosen by the implementation is irrelevant to the -semantics of the language. -
- --The storage location does have an effect on writing efficient programs. -When possible, the Go compilers will allocate variables that are -local to a function in that function's stack frame. However, if the -compiler cannot prove that the variable is not referenced after the -function returns, then the compiler must allocate the variable on the -garbage-collected heap to avoid dangling pointer errors. -Also, if a local variable is very large, it might make more sense -to store it on the heap rather than the stack. -
- --In the current compilers, if a variable has its address taken, that variable -is a candidate for allocation on the heap. However, a basic escape -analysis recognizes some cases when such variables will not -live past the return from the function and can reside on the stack. -
- --Why does my Go process use so much virtual memory?
- --The Go memory allocator reserves a large region of virtual memory as an arena -for allocations. This virtual memory is local to the specific Go process; the -reservation does not deprive other processes of memory. -
- --To find the amount of actual memory allocated to a Go process, use the Unix -
- -top
command and consult theRES
(Linux) or -RSIZE
(macOS) columns. - -Concurrency
- --What operations are atomic? What about mutexes?
- --A description of the atomicity of operations in Go can be found in -the Go Memory Model document. -
- --Low-level synchronization and atomic primitives are available in the -sync and -sync/atomic -packages. -These packages are good for simple tasks such as incrementing -reference counts or guaranteeing small-scale mutual exclusion. -
- --For higher-level operations, such as coordination among -concurrent servers, higher-level techniques can lead -to nicer programs, and Go supports this approach through -its goroutines and channels. -For instance, you can structure your program so that only one -goroutine at a time is ever responsible for a particular piece of data. -That approach is summarized by the original -Go proverb, -
- --Do not communicate by sharing memory. Instead, share memory by communicating. -
- --See the Share Memory By Communicating code walk -and its -associated article for a detailed discussion of this concept. -
- --Large concurrent programs are likely to borrow from both these toolkits. -
- --Why doesn't my program run faster with more CPUs?
- --Whether a program runs faster with more CPUs depends on the problem -it is solving. -The Go language provides concurrency primitives, such as goroutines -and channels, but concurrency only enables parallelism -when the underlying problem is intrinsically parallel. -Problems that are intrinsically sequential cannot be sped up by adding -more CPUs, while those that can be broken into pieces that can -execute in parallel can be sped up, sometimes dramatically. -
- --Sometimes adding more CPUs can slow a program down. -In practical terms, programs that spend more time -synchronizing or communicating than doing useful computation -may experience performance degradation when using -multiple OS threads. -This is because passing data between threads involves switching -contexts, which has significant cost, and that cost can increase -with more CPUs. -For instance, the prime sieve example -from the Go specification has no significant parallelism although it launches many -goroutines; increasing the number of threads (CPUs) is more likely to slow it down than -to speed it up. -
- --For more detail on this topic see the talk entitled -Concurrency -is not Parallelism. - -
-How can I control the number of CPUs?
- --The number of CPUs available simultaneously to executing goroutines is -controlled by the
- -GOMAXPROCS
shell environment variable, -whose default value is the number of CPU cores available. -Programs with the potential for parallel execution should therefore -achieve it by default on a multiple-CPU machine. -To change the number of parallel CPUs to use, -set the environment variable or use the similarly-named -function -of the runtime package to configure the -run-time support to utilize a different number of threads. -Setting it to 1 eliminates the possibility of true parallelism, -forcing independent goroutines to take turns executing. --The runtime can allocate more threads than the value -of
- -GOMAXPROCS
to service multiple outstanding -I/O requests. -GOMAXPROCS
only affects how many goroutines -can actually execute at once; arbitrarily more may be blocked -in system calls. --Go's goroutine scheduler is not as good as it needs to be, although it -has improved over time. -In the future, it may better optimize its use of OS threads. -For now, if there are performance issues, -setting
- - -GOMAXPROCS
on a per-application basis may help. --Why is there no goroutine ID?
- --Goroutines do not have names; they are just anonymous workers. -They expose no unique identifier, name, or data structure to the programmer. -Some people are surprised by this, expecting the
- -go
-statement to return some item that can be used to access and control -the goroutine later. --The fundamental reason goroutines are anonymous is so that -the full Go language is available when programming concurrent code. -By contrast, the usage patterns that develop when threads and goroutines are -named can restrict what a library using them can do. -
- --Here is an illustration of the difficulties. -Once one names a goroutine and constructs a model around -it, it becomes special, and one is tempted to associate all computation -with that goroutine, ignoring the possibility -of using multiple, possibly shared goroutines for the processing. -If the
- -net/http
package associated per-request -state with a goroutine, -clients would be unable to use more goroutines -when serving a request. --Moreover, experience with libraries such as those for graphics systems -that require all processing to occur on the "main thread" -has shown how awkward and limiting the approach can be when -deployed in a concurrent language. -The very existence of a special thread or goroutine forces -the programmer to distort the program to avoid crashes -and other problems caused by inadvertently operating -on the wrong thread. -
- --For those cases where a particular goroutine is truly special, -the language provides features such as channels that can be -used in flexible ways to interact with it. -
- -Functions and Methods
- --Why do T and *T have different method sets?
- --As the Go specification says, -the method set of a type
- -T
consists of all methods -with receiver typeT
, -while that of the corresponding pointer -type*T
consists of all methods with receiver*T
or -T
. -That means the method set of*T
-includes that ofT
, -but not the reverse. --This distinction arises because -if an interface value contains a pointer
- -*T
, -a method call can obtain a value by dereferencing the pointer, -but if an interface value contains a valueT
, -there is no safe way for a method call to obtain a pointer. -(Doing so would allow a method to modify the contents of -the value inside the interface, which is not permitted by -the language specification.) --Even in cases where the compiler could take the address of a value -to pass to the method, if the method modifies the value the changes -will be lost in the caller. -As an example, if the
- -Write
method of -bytes.Buffer
-used a value receiver rather than a pointer, -this code: --var buf bytes.Buffer -io.Copy(buf, os.Stdin) -- --would copy standard input into a copy of
- -buf
, -not intobuf
itself. -This is almost never the desired behavior. --What happens with closures running as goroutines?
- --Some confusion may arise when using closures with concurrency. -Consider the following program: -
- --func main() { - done := make(chan bool) - - values := []string{"a", "b", "c"} - for _, v := range values { - go func() { - fmt.Println(v) - done <- true - }() - } - - // wait for all goroutines to complete before exiting - for _ = range values { - <-done - } -} -- --One might mistakenly expect to see
- -a, b, c
as the output. -What you'll probably see instead isc, c, c
. This is because -each iteration of the loop uses the same instance of the variablev
, so -each closure shares that single variable. When the closure runs, it prints the -value ofv
at the timefmt.Println
is executed, -butv
may have been modified since the goroutine was launched. -To help detect this and other problems before they happen, run -go vet
. --To bind the current value of
- -v
to each closure as it is launched, one -must modify the inner loop to create a new variable each iteration. -One way is to pass the variable as an argument to the closure: -- for _, v := range values { - go func(u string) { - fmt.Println(u) - done <- true - }(v) - } -- --In this example, the value of
- -v
is passed as an argument to the -anonymous function. That value is then accessible inside the function as -the variableu
. --Even easier is just to create a new variable, using a declaration style that may -seem odd but works fine in Go: -
- -- for _, v := range values { - v := v // create a new 'v'. - go func() { - fmt.Println(v) - done <- true - }() - } -- --This behavior of the language, not defining a new variable for -each iteration, may have been a mistake in retrospect. -It may be addressed in a later version but, for compatibility, -cannot change in Go version 1. -
- -Control flow
- --Why does Go not have the
- -?:
operator?-There is no ternary testing operation in Go. -You may use the following to achieve the same -result: -
- --if expr { - n = trueVal -} else { - n = falseVal -} -- --The reason
- -?:
is absent from Go is that the language's designers -had seen the operation used too often to create impenetrably complex expressions. -Theif-else
form, although longer, -is unquestionably clearer. -A language needs only one conditional control flow construct. -Packages and Testing
- --How do I create a multifile package?
- --Put all the source files for the package in a directory by themselves. -Source files can refer to items from different files at will; there is -no need for forward declarations or a header file. -
- --Other than being split into multiple files, the package will compile and test -just like a single-file package. -
- --How do I write a unit test?
- --Create a new file ending in
- -_test.go
in the same directory -as your package sources. Inside that file,import "testing"
-and write functions of the form --func TestFoo(t *testing.T) { - ... -} -- --Run
- -go test
in that directory. -That script finds theTest
functions, -builds a test binary, and runs it. -See the How to Write Go Code document, -the
- -testing
package -and thego test
subcommand for more details. --Where is my favorite helper function for testing?
- --Go's standard
- -testing
package makes it easy to write unit tests, but it lacks -features provided in other language's testing frameworks such as assertion functions. -An earlier section of this document explained why Go -doesn't have assertions, and -the same arguments apply to the use ofassert
in tests. -Proper error handling means letting other tests run after one has failed, so -that the person debugging the failure gets a complete picture of what is -wrong. It is more useful for a test to report that -isPrime
gives the wrong answer for 2, 3, 5, and 7 (or for -2, 4, 8, and 16) than to report thatisPrime
gives the wrong -answer for 2 and therefore no more tests were run. The programmer who -triggers the test failure may not be familiar with the code that fails. -Time invested writing a good error message now pays off later when the -test breaks. --A related point is that testing frameworks tend to develop into mini-languages -of their own, with conditionals and controls and printing mechanisms, -but Go already has all those capabilities; why recreate them? -We'd rather write tests in Go; it's one fewer language to learn and the -approach keeps the tests straightforward and easy to understand. -
- --If the amount of extra code required to write -good errors seems repetitive and overwhelming, the test might work better if -table-driven, iterating over a list of inputs and outputs defined -in a data structure (Go has excellent support for data structure literals). -The work to write a good test and good error messages will then be amortized over many -test cases. The standard Go library is full of illustrative examples, such as in -the formatting tests for the
- -fmt
package. --Why isn't X in the standard library?
- --The standard library's purpose is to support the runtime, connect to -the operating system, and provide key functionality that many Go -programs require, such as formatted I/O and networking. -It also contains elements important for web programming, including -cryptography and support for standards like HTTP, JSON, and XML. -
- --There is no clear criterion that defines what is included because for -a long time, this was the only Go library. -There are criteria that define what gets added today, however. -
- --New additions to the standard library are rare and the bar for -inclusion is high. -Code included in the standard library bears a large ongoing maintenance cost -(often borne by those other than the original author), -is subject to the Go 1 compatibility promise -(blocking fixes to any flaws in the API), -and is subject to the Go -release schedule, -preventing bug fixes from being available to users quickly. -
- --Most new code should live outside of the standard library and be accessible -via the
- -go
tool's -go get
command. -Such code can have its own maintainers, release cycle, -and compatibility guarantees. -Users can find packages and read their documentation at -godoc.org. --Although there are pieces in the standard library that don't really belong, -such as
- -log/syslog
, we continue to maintain everything in the -library because of the Go 1 compatibility promise. -But we encourage most new code to live elsewhere. -Implementation
- --What compiler technology is used to build the compilers?
- --There are several production compilers for Go, and a number of others -in development for various platforms. -
- --The default compiler,
- -gc
, is included with the -Go distribution as part of the support for thego
-command. -Gc
was originally written in C -because of the difficulties of bootstrapping—you'd need a Go compiler to -set up a Go environment. -But things have advanced and since the Go 1.5 release the compiler has been -a Go program. -The compiler was converted from C to Go using automatic translation tools, as -described in this design document -and talk. -Thus the compiler is now "self-hosting", which means we needed to face -the bootstrapping problem. -The solution is to have a working Go installation already in place, -just as one normally has with a working C installation. -The story of how to bring up a new Go environment from source -is described here and -here. --
- -Gc
is written in Go with a recursive descent parser -and uses a custom loader, also written in Go but -based on the Plan 9 loader, to generate ELF/Mach-O/PE binaries. --At the beginning of the project we considered using LLVM for -
- -gc
but decided it was too large and slow to meet -our performance goals. -More important in retrospect, starting with LLVM would have made it -harder to introduce some of the ABI and related changes, such as -stack management, that Go requires but not are not part of the -standard C setup. -A new LLVM implementation -is starting to come together now, however. --The
- -Gccgo
compiler is a front end written in C++ -with a recursive descent parser coupled to the -standard GCC back end. --Go turned out to be a fine language in which to implement a Go compiler, -although that was not its original goal. -Not being self-hosting from the beginning allowed Go's design to -concentrate on its original use case, which was networked servers. -Had we decided Go should compile itself early on, we might have -ended up with a language targeted more for compiler construction, -which is a worthy goal but not the one we had initially. -
- --Although
- -gc
does not use them (yet?), a native lexer and -parser are available in thego
package -and there is also a native type checker. --How is the run-time support implemented?
- --Again due to bootstrapping issues, the run-time code was originally written mostly in C (with a -tiny bit of assembler) but it has since been translated to Go -(except for some assembler bits). -
- -Gccgo
's run-time support usesglibc
. -Thegccgo
compiler implements goroutines using -a technique called segmented stacks, -supported by recent modifications to the gold linker. -Gollvm
similarly is built on the corresponding -LLVM infrastructure. --Why is my trivial program such a large binary?
- --The linker in the
- -gc
toolchain -creates statically-linked binaries by default. -All Go binaries therefore include the Go -runtime, along with the run-time type information necessary to support dynamic -type checks, reflection, and even panic-time stack traces. --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
weighs a couple of megabytes, but that includes -more powerful run-time support and type and debugging information. --A Go program compiled with
- -gc
can be linked with -the-ldflags=-w
flag to disable DWARF generation, -removing debugging information from the binary but with no -other loss of functionality. -This can reduce the binary size substantially. --Can I stop these complaints about my unused variable/import?
- --The presence of an unused variable may indicate a bug, while -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. -
- --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. -
- --Some have asked for a compiler option to turn those checks off -or at least reduce them to warnings. -Such an option has not been added, though, -because compiler options should not affect the semantics of the -language and because the Go compiler does not report warnings, only -errors that prevent compilation. -
- --There are two reasons for having no warnings. First, if it's worth -complaining about, it's worth fixing in the code. (And if it's not -worth fixing, it's not worth mentioning.) Second, having the compiler -generate warnings encourages the implementation to warn about weak -cases that can make compilation noisy, masking real errors that -should be fixed. -
- --It's easy to address the situation, though. Use the blank identifier -to let unused things persist while you're developing. -
- --import "unused" - -// This declaration marks the import as used by referencing an -// item from the package. -var _ = unused.Item // TODO: Delete before committing! - -func main() { - debugData := debug.Profile() - _ = debugData // Used only during debugging. - .... -} -- --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. -
- --Why does my virus-scanning software think my Go distribution or compiled binary is infected?
- --This is a common occurrence, especially on Windows machines, and is almost always a false positive. -Commercial virus scanning programs are often confused by the structure of Go binaries, which -they don't see as often as those compiled from other languages. -
- --If you've just installed the Go distribution and the system reports it is infected, that's certainly a mistake. -To be really thorough, you can verify the download by comparing the checksum with those on the -downloads page. -
- --In any case, if you believe the report is in error, please report a bug to the supplier of your virus scanner. -Maybe in time virus scanners can learn to understand Go programs. -
- -Performance
- --Why does Go perform badly on benchmark X?
- --One of Go's design goals is to approach the performance of C for comparable -programs, yet on some benchmarks it does quite poorly, including several -in golang.org/x/exp/shootout. -The slowest depend on libraries for which versions of comparable performance -are not available in Go. -For instance, pidigits.go -depends on a multi-precision math package, and the C -versions, unlike Go's, use GMP (which is -written in optimized assembler). -Benchmarks that depend on regular expressions -(regex-dna.go, -for instance) are essentially comparing Go's native regexp package to -mature, highly optimized regular expression libraries like PCRE. -
- --Benchmark games are won by extensive tuning and the Go versions of most -of the benchmarks need attention. If you measure comparable C -and Go programs -(reverse-complement.go -is one example), you'll see the two languages are much closer in raw performance -than this suite would indicate. -
- --Still, there is room for improvement. The compilers are good but could be -better, many libraries need major performance work, and the garbage collector -isn't fast enough yet. (Even if it were, taking care not to generate unnecessary -garbage can have a huge effect.) -
- --In any case, Go can often be very competitive. -There has been significant improvement in the performance of many programs -as the language and tools have developed. -See the blog post about -profiling -Go programs for an informative example. - -
Changes from C
- --Why is the syntax so different from C?
--Other than declaration syntax, the differences are not major and stem -from two desires. First, the syntax should feel light, without too -many mandatory keywords, repetition, or arcana. Second, the language -has been designed to be easy to analyze -and can be parsed without a symbol table. This makes it much easier -to build tools such as debuggers, dependency analyzers, automated -documentation extractors, IDE plug-ins, and so on. C and its -descendants are notoriously difficult in this regard. -
- --Why are declarations backwards?
--They're only backwards if you're used to C. In C, the notion is that a -variable is declared like an expression denoting its type, which is a -nice idea, but the type and expression grammars don't mix very well and -the results can be confusing; consider function pointers. Go mostly -separates expression and type syntax and that simplifies things (using -prefix
-*
for pointers is an exception that proves the rule). In C, -the declaration -- int* a, b; ---declares
-a
to be a pointer but notb
; in Go -- var a, b *int ---declares both to be pointers. This is clearer and more regular. -Also, the
-:=
short declaration form argues that a full variable -declaration should present the same order as:=
so -- var a uint64 = 1 ---has the same effect as -
-- a := uint64(1) ---Parsing is also simplified by having a distinct grammar for types that -is not just the expression grammar; keywords such as
- -func
-andchan
keep things clear. --See the article about -Go's Declaration Syntax -for more details. -
- --Why is there no pointer arithmetic?
--Safety. Without pointer arithmetic it's possible to create a -language that can never derive an illegal address that succeeds -incorrectly. Compiler and hardware technology have advanced to the -point where a loop using array indices can be as efficient as a loop -using pointer arithmetic. Also, the lack of pointer arithmetic can -simplify the implementation of the garbage collector. -
- --Why are
-++
and--
statements and not expressions? And why postfix, not prefix?-Without pointer arithmetic, the convenience value of pre- and postfix -increment operators drops. By removing them from the expression -hierarchy altogether, expression syntax is simplified and the messy -issues around order of evaluation of
- -++
and--
-(considerf(i++)
andp[i] = q[++i]
) -are eliminated as well. The simplification is -significant. As for postfix vs. prefix, either would work fine but -the postfix version is more traditional; insistence on prefix arose -with the STL, a library for a language whose name contains, ironically, a -postfix increment. --Why are there braces but no semicolons? And why can't I put the opening -brace on the next line?
--Go uses brace brackets for statement grouping, a syntax familiar to -programmers who have worked with any language in the C family. -Semicolons, however, are for parsers, not for people, and we wanted to -eliminate them as much as possible. To achieve this goal, Go borrows -a trick from BCPL: the semicolons that separate statements are in the -formal grammar but are injected automatically, without lookahead, by -the lexer at the end of any line that could be the end of a statement. -This works very well in practice but has the effect that it forces a -brace style. For instance, the opening brace of a function cannot -appear on a line by itself. -
- --Some have argued that the lexer should do lookahead to permit the -brace to live on the next line. We disagree. Since Go code is meant -to be formatted automatically by -
- -gofmt
, -some style must be chosen. That style may differ from what -you've used in C or Java, but Go is a different language and -gofmt
's style is as good as any other. More -important—much more important—the advantages of a single, -programmatically mandated format for all Go programs greatly outweigh -any perceived disadvantages of the particular style. -Note too that Go's style means that an interactive implementation of -Go can use the standard syntax one line at a time without special rules. --Why do garbage collection? Won't it be too expensive?
--One of the biggest sources of bookkeeping in systems programs is -managing the lifetimes of allocated objects. -In languages such as C in which it is done manually, -it can consume a significant amount of programmer time and is -often the cause of pernicious bugs. -Even in languages like C++ or Rust that provide mechanisms -to assist, those mechanisms can have a significant effect on the -design of the software, often adding programming overhead -of its own. -We felt it was critical to eliminate such -programmer overheads, and advances in garbage collection -technology in the last few years gave us confidence that it -could be implemented cheaply enough, and with low enough -latency, that it could be a viable approach for networked -systems. -
- --Much of the difficulty of concurrent programming -has its roots in the object lifetime problem: -as objects get passed among threads it becomes cumbersome -to guarantee they become freed safely. -Automatic garbage collection makes concurrent code far easier to write. -Of course, implementing garbage collection in a concurrent environment is -itself a challenge, but meeting it once rather than in every -program helps everyone. -
- --Finally, concurrency aside, garbage collection makes interfaces -simpler because they don't need to specify how memory is managed across them. -
- --This is not to say that the recent work in languages -like Rust that bring new ideas to the problem of managing -resources is misguided; we encourage this work and are excited to see -how it evolves. -But Go takes a more traditional approach by addressing -object lifetimes through -garbage collection, and garbage collection alone. -
- --The current implementation is a mark-and-sweep collector. -If the machine is a multiprocessor, the collector runs on a separate CPU -core in parallel with the main program. -Major work on the collector in recent years has reduced pause times -often to the sub-millisecond range, even for large heaps, -all but eliminating one of the major objections to garbage collection -in networked servers. -Work continues to refine the algorithm, reduce overhead and -latency further, and to explore new approaches. -The 2018 -ISMM keynote -by Rick Hudson of the Go team -describes the progress so far and suggests some future approaches. -
- --On the topic of performance, keep in mind that Go gives the programmer -considerable control over memory layout and allocation, much more than -is typical in garbage-collected languages. A careful programmer can reduce -the garbage collection overhead dramatically by using the language well; -see the article about -profiling -Go programs for a worked example, including a demonstration of Go's -profiling tools. -
diff --git a/content/doc/go_mem.html b/content/doc/go_mem.html deleted file mode 100644 index d355beba..00000000 --- a/content/doc/go_mem.html +++ /dev/null @@ -1,570 +0,0 @@ - - - - -Introduction
- --The Go memory model specifies the conditions under which -reads of a variable in one goroutine can be guaranteed to -observe values produced by writes to the same variable in a different goroutine. -
- - -Advice
- --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
-andsync/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. -
- -Happens Before
- --Within a single goroutine, reads and writes must behave -as if they executed in the order specified by the program. -That is, compilers and processors may reorder the reads and writes -executed within a single goroutine only when the reordering -does not change the behavior within that goroutine -as defined by the language specification. -Because of this reordering, the execution order observed -by one goroutine may differ from the order perceived -by another. For example, if one goroutine -executes
- -a = 1; b = 2;
, another might observe -the updated value ofb
before the updated value ofa
. --To specify the requirements of reads and writes, we define -happens before, a partial order on the execution -of memory operations in a Go program. If event e1 happens -before event e2, then we say that e2 happens after e1. -Also, if e1 does not happen before e2 and does not happen -after e2, then we say that e1 and e2 happen concurrently. -
- --Within a single goroutine, the happens-before order is the -order expressed by the program. -
- --A read r of a variable
- -v
is allowed to observe a write w tov
-if both of the following hold: --
- -- r does not happen before w.
-- There is no other write w' to
-v
that happens - after w but before r.-To guarantee that a read r of a variable
- -v
observes a -particular write w tov
, ensure that w is the only -write r is allowed to observe. -That is, r is guaranteed to observe w if both of the following hold: --
- -- w happens before r.
-- Any other write to the shared variable
-v
-either happens before w or after r.-This pair of conditions is stronger than the first pair; -it requires that there are no other writes happening -concurrently with w or r. -
- --Within a single goroutine, -there is no concurrency, so the two definitions are equivalent: -a read r observes the value written by the most recent write w to
- -v
. -When multiple goroutines access a shared variablev
, -they must use synchronization events to establish -happens-before conditions that ensure reads observe the -desired writes. --The initialization of variable
- -v
with the zero value -forv
's type behaves as a write in the memory model. --Reads and writes of values larger than a single machine word -behave as multiple machine-word-sized operations in an -unspecified order. -
- -Synchronization
- -Initialization
- --Program initialization runs in a single goroutine, -but that goroutine may create other goroutines, -which run concurrently. -
- --If a package
- -p
imports packageq
, the completion of -q
'sinit
functions happens before the start of any ofp
's. --The start of the function
- -main.main
happens after -allinit
functions have finished. -Goroutine creation
- --The
- -go
statement that starts a new goroutine -happens before the goroutine's execution begins. --For example, in this program: -
- --var a string - -func f() { - print(a) -} - -func hello() { - a = "hello, world" - go f() -} -- --calling
- -hello
will print"hello, world"
-at some point in the future (perhaps afterhello
has returned). -Goroutine destruction
- --The exit of a goroutine is not guaranteed to happen before -any event in the program. For example, in this program: -
- --var a string - -func hello() { - go func() { a = "hello" }() - print(a) -} -- --the assignment to
- -a
is not followed by -any synchronization event, so it is not guaranteed to be -observed by any other goroutine. -In fact, an aggressive compiler might delete the entirego
statement. --If the effects of a goroutine must be observed by another goroutine, -use a synchronization mechanism such as a lock or channel -communication to establish a relative ordering. -
- -Channel communication
- --Channel communication is the main method of synchronization -between goroutines. Each send on a particular channel -is matched to a corresponding receive from that channel, -usually in a different goroutine. -
- --A send on a channel happens before the corresponding -receive from that channel completes. -
- --This program: -
- --var c = make(chan int, 10) -var a string - -func f() { - a = "hello, world" - c <- 0 -} - -func main() { - go f() - <-c - print(a) -} -- --is guaranteed to print
- -"hello, world"
. The write toa
-happens before the send onc
, which happens before -the corresponding receive onc
completes, which happens before -the-The closing of a channel happens before a receive that returns a zero value -because the channel is closed. -
- --In the previous example, replacing -
- -c <- 0
withclose(c)
-yields a program with the same guaranteed behavior. --A receive from an unbuffered channel happens before -the send on that channel completes. -
- --This program (as above, but with the send and receive statements swapped and -using an unbuffered channel): -
- --var c = make(chan int) -var a string - -func f() { - a = "hello, world" - <-c -} -- --func main() { - go f() - c <- 0 - print(a) -} -- --is also guaranteed to print
- -"hello, world"
. The write toa
-happens before the receive onc
, which happens before -the corresponding send onc
completes, which happens -before the-If the channel were buffered (e.g.,
- -c = make(chan int, 1)
) -then the program would not be guaranteed to print -"hello, world"
. (It might print the empty string, -crash, or do something else.) --The kth receive on a channel with capacity C happens before the k+Cth send from that channel completes. -
- --This rule generalizes the previous rule to buffered channels. -It allows a counting semaphore to be modeled by a buffered channel: -the number of items in the channel corresponds to the number of active uses, -the capacity of the channel corresponds to the maximum number of simultaneous uses, -sending an item acquires the semaphore, and receiving an item releases -the semaphore. -This is a common idiom for limiting concurrency. -
- --This program starts a goroutine for every entry in the work list, but the -goroutines coordinate using the
- -limit
channel to ensure -that at most three are running work functions at a time. --var limit = make(chan int, 3) - -func main() { - for _, w := range work { - go func(w func()) { - limit <- 1 - w() - <-limit - }(w) - } - select{} -} -- -Locks
- --The
- -sync
package implements two lock data types, -sync.Mutex
andsync.RWMutex
. --For any
- -sync.Mutex
orsync.RWMutex
variablel
and n < m, -call n ofl.Unlock()
happens before call m ofl.Lock()
returns. --This program: -
- --var l sync.Mutex -var a string - -func f() { - a = "hello, world" - l.Unlock() -} - -func main() { - l.Lock() - go f() - l.Lock() - print(a) -} -- --is guaranteed to print
- -"hello, world"
. -The first call tol.Unlock()
(inf
) happens -before the second call tol.Lock()
(inmain
) returns, -which happens before the-For any call to
- -l.RLock
on async.RWMutex
variablel
, -there is an n such that thel.RLock
happens (returns) after call n to -l.Unlock
and the matchingl.RUnlock
happens -before call n+1 tol.Lock
. -Once
- --The
- -sync
package provides a safe mechanism for -initialization in the presence of multiple goroutines -through the use of theOnce
type. -Multiple threads can executeonce.Do(f)
for a particularf
, -but only one will runf()
, and the other calls block -untilf()
has returned. --A single call of
- -f()
fromonce.Do(f)
happens (returns) before any call ofonce.Do(f)
returns. --In this program: -
- --var a string -var once sync.Once - -func setup() { - a = "hello, world" -} - -func doprint() { - once.Do(setup) - print(a) -} - -func twoprint() { - go doprint() - go doprint() -} -- --calling
- -twoprint
will callsetup
exactly -once. -Thesetup
function will complete before either call -of"hello, world"
will be printed -twice. -Incorrect synchronization
- --Note that a read r may observe the value written by a write w -that happens concurrently with r. -Even if this occurs, it does not imply that reads happening after r -will observe writes that happened before w. -
- --In this program: -
- --var a, b int - -func f() { - a = 1 - b = 2 -} - -func g() { - print(b) - print(a) -} - -func main() { - go f() - g() -} -- --it can happen that
- -g
prints2
and then0
. --This fact invalidates a few common idioms. -
- --Double-checked locking is an attempt to avoid the overhead of synchronization. -For example, the
- -twoprint
program might be -incorrectly written as: --var a string -var done bool - -func setup() { - a = "hello, world" - done = true -} - -func doprint() { - if !done { - once.Do(setup) - } - print(a) -} - -func twoprint() { - go doprint() - go doprint() -} -- --but there is no guarantee that, in
- -doprint
, observing the write todone
-implies observing the write toa
. This -version can (incorrectly) print an empty string -instead of"hello, world"
. --Another incorrect idiom is busy waiting for a value, as in: -
- --var a string -var done bool - -func setup() { - a = "hello, world" - done = true -} - -func main() { - go setup() - for !done { - } - print(a) -} -- --As before, there is no guarantee that, in
- -main
, -observing the write todone
-implies observing the write toa
, so this program could -print an empty string too. -Worse, there is no guarantee that the write todone
will ever -be observed bymain
, since there are no synchronization -events between the two threads. The loop inmain
is not -guaranteed to finish. --There are subtler variants on this theme, such as this program. -
- --type T struct { - msg string -} - -var g *T - -func setup() { - t := new(T) - t.msg = "hello, world" - g = t -} - -func main() { - go setup() - for g == nil { - } - print(g.msg) -} -- --Even if
- -main
observesg != nil
and exits its loop, -there is no guarantee that it will observe the initialized -value forg.msg
. --In all these examples, the solution is the same: -use explicit synchronization. -
diff --git a/content/doc/go_spec.html b/content/doc/go_spec.html deleted file mode 100644 index dcc81ed6..00000000 --- a/content/doc/go_spec.html +++ /dev/null @@ -1,6580 +0,0 @@ - - -Introduction
- --This is a reference manual for the Go programming language. For -more information and other documents, see golang.org. -
- --Go is a general-purpose language designed with systems programming -in mind. It is strongly typed and garbage-collected and has explicit -support for concurrent programming. Programs are constructed from -packages, whose properties allow efficient management of -dependencies. -
- --The grammar is compact and regular, allowing for easy analysis by -automatic tools such as integrated development environments. -
- -Notation
--The syntax is specified using Extended Backus-Naur Form (EBNF): -
- --Production = production_name "=" [ Expression ] "." . -Expression = Alternative { "|" Alternative } . -Alternative = Term { Term } . -Term = production_name | token [ "…" token ] | Group | Option | Repetition . -Group = "(" Expression ")" . -Option = "[" Expression "]" . -Repetition = "{" Expression "}" . -- --Productions are expressions constructed from terms and the following -operators, in increasing precedence: -
--| alternation -() grouping -[] option (0 or 1 times) -{} repetition (0 to n times) -- --Lower-case production names are used to identify lexical tokens. -Non-terminals are in CamelCase. Lexical tokens are enclosed in -double quotes
- -""
or back quotes``
. --The form
- -a … b
represents the set of characters from -a
throughb
as alternatives. The horizontal -ellipsis…
is also used elsewhere in the spec to informally denote various -enumerations or code snippets that are not further specified. The character…
-(as opposed to the three characters...
) is not a token of the Go -language. -Source code representation
- --Source code is Unicode text encoded in -UTF-8. The text is not -canonicalized, so a single accented code point is distinct from the -same character constructed from combining an accent and a letter; -those are treated as two code points. For simplicity, this document -will use the unqualified term character to refer to a Unicode code point -in the source text. -
--Each code point is distinct; for instance, upper and lower case letters -are different characters. -
--Implementation restriction: For compatibility with other tools, a -compiler may disallow the NUL character (U+0000) in the source text. -
--Implementation restriction: For compatibility with other tools, a -compiler may ignore a UTF-8-encoded byte order mark -(U+FEFF) if it is the first Unicode code point in the source text. -A byte order mark may be disallowed anywhere else in the source. -
- -Characters
- --The following terms are used to denote specific Unicode character classes: -
--newline = /* the Unicode code point U+000A */ . -unicode_char = /* an arbitrary Unicode code point except newline */ . -unicode_letter = /* a Unicode code point classified as "Letter" */ . -unicode_digit = /* a Unicode code point classified as "Number, decimal digit" */ . -- --In The Unicode Standard 8.0, -Section 4.5 "General Category" defines a set of character categories. -Go treats all characters in any of the Letter categories Lu, Ll, Lt, Lm, or Lo -as Unicode letters, and those in the Number category Nd as Unicode digits. -
- -Letters and digits
- --The underscore character
-_
(U+005F) is considered a letter. --letter = unicode_letter | "_" . -decimal_digit = "0" … "9" . -octal_digit = "0" … "7" . -hex_digit = "0" … "9" | "A" … "F" | "a" … "f" . -- -Lexical elements
- -Comments
- --Comments serve as program documentation. There are two forms: -
- --
- -- -Line comments start with the character sequence
-//
-and stop at the end of the line. -- -General comments start with the character sequence
-/*
-and stop with the first subsequent character sequence*/
. --A comment cannot start inside a rune or -string literal, or inside a comment. -A general comment containing no newlines acts like a space. -Any other comment acts like a newline. -
- -Tokens
- --Tokens form the vocabulary of the Go language. -There are four classes: identifiers, keywords, operators -and punctuation, and literals. White space, formed from -spaces (U+0020), horizontal tabs (U+0009), -carriage returns (U+000D), and newlines (U+000A), -is ignored except as it separates tokens -that would otherwise combine into a single token. Also, a newline or end of file -may trigger the insertion of a semicolon. -While breaking the input into tokens, -the next token is the longest sequence of characters that form a -valid token. -
- -Semicolons
- --The formal grammar uses semicolons
- -";"
as terminators in -a number of productions. Go programs may omit most of these semicolons -using the following two rules: --
- -- -When the input is broken into tokens, a semicolon is automatically inserted -into the token stream immediately after a line's final token if that token is -
- --
-- an - identifier -
- -- an - integer, - floating-point, - imaginary, - rune, or - string literal -
- -- one of the keywords -
- -break
, -continue
, -fallthrough
, or -return
-- one of the operators and punctuation -
-++
, ---
, -)
, -]
, or -}
-- -To allow complex statements to occupy a single line, a semicolon -may be omitted before a closing
-")"
or"}"
. --To reflect idiomatic use, code examples in this document elide semicolons -using these rules. -
- - -Identifiers
- --Identifiers name program entities such as variables and types. -An identifier is a sequence of one or more letters and digits. -The first character in an identifier must be a letter. -
--identifier = letter { letter | unicode_digit } . ---a -_x9 -ThisVariableIsExported -αβ -- --Some identifiers are predeclared. -
- - -Keywords
- --The following keywords are reserved and may not be used as identifiers. -
--break default func interface select -case defer go map struct -chan else goto package switch -const fallthrough if range type -continue for import return var -- -Operators and punctuation
- --The following character sequences represent operators -(including assignment operators) and punctuation: -
--+ & += &= && == != ( ) -- | -= |= || < <= [ ] -* ^ *= ^= <- > >= { } -/ << /= <<= ++ = := , ; -% >> %= >>= -- ! ... . : - &^ &^= -- -Integer literals
- --An integer literal is a sequence of digits representing an -integer constant. -An optional prefix sets a non-decimal base:
-0
for octal,0x
or -0X
for hexadecimal. In hexadecimal literals, letters -a-f
andA-F
represent values 10 through 15. --int_lit = decimal_lit | octal_lit | hex_lit . -decimal_lit = ( "1" … "9" ) { decimal_digit } . -octal_lit = "0" { octal_digit } . -hex_lit = "0" ( "x" | "X" ) hex_digit { hex_digit } . -- --42 -0600 -0xBadFace -170141183460469231731687303715884105727 -- -Floating-point literals
--A floating-point literal is a decimal representation of a -floating-point constant. -It has an integer part, a decimal point, a fractional part, -and an exponent part. The integer and fractional part comprise -decimal digits; the exponent part is an
-e
orE
-followed by an optionally signed decimal exponent. One of the -integer part or the fractional part may be elided; one of the decimal -point or the exponent may be elided. --float_lit = decimals "." [ decimals ] [ exponent ] | - decimals exponent | - "." decimals [ exponent ] . -decimals = decimal_digit { decimal_digit } . -exponent = ( "e" | "E" ) [ "+" | "-" ] decimals . -- --0. -72.40 -072.40 // == 72.40 -2.71828 -1.e+0 -6.67428e-11 -1E6 -.25 -.12345E+5 -- -Imaginary literals
--An imaginary literal is a decimal representation of the imaginary part of a -complex constant. -It consists of a -floating-point literal -or decimal integer followed -by the lower-case letter
-i
. --imaginary_lit = (decimals | float_lit) "i" . -- --0i -011i // == 11i -0.i -2.71828i -1.e+0i -6.67428e-11i -1E6i -.25i -.12345E+5i -- - -Rune literals
- --A rune literal represents a rune constant, -an integer value identifying a Unicode code point. -A rune literal is expressed as one or more characters enclosed in single quotes, -as in
-'x'
or'\n'
. -Within the quotes, any character may appear except newline and unescaped single -quote. A single quoted character represents the Unicode value -of the character itself, -while multi-character sequences beginning with a backslash encode -values in various formats. --The simplest form represents the single character within the quotes; -since Go source text is Unicode characters encoded in UTF-8, multiple -UTF-8-encoded bytes may represent a single integer value. For -instance, the literal
-'a'
holds a single byte representing -a literala
, Unicode U+0061, value0x61
, while -'ä'
holds two bytes (0xc3
0xa4
) representing -a literala
-dieresis, U+00E4, value0xe4
. --Several backslash escapes allow arbitrary values to be encoded as -ASCII text. There are four ways to represent the integer value -as a numeric constant:
-\x
followed by exactly two hexadecimal -digits;\u
followed by exactly four hexadecimal digits; -\U
followed by exactly eight hexadecimal digits, and a -plain backslash\
followed by exactly three octal digits. -In each case the value of the literal is the value represented by -the digits in the corresponding base. --Although these representations all result in an integer, they have -different valid ranges. Octal escapes must represent a value between -0 and 255 inclusive. Hexadecimal escapes satisfy this condition -by construction. The escapes
-\u
and\U
-represent Unicode code points so within them some values are illegal, -in particular those above0x10FFFF
and surrogate halves. --After a backslash, certain single-character escapes represent special values: -
--\a U+0007 alert or bell -\b U+0008 backspace -\f U+000C form feed -\n U+000A line feed or newline -\r U+000D carriage return -\t U+0009 horizontal tab -\v U+000b vertical tab -\\ U+005c backslash -\' U+0027 single quote (valid escape only within rune literals) -\" U+0022 double quote (valid escape only within string literals) ---All other sequences starting with a backslash are illegal inside rune literals. -
--rune_lit = "'" ( unicode_value | byte_value ) "'" . -unicode_value = unicode_char | little_u_value | big_u_value | escaped_char . -byte_value = octal_byte_value | hex_byte_value . -octal_byte_value = `\` octal_digit octal_digit octal_digit . -hex_byte_value = `\` "x" hex_digit hex_digit . -little_u_value = `\` "u" hex_digit hex_digit hex_digit hex_digit . -big_u_value = `\` "U" hex_digit hex_digit hex_digit hex_digit - hex_digit hex_digit hex_digit hex_digit . -escaped_char = `\` ( "a" | "b" | "f" | "n" | "r" | "t" | "v" | `\` | "'" | `"` ) . -- --'a' -'ä' -'本' -'\t' -'\000' -'\007' -'\377' -'\x07' -'\xff' -'\u12e4' -'\U00101234' -'\'' // rune literal containing single quote character -'aa' // illegal: too many characters -'\xa' // illegal: too few hexadecimal digits -'\0' // illegal: too few octal digits -'\uDFFF' // illegal: surrogate half -'\U00110000' // illegal: invalid Unicode code point -- - -String literals
- --A string literal represents a string constant -obtained from concatenating a sequence of characters. There are two forms: -raw string literals and interpreted string literals. -
--Raw string literals are character sequences between back quotes, as in -
-`foo`
. Within the quotes, any character may appear except -back quote. The value of a raw string literal is the -string composed of the uninterpreted (implicitly UTF-8-encoded) characters -between the quotes; -in particular, backslashes have no special meaning and the string may -contain newlines. -Carriage return characters ('\r') inside raw string literals -are discarded from the raw string value. --Interpreted string literals are character sequences between double -quotes, as in
- -"bar"
. -Within the quotes, any character may appear except newline and unescaped double quote. -The text between the quotes forms the -value of the literal, with backslash escapes interpreted as they -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 -bytes of the resulting string; all other escapes represent -the (possibly multi-byte) UTF-8 encoding of individual characters. -Thus inside a string literal\377
and\xFF
represent -a single byte of value0xFF
=255, whileÿ
, -\u00FF
,\U000000FF
and\xc3\xbf
represent -the two bytes0xc3
0xbf
of the UTF-8 encoding of character -U+00FF. --string_lit = raw_string_lit | interpreted_string_lit . -raw_string_lit = "`" { unicode_char | newline } "`" . -interpreted_string_lit = `"` { unicode_value | byte_value } `"` . -- --`abc` // same as "abc" -`\n -\n` // same as "\\n\n\\n" -"\n" -"\"" // same as `"` -"Hello, world!\n" -"日本語" -"\u65e5本\U00008a9e" -"\xff\u00FF" -"\uD800" // illegal: surrogate half -"\U00110000" // illegal: invalid Unicode code point -- --These examples all represent the same string: -
- --"日本語" // UTF-8 input text -`日本語` // UTF-8 input text as a raw literal -"\u65e5\u672c\u8a9e" // the explicit Unicode code points -"\U000065e5\U0000672c\U00008a9e" // the explicit Unicode code points -"\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e" // the explicit UTF-8 bytes -- --If the source code represents a character as two code points, such as -a combining form involving an accent and a letter, the result will be -an error if placed in a rune literal (it is not a single code -point), and will appear as two code points if placed in a string -literal. -
- - -Constants
- -There are boolean constants, -rune constants, -integer constants, -floating-point constants, complex constants, -and string constants. Rune, integer, floating-point, -and complex constants are -collectively called numeric constants. -
- --A constant value is represented by a -rune, -integer, -floating-point, -imaginary, -or -string literal, -an identifier denoting a constant, -a constant expression, -a conversion with a result that is a constant, or -the result value of some built-in functions such as -
- -unsafe.Sizeof
applied to any value, -cap
orlen
applied to -some expressions, -real
andimag
applied to a complex constant -andcomplex
applied to numeric constants. -The boolean truth values are represented by the predeclared constants -true
andfalse
. The predeclared identifier -iota denotes an integer constant. --In general, complex constants are a form of -constant expression -and are discussed in that section. -
- --Numeric constants represent exact values of arbitrary precision and do not overflow. -Consequently, there are no constants denoting the IEEE-754 negative zero, infinity, -and not-a-number values. -
- --Constants may be typed or untyped. -Literal constants,
- -true
,false
,iota
, -and certain constant expressions -containing only untyped constant operands are untyped. --A constant may be given a type explicitly by a constant declaration -or conversion, or implicitly when used in a -variable declaration or an -assignment or as an -operand in an expression. -It is an error if the constant value -cannot be represented as a value of the respective type. -
- --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 isbool
,rune
, -int
,float64
,complex128
orstring
-respectively, depending on whether it is a boolean, rune, integer, floating-point, -complex, or string constant. --Implementation restriction: Although numeric constants have arbitrary -precision in the language, a compiler may implement them using an -internal representation with limited precision. That said, every -implementation must: -
--
-- Represent integer constants with at least 256 bits.
- -- Represent floating-point constants, including the parts of - a complex constant, with a mantissa of at least 256 bits - and a signed binary exponent of at least 16 bits.
- -- Give an error if unable to represent an integer constant - precisely.
- -- Give an error if unable to represent a floating-point or - complex constant due to overflow.
- -- Round to the nearest representable constant if unable to - represent a floating-point or complex constant due to limits - on precision.
--These requirements apply both to literal constants and to the result -of evaluating constant -expressions. -
- -Variables
- --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 identifiernil
, -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. -
- - -Types
- --A type determines a set of values together with operations and methods specific -to those values. A type may be denoted by a type name, if it has one, -or specified using a type literal, which composes a type from existing types. -
- --Type = TypeName | TypeLit | "(" Type ")" . -TypeName = identifier | QualifiedIdent . -TypeLit = ArrayType | StructType | PointerType | FunctionType | InterfaceType | - SliceType | MapType | ChannelType . -- --The language predeclares certain type names. -Others are introduced with type declarations. -Composite types—array, struct, pointer, function, -interface, slice, map, and channel types—may be constructed using -type literals. -
- --Each type
- -T
has an underlying type: IfT
-is one of the predeclared boolean, numeric, or string types, or a type literal, -the corresponding underlying -type isT
itself. Otherwise,T
's underlying type -is the underlying type of the type to whichT
refers in its -type declaration. --type ( - A1 = string - A2 = A1 -) - -type ( - B1 string - B2 B1 - B3 []B1 - B4 B3 -) -- --The underlying type of
- -string
,A1
,A2
,B1
, -andB2
isstring
. -The underlying type of[]B1
,B3
, andB4
is[]B1
. -Method sets
--A type may have a method set associated with it. -The method set of an interface type is its interface. -The method set of any other type
- -T
consists of all -methods declared with receiver typeT
. -The method set of the corresponding pointer type*T
-is the set of all methods declared with receiver*T
orT
-(that is, it also contains the method set ofT
). -Further rules apply to structs containing embedded fields, as described -in the section on struct types. -Any other type has an empty method set. -In a method set, each method must have a -unique -non-blank method name. --The method set of a type determines the interfaces that the -type implements -and the methods that can be called -using a receiver of that type. -
- -Boolean types
- --A boolean type represents the set of Boolean truth values -denoted by the predeclared constants
- -true
-andfalse
. The predeclared boolean type isbool
; -it is a defined type. -Numeric types
- --A numeric type represents sets of integer or floating-point values. -The predeclared architecture-independent numeric types are: -
- --uint8 the set of all unsigned 8-bit integers (0 to 255) -uint16 the set of all unsigned 16-bit integers (0 to 65535) -uint32 the set of all unsigned 32-bit integers (0 to 4294967295) -uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615) - -int8 the set of all signed 8-bit integers (-128 to 127) -int16 the set of all signed 16-bit integers (-32768 to 32767) -int32 the set of all signed 32-bit integers (-2147483648 to 2147483647) -int64 the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807) - -float32 the set of all IEEE-754 32-bit floating-point numbers -float64 the set of all IEEE-754 64-bit floating-point numbers - -complex64 the set of all complex numbers with float32 real and imaginary parts -complex128 the set of all complex numbers with float64 real and imaginary parts - -byte alias for uint8 -rune alias for int32 -- --The value of an n-bit integer is n bits wide and represented using -two's complement arithmetic. -
- --There is also a set of predeclared numeric types with implementation-specific sizes: -
- --uint either 32 or 64 bits -int same size as uint -uintptr an unsigned integer large enough to store the uninterpreted bits of a pointer value -- --To avoid portability issues all numeric types are defined -types and thus distinct except -
byte
, which is an alias foruint8
, and -rune
, which is an alias forint32
. -Explicit conversions -are required when different numeric types are mixed in an expression -or assignment. For instance,int32
andint
-are not the same type even though they may have the same size on a -particular architecture. - - -String types
- --A string type represents the set of string values. -A string value is a (possibly empty) sequence of bytes. -The number of bytes is called the length of the string and is never negative. -Strings are immutable: once created, -it is impossible to change the contents of a string. -The predeclared string type is
- -string
; -it is a defined type. --The length of a string
- - -s
can be discovered using -the built-in functionlen
. -The length is a compile-time constant if the string is a constant. -A string's bytes can be accessed by integer indices -0 throughlen(s)-1
. -It is illegal to take the address of such an element; if -s[i]
is thei
'th byte of a -string,&s[i]
is invalid. -Array types
- --An array is a numbered sequence of elements of a single -type, called the element type. -The number of elements is called the length of the array and is never negative. -
- --ArrayType = "[" ArrayLength "]" ElementType . -ArrayLength = Expression . -ElementType = Type . -- --The length is part of the array's type; it must evaluate to a -non-negative constant -representable by a value -of type
- -int
. -The length of arraya
can be discovered -using the built-in functionlen
. -The elements can be addressed by integer indices -0 throughlen(a)-1
. -Array types are always one-dimensional but may be composed to form -multi-dimensional types. --[32]byte -[2*N] struct { x, y int32 } -[1000]*float64 -[3][5]int -[2][2][2]float64 // same as [2]([2]([2]float64)) -- -Slice types
- --A slice is a descriptor for a contiguous segment of an underlying array and -provides access to a numbered sequence of elements from that array. -A slice type denotes the set of all slices of arrays of its element type. -The number of elements is called the length of the slice and is never negative. -The value of an uninitialized slice is
- -nil
. --SliceType = "[" "]" ElementType . -- --The length of a slice
-s
can be discovered by the built-in function -len
; unlike with arrays it may change during -execution. The elements can be addressed by integer indices -0 throughlen(s)-1
. The slice index of a -given element may be less than the index of the same element in the -underlying array. --A slice, once initialized, is always associated with an underlying -array that holds its elements. A slice therefore shares storage -with its array and with other slices of the same array; by contrast, -distinct arrays always represent distinct storage. -
--The array underlying a slice may extend past the end of the slice. -The capacity is a measure of that extent: it is the sum of -the length of the slice and the length of the array beyond the slice; -a slice of length up to that capacity can be created by -slicing a new one from the original slice. -The capacity of a slice
- -a
can be discovered using the -built-in functioncap(a)
. --A new, initialized slice value for a given element type
- -T
is -made using the built-in function -make
, -which takes a slice type -and parameters specifying the length and optionally the capacity. -A slice created withmake
always allocates a new, hidden array -to which the returned slice value refers. That is, executing --make([]T, length, capacity) -- --produces the same slice as allocating an array and slicing -it, so these two expressions are equivalent: -
- --make([]int, 50, 100) -new([100]int)[0:50] -- --Like arrays, slices are always one-dimensional but may be composed to construct -higher-dimensional objects. -With arrays of arrays, the inner arrays are, by construction, always the same length; -however with slices of slices (or arrays of slices), the inner lengths may vary dynamically. -Moreover, the inner slices must be initialized individually. -
- -Struct types
- --A struct is a sequence of named elements, called fields, each of which has a -name and a type. Field names may be specified explicitly (IdentifierList) or -implicitly (EmbeddedField). -Within a struct, non-blank field names must -be unique. -
- --StructType = "struct" "{" { FieldDecl ";" } "}" . -FieldDecl = (IdentifierList Type | EmbeddedField) [ Tag ] . -EmbeddedField = [ "*" ] TypeName . -Tag = string_lit . -- --// An empty struct. -struct {} - -// A struct with 6 fields. -struct { - x, y int - u float32 - _ float32 // padding - A *[]int - F func() -} -- --A field declared with a type but no explicit field name is called an embedded field. -An embedded field must be specified as -a type name
- -T
or as a pointer to a non-interface type name*T
, -andT
itself may not be -a pointer type. The unqualified type name acts as the field name. --// A struct with four embedded fields of types T1, *T2, P.T3 and *P.T4 -struct { - T1 // field name is T1 - *T2 // field name is T2 - P.T3 // field name is T3 - *P.T4 // field name is T4 - x, y int // field names are x and y -} -- --The following declaration is illegal because field names must be unique -in a struct type: -
- --struct { - T // conflicts with embedded field *T and *P.T - *T // conflicts with embedded field T and *P.T - *P.T // conflicts with embedded field T and *T -} -- --A field or method
- -f
of an -embedded field in a structx
is called promoted if -x.f
is a legal selector that denotes -that field or methodf
. --Promoted fields act like ordinary fields -of a struct except that they cannot be used as field names in -composite literals of the struct. -
- --Given a struct type
-S
and a defined type -T
, promoted methods are included in the method set of the struct as follows: --
- -- - If
- -S
contains an embedded fieldT
, - the method sets ofS
- and*S
both include promoted methods with receiver -T
. The method set of*S
also - includes promoted methods with receiver*T
. -- - If
-S
contains an embedded field*T
, - the method sets ofS
and*S
both - include promoted methods with receiverT
or -*T
. --A field declaration may be followed by an optional string literal tag, -which becomes an attribute for all the fields in the corresponding -field declaration. An empty tag string is equivalent to an absent tag. -The tags are made visible through a reflection interface -and take part in type identity for structs -but are otherwise ignored. -
- --struct { - x, y float64 "" // an empty tag string is like an absent tag - name string "any string is permitted as a tag" - _ [4]byte "ceci n'est pas un champ de structure" -} - -// A struct corresponding to a TimeStamp protocol buffer. -// The tag strings define the protocol buffer field numbers; -// they follow the convention outlined by the reflect package. -struct { - microsec uint64 `protobuf:"1"` - serverIP6 uint64 `protobuf:"2"` -} -- -Pointer types
- --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 . -- --*Point -*[4]int -- -Function types
- --A function type denotes the set of all functions with the same parameter -and result types. The value of an uninitialized variable of function type -is
- -nil
. --FunctionType = "func" Signature . -Signature = Parameters [ Result ] . -Result = Parameters | Type . -Parameters = "(" [ ParameterList [ "," ] ] ")" . -ParameterList = ParameterDecl { "," ParameterDecl } . -ParameterDecl = [ IdentifierList ] [ "..." ] Type . -- --Within a list of parameters or results, the names (IdentifierList) -must either all be present or all be absent. If present, each name -stands for one item (parameter or result) of the specified type and -all non-blank names in the signature -must be unique. -If absent, each type stands for one item of that type. -Parameter and result -lists are always parenthesized except that if there is exactly -one unnamed result it may be written as an unparenthesized type. -
- --The final incoming parameter in a function signature may have -a type prefixed with
- -...
. -A function with such a parameter is called variadic and -may be invoked with zero or more arguments for that parameter. --func() -func(x int) int -func(a, _ int, z float32) bool -func(a, b int, z float32) (bool) -func(prefix string, values ...int) -func(a, b int, z float64, opt ...interface{}) (success bool) -func(int, int, float64) (float64, *[]int) -func(n int) func(p *T) -- - -Interface types
- --An interface type specifies a method set called its interface. -A variable of interface type can store a value of any type with a method set -that is any superset of the interface. Such a type is said to -implement the interface. -The value of an uninitialized variable of interface type is
- -nil
. --InterfaceType = "interface" "{" { MethodSpec ";" } "}" . -MethodSpec = MethodName Signature | InterfaceTypeName . -MethodName = identifier . -InterfaceTypeName = TypeName . -- --As with all method sets, in an interface type, each method must have a -unique -non-blank name. -
- --// A simple File interface -interface { - Read(b Buffer) bool - Write(b Buffer) bool - Close() -} -- --More than one type may implement an interface. -For instance, if two types
- -S1
andS2
-have the method set --func (p T) Read(b Buffer) bool { return … } -func (p T) Write(b Buffer) bool { return … } -func (p T) Close() { … } -- --(where
- -T
stands for eitherS1
orS2
) -then theFile
interface is implemented by bothS1
and -S2
, regardless of what other methods -S1
andS2
may have or share. --A type implements any interface comprising any subset of its methods -and may therefore implement several distinct interfaces. For -instance, all types implement the empty interface: -
- --interface{} -- --Similarly, consider this interface specification, -which appears within a type declaration -to define an interface called
- -Locker
: --type Locker interface { - Lock() - Unlock() -} -- --If
- -S1
andS2
also implement --func (p T) Lock() { … } -func (p T) Unlock() { … } -- --they implement the
- -Locker
interface as well -as theFile
interface. --An interface
- -T
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 ReadWriter interface { - Read(b Buffer) bool - Write(b Buffer) bool -} - -type File interface { - 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 -} -- --An interface type
- -T
may not embed itself -or any interface type that embedsT
, recursively. --// illegal: Bad cannot embed itself -type Bad interface { - Bad -} - -// illegal: Bad1 cannot embed itself using Bad2 -type Bad1 interface { - Bad2 -} -type Bad2 interface { - Bad1 -} -- -Map types
- --A map is an unordered group of elements of one type, called the -element type, indexed by a set of unique keys of another type, -called the key type. -The value of an uninitialized map is
- -nil
. --MapType = "map" "[" KeyType "]" ElementType . -KeyType = Type . -- --The comparison operators -
- -==
and!=
must be fully defined -for operands of the key type; thus the key type must not be a function, map, or -slice. -If the key type is an interface type, these -comparison operators must be defined for the dynamic key values; -failure will cause a run-time panic. - --map[string]int -map[*T]struct{ x, y float64 } -map[string]interface{} -- --The number of map elements is called its length. -For a map
-m
, it can be discovered using the -built-in functionlen
-and may change during execution. Elements may be added during execution -using assignments and retrieved with -index expressions; they may be removed with the -delete
built-in function. --A new, empty map value is made using the built-in -function
- -make
, -which takes the map type and an optional capacity hint as arguments: --make(map[string]int) -make(map[string]int, 100) -- --The initial capacity does not bound its size: -maps grow to accommodate the number of items -stored in them, with the exception of
nil
maps. -Anil
map is equivalent to an empty map except that no elements -may be added. - -Channel types
- --A channel provides a mechanism for -concurrently executing functions -to communicate by -sending and -receiving -values of a specified element type. -The value of an uninitialized channel is
- -nil
. --ChannelType = ( "chan" | "chan" "<-" | "<-" "chan" ) ElementType . -- --The optional
- -<-
operator specifies the channel direction, -send or receive. If no direction is given, the channel is -bidirectional. -A channel may be constrained only to send or only to receive by -assignment or -explicit conversion. --chan T // can be used to send and receive values of type T -chan<- float64 // can only be used to send float64s -<-chan int // can only be used to receive ints -- --The
- -<-
operator associates with the leftmostchan
-possible: --chan<- chan int // same as chan<- (chan int) -chan<- <-chan int // same as chan<- (<-chan int) -<-chan <-chan int // same as <-chan (<-chan int) -chan (<-chan int) -- --A new, initialized channel -value can be made using the built-in function -
- -make
, -which takes the channel type and an optional capacity as arguments: --make(chan int, 100) -- --The capacity, in number of elements, sets the size of the buffer in the channel. -If the capacity is zero or absent, the channel is unbuffered and communication -succeeds only when both a sender and receiver are ready. Otherwise, the channel -is buffered and communication succeeds without blocking if the buffer -is not full (sends) or not empty (receives). -A
- -nil
channel is never ready for communication. --A channel may be closed with the built-in function -
- -close
. -The multi-valued assignment form of the -receive operator -reports whether a received value was sent before -the channel was closed. --A single channel may be used in -send statements, -receive operations, -and calls to the built-in functions -
- -cap
and -len
-by any number of goroutines without further synchronization. -Channels act as first-in-first-out queues. -For example, if one goroutine sends values on a channel -and a second goroutine receives them, the values are -received in the order sent. -Properties of types and values
- -Type identity
- --Two types are either identical or different. -
- --A defined type is always different from any other type. -Otherwise, two types are identical if their underlying type literals are -structurally equivalent; that is, they have the same literal structure and corresponding -components have identical types. In detail: -
- --
- -- Two array types are identical if they have identical element types and - the same array length.
- -- Two slice types are identical if they have identical element types.
- -- Two struct types are identical if they have the same sequence of fields, - and if corresponding fields have the same names, and identical types, - and identical tags. - Non-exported field names from different - packages are always different.
- -- Two pointer types are identical if they have identical base types.
- -- Two function types are identical if they have the same number of parameters - and result values, corresponding parameter and result types are - identical, and either both functions are variadic or neither is. - Parameter and result names are not required to match.
- -- Two interface types are identical if they have the same set of methods - with the same names and identical function types. - Non-exported method names from different - packages are always different. The order of the methods is irrelevant.
- -- Two map types are identical if they have identical key and element types.
- -- Two channel types are identical if they have identical element types and - the same direction.
--Given the declarations -
- --type ( - A0 = []string - A1 = A0 - A2 = struct{ a, b int } - A3 = int - A4 = func(A3, float64) *A0 - A5 = func(x int, _ float64) *[]string -) - -type ( - B0 A0 - B1 []string - B2 struct{ a, b int } - B3 struct{ a, c int } - B4 func(int, float64) *B0 - B5 func(x int, y float64) *A1 -) - -type C0 = B0 -- --these types are identical: -
- --A0, A1, and []string -A2 and struct{ a, b int } -A3 and int -A4, func(int, float64) *[]string, and A5 - -B0 and C0 -[]int and []int -struct{ a, b *T5 } and struct{ a, b *T5 } -func(x int, y float64) *[]string, func(int, float64) (result *[]string), and A5 -- --
- - -B0
andB1
are different because they are new types -created by distinct type definitions; -func(int, float64) *B0
andfunc(x int, y float64) *[]string
-are different becauseB0
is different from[]string
. -Assignability
- --A value
- -x
is assignable to a variable of typeT
-("x
is assignable toT
") if one of the following conditions applies: --
- - -- -
-x
's type is identical toT
. -- -
-x
's typeV
andT
have identical -underlying types and at least one ofV
-orT
is not a defined type. -- -
-T
is an interface type and -x
implementsT
. -- -
-x
is a bidirectional channel value,T
is a channel type, -x
's typeV
andT
have identical element types, -and at least one ofV
orT
is not a defined type. -- -
-x
is the predeclared identifiernil
andT
-is a pointer, function, slice, map, channel, or interface type. -- -
-x
is an untyped constant -representable -by a value of typeT
. -Representability
- --A constant
- -x
is representable -by a value of typeT
if one of the following conditions applies: --
- -- -
- -x
is in the set of values determined byT
. -- -
- -T
is a floating-point type andx
can be rounded toT
's -precision without overflow. Rounding uses IEEE 754 round-to-even rules but with an IEEE -negative zero further simplified to an unsigned zero. Note that constant values never result -in an IEEE negative zero, NaN, or infinity. -- -
-T
is a complex type, andx
's -componentsreal(x)
andimag(x)
-are representable by values ofT
's component type (float32
or -float64
). --x T x is representable by a value of T because - -'a' byte 97 is in the set of byte values -97 rune rune is an alias for int32, and 97 is in the set of 32-bit integers -"foo" string "foo" is in the set of string values -1024 int16 1024 is in the set of 16-bit integers -42.0 byte 42 is in the set of unsigned 8-bit integers -1e10 uint64 10000000000 is in the set of unsigned 64-bit integers -2.718281828459045 float32 2.718281828459045 rounds to 2.7182817 which is in the set of float32 values --1e-1000 float64 -1e-1000 rounds to IEEE -0.0 which is further simplified to 0.0 -0i int 0 is an integer value -(42 + 0i) float32 42.0 (with zero imaginary part) is in the set of float32 values -- --x T x is not representable by a value of T because - -0 bool 0 is not in the set of boolean values -'a' string 'a' is a rune, it is not in the set of string values -1024 byte 1024 is not in the set of unsigned 8-bit integers --1 uint16 -1 is not in the set of unsigned 16-bit integers -1.1 int 1.1 is not an integer value -42i float32 (0 + 42i) is not in the set of float32 values -1e1000 float64 1e1000 overflows to IEEE +Inf after rounding -- - -Blocks
- --A block is a possibly empty sequence of declarations and statements -within matching brace brackets. -
- --Block = "{" StatementList "}" . -StatementList = { Statement ";" } . -- --In addition to explicit blocks in the source code, there are implicit blocks: -
- --
- -- The universe block encompasses all Go source text.
- -- Each package has a package block containing all - Go source text for that package.
- -- Each file has a file block containing all Go source text - in that file.
- -- Each "if", - "for", and - "switch" - statement is considered to be in its own implicit block.
- -- Each clause in a "switch" - or "select" statement - acts as an implicit block.
--Blocks nest and influence scoping. -
- - -Declarations and scope
- --A declaration binds a non-blank identifier to a -constant, -type, -variable, -function, -label, or -package. -Every identifier in a program must be declared. -No identifier may be declared twice in the same block, and -no identifier may be declared in both the file and package block. -
- --The blank identifier may be used like any other identifier -in a declaration, but it does not introduce a binding and thus is not declared. -In the package block, the identifier
- -init
may only be used for -init
function declarations, -and like the blank identifier it does not introduce a new binding. --Declaration = ConstDecl | TypeDecl | VarDecl . -TopLevelDecl = Declaration | FunctionDecl | MethodDecl . -- --The scope of a declared identifier is the extent of source text in which -the identifier denotes the specified constant, type, variable, function, label, or package. -
- --Go is lexically scoped using blocks: -
- --
- -- The scope of a predeclared identifier is the universe block.
- -- The scope of an identifier denoting a constant, type, variable, - or function (but not method) declared at top level (outside any - function) is the package block.
- -- The scope of the package name of an imported package is the file block - of the file containing the import declaration.
- -- The scope of an identifier denoting a method receiver, function parameter, - or result variable is the function body.
- -- The scope of a constant or variable identifier declared - inside a function begins at the end of the ConstSpec or VarSpec - (ShortVarDecl for short variable declarations) - and ends at the end of the innermost containing block.
- -- The scope of a type identifier declared inside a function - begins at the identifier in the TypeSpec - and ends at the end of the innermost containing block.
--An identifier declared in a block may be redeclared in an inner block. -While the identifier of the inner declaration is in scope, it denotes -the entity declared by the inner declaration. -
- --The package clause is not a declaration; the package name -does not appear in any scope. Its purpose is to identify the files belonging -to the same package and to specify the default package name for import -declarations. -
- - -Label scopes
- --Labels are declared by labeled statements and are -used in the "break", -"continue", and -"goto" statements. -It is illegal to define a label that is never used. -In contrast to other identifiers, labels are not block scoped and do -not conflict with identifiers that are not labels. The scope of a label -is the body of the function in which it is declared and excludes -the body of any nested function. -
- - -Blank identifier
- --The blank identifier is represented by the underscore character
- - -_
. -It serves as an anonymous placeholder instead of a regular (non-blank) -identifier and has special meaning in declarations, -as an operand, and in assignments. -Predeclared identifiers
- --The following identifiers are implicitly declared in the -universe block: -
--Types: - bool byte complex64 complex128 error float32 float64 - int int8 int16 int32 int64 rune string - uint uint8 uint16 uint32 uint64 uintptr - -Constants: - true false iota - -Zero value: - nil - -Functions: - append cap close complex copy delete imag len - make new panic print println real recover -- - -Exported identifiers
- --An identifier may be exported to permit access to it from another package. -An identifier is exported if both: -
--
-- the first character of the identifier's name is a Unicode upper case - letter (Unicode class "Lu"); and
-- the identifier is declared in the package block - or it is a field name or - method name.
--All other identifiers are not exported. -
- - -Uniqueness of identifiers
- --Given a set of identifiers, an identifier is called unique if it is -different from every other in the set. -Two identifiers are different if they are spelled differently, or if they -appear in different packages and are not -exported. Otherwise, they are the same. -
- -Constant declarations
- --A constant declaration binds a list of identifiers (the names of -the constants) to the values of a list of constant expressions. -The number of identifiers must be equal -to the number of expressions, and the nth identifier on -the left is bound to the value of the nth expression on the -right. -
- --ConstDecl = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) . -ConstSpec = IdentifierList [ [ Type ] "=" ExpressionList ] . - -IdentifierList = identifier { "," identifier } . -ExpressionList = Expression { "," Expression } . -- --If the type is present, all constants take the type specified, and -the expressions must be assignable to that type. -If the type is omitted, the constants take the -individual types of the corresponding expressions. -If the expression values are untyped constants, -the declared constants remain untyped and the constant identifiers -denote the constant values. For instance, if the expression is a -floating-point literal, the constant identifier denotes a floating-point -constant, even if the literal's fractional part is zero. -
- --const Pi float64 = 3.14159265358979323846 -const zero = 0.0 // untyped floating-point constant -const ( - size int64 = 1024 - eof = -1 // untyped integer constant -) -const a, b, c = 3, 4, "foo" // a = 3, b = 4, c = "foo", untyped integer and string constants -const u, v float32 = 0, 3 // u = 0.0, v = 3.0 -- --Within a parenthesized
- -const
declaration list the -expression list may be omitted from any but the first ConstSpec. -Such an empty list is equivalent to the textual substitution of the -first preceding non-empty expression list and its type if any. -Omitting the list of expressions is therefore equivalent to -repeating the previous list. The number of identifiers must be equal -to the number of expressions in the previous list. -Together with theiota
constant generator -this mechanism permits light-weight declaration of sequential values: --const ( - Sunday = iota - Monday - Tuesday - Wednesday - Thursday - Friday - Partyday - numberOfDays // this constant is not exported -) -- - -Iota
- --Within a constant declaration, the predeclared identifier -
- -iota
represents successive untyped integer -constants. Its value is the index of the respective ConstSpec -in that constant declaration, starting at zero. -It can be used to construct a set of related constants: --const ( - c0 = iota // c0 == 0 - c1 = iota // c1 == 1 - c2 = iota // c2 == 2 -) - -const ( - a = 1 << iota // a == 1 (iota == 0) - b = 1 << iota // b == 2 (iota == 1) - c = 3 // c == 3 (iota == 2, unused) - d = 1 << iota // d == 8 (iota == 3) -) - -const ( - u = iota * 42 // u == 0 (untyped integer constant) - v float64 = iota * 42 // v == 42.0 (float64 constant) - w = iota * 42 // w == 84 (untyped integer constant) -) - -const x = iota // x == 0 -const y = iota // y == 0 -- --By definition, multiple uses of
- -iota
in the same ConstSpec all have the same value: --const ( - bit0, mask0 = 1 << iota, 1<<iota - 1 // bit0 == 1, mask0 == 0 (iota == 0) - bit1, mask1 // bit1 == 2, mask1 == 1 (iota == 1) - _, _ // (iota == 2, unused) - bit3, mask3 // bit3 == 8, mask3 == 7 (iota == 3) -) -- --This last example exploits the implicit repetition -of the last non-empty expression list. -
- - -Type declarations
- --A type declaration binds an identifier, the type name, to a type. -Type declarations come in two forms: alias declarations and type definitions. -
- -
-TypeDecl = "type" ( TypeSpec | "(" { TypeSpec ";" } ")" ) . -TypeSpec = AliasDecl | TypeDef . -- -Alias declarations
- --An alias declaration binds an identifier to the given type. -
- --AliasDecl = identifier "=" Type . -- --Within the scope of -the identifier, it serves as an alias for the type. -
- --type ( - nodeList = []*Node // nodeList and []*Node are identical types - Polar = polar // Polar and polar denote identical types -) -- - -Type definitions
- --A type definition creates a new, distinct type with the same -underlying type and operations as the given type, -and binds an identifier to it. -
- --TypeDef = identifier Type . -- --The new type is called a defined type. -It is different from any other type, -including the type it is created from. -
- --type ( - Point struct{ x, y float64 } // Point and struct{ x, y float64 } are different types - polar Point // polar and Point denote different types -) - -type TreeNode struct { - left, right *TreeNode - value *Comparable -} - -type Block interface { - BlockSize() int - Encrypt(src, dst []byte) - Decrypt(src, dst []byte) -} -- --A defined type may have methods associated with it. -It does not inherit any methods bound to the given type, -but the method set -of an interface type or of elements of a composite type remains unchanged: -
- --// A Mutex is a data type with two methods, Lock and Unlock. -type Mutex struct { /* Mutex fields */ } -func (m *Mutex) Lock() { /* Lock implementation */ } -func (m *Mutex) Unlock() { /* Unlock implementation */ } - -// NewMutex has the same composition as Mutex but its method set is empty. -type NewMutex Mutex - -// The method set of PtrMutex's underlying type *Mutex remains unchanged, -// but the method set of PtrMutex is empty. -type PtrMutex *Mutex - -// The method set of *PrintableMutex contains the methods -// Lock and Unlock bound to its embedded field Mutex. -type PrintableMutex struct { - Mutex -} - -// MyBlock is an interface type that has the same method set as Block. -type MyBlock Block -- --Type definitions may be used to define different boolean, numeric, -or string types and associate methods with them: -
- --type TimeZone int - -const ( - EST TimeZone = -(5 + iota) - CST - MST - PST -) - -func (tz TimeZone) String() string { - return fmt.Sprintf("GMT%+dh", tz) -} -- - -Variable declarations
- --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 ) . -- --var i int -var U, V, W float64 -var k = 0 -var x, y float32 = -1, -2 -var ( - i int - u, v, s = 2.0, 3.0, "bar" -) -var re, im = complexSqrt(-1) -var _, found = entries[name] // map lookup; only interested in "found" -- --If a list of expressions is given, the variables are initialized -with the expressions following the rules for assignments. -Otherwise, each variable is initialized to its zero value. -
- --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 implicitly -converted to its default type; -if it is an untyped boolean value, it is first implicitly converted to type
- -bool
. -The predeclared valuenil
cannot be used to initialize a variable -with no explicit type. --var d = math.Sin(0.5) // d is float64 -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 -inside a function body if the variable is -never used. -
- -Short variable declarations
- --A short variable declaration uses the syntax: -
- --ShortVarDecl = IdentifierList ":=" ExpressionList . -- --It is shorthand for a regular variable declaration -with initializer expressions but no types: -
- --"var" IdentifierList = ExpressionList . -- --i, j := 0, 10 -f := func() int { return 7 } -ch := make(chan int) -r, w, _ := os.Pipe() // os.Pipe() returns a connected pair of Files and an error, if any -_, y, _ := coord(p) // coord() returns three values; only interested in y coordinate -- --Unlike regular variable declarations, a short variable declaration may redeclare -variables provided they were originally declared earlier in the same block -(or the parameter lists if the block is the function body) with the same type, -and at least one of the non-blank variables is new. -As a consequence, redeclaration can only appear in a multi-variable short declaration. -Redeclaration does not introduce a new variable; it just assigns a new value to the original. -
- --field1, offset := nextField(str, 0) -field2, offset := nextField(str, offset) // redeclares offset -a, a := 1, 2 // illegal: double declaration of a or no new variable if a was declared elsewhere -- --Short variable declarations may appear only inside functions. -In some contexts such as the initializers for -"if", -"for", or -"switch" statements, -they can be used to declare local temporary variables. -
- -Function declarations
- --A function declaration binds an identifier, the function name, -to a function. -
- --FunctionDecl = "func" FunctionName Signature [ FunctionBody ] . -FunctionName = identifier . -FunctionBody = Block . -- --If the function's signature declares -result parameters, the function body's statement list must end in -a terminating statement. -
- --func IndexRune(s string, r rune) int { - for i, c := range s { - if c == r { - return i - } - } - // invalid: missing return statement -} -- --A function declaration may omit the body. Such a declaration provides the -signature for a function implemented outside Go, such as an assembly routine. -
- --func min(x int, y int) int { - if x < y { - return x - } - return y -} - -func flushICache(begin, end uintptr) // implemented externally -- -Method declarations
- --A method is a function with a receiver. -A method declaration binds an identifier, the method name, to a method, -and associates the method with the receiver's base type. -
- --MethodDecl = "func" Receiver MethodName Signature [ FunctionBody ] . -Receiver = Parameters . -- --The receiver is specified via an extra parameter section preceding the method -name. That parameter section must declare a single non-variadic parameter, the receiver. -Its type must be a defined type
- -T
or a -pointer to a defined typeT
.T
is called the receiver -base type. A receiver base type cannot be a pointer or interface type and -it must be defined in the same package as the method. -The method is said to be bound to its receiver base type and the method name -is visible only within selectors for typeT
-or*T
. --A non-blank receiver identifier must be -unique in the method signature. -If the receiver's value is not referenced inside the body of the method, -its identifier may be omitted in the declaration. The same applies in -general to parameters of functions and methods. -
- --For a base type, the non-blank names of methods bound to it must be unique. -If the base type is a struct type, -the non-blank method and field names must be distinct. -
- --Given defined type
- -Point
, the declarations --func (p *Point) Length() float64 { - return math.Sqrt(p.x * p.x + p.y * p.y) -} - -func (p *Point) Scale(factor float64) { - p.x *= factor - p.y *= factor -} -- --bind the methods
- -Length
andScale
, -with receiver type*Point
, -to the base typePoint
. --The type of a method is the type of a function with the receiver as first -argument. For instance, the method
- -Scale
has type --func(p *Point, factor float64) -- --However, a function declared this way is not a method. -
- - -Expressions
- --An expression specifies the computation of a value by applying -operators and functions to operands. -
- -Operands
- --Operands denote the elementary values in an expression. An operand may be a -literal, a (possibly qualified) -non-blank identifier denoting a -constant, -variable, or -function, -or a parenthesized expression. -
- --The blank identifier may appear as an -operand only on the left-hand side of an assignment. -
- --Operand = Literal | OperandName | "(" Expression ")" . -Literal = BasicLit | CompositeLit | FunctionLit . -BasicLit = int_lit | float_lit | imaginary_lit | rune_lit | string_lit . -OperandName = identifier | QualifiedIdent. -- -Qualified identifiers
- --A qualified identifier is an identifier qualified with a package name prefix. -Both the package name and the identifier must not be -blank. -
- --QualifiedIdent = PackageName "." identifier . -- --A qualified identifier accesses an identifier in a different package, which -must be imported. -The identifier must be exported and -declared in the package block of that package. -
- --math.Sin // denotes the Sin function in package math -- -Composite literals
- --Composite literals construct values for structs, arrays, slices, and maps -and create a new value each time they are evaluated. -They consist of the type of the literal followed by a brace-bound list of elements. -Each element may optionally be preceded by a corresponding key. -
- --CompositeLit = LiteralType LiteralValue . -LiteralType = StructType | ArrayType | "[" "..." "]" ElementType | - SliceType | MapType | TypeName . -LiteralValue = "{" [ ElementList [ "," ] ] "}" . -ElementList = KeyedElement { "," KeyedElement } . -KeyedElement = [ Key ":" ] Element . -Key = FieldName | Expression | LiteralValue . -FieldName = identifier . -Element = Expression | LiteralValue . -- --The LiteralType's underlying type must be a struct, array, slice, or map type -(the grammar enforces this constraint except when the type is given -as a TypeName). -The types of the elements and keys must be assignable -to the respective field, element, and key types of the literal type; -there is no additional conversion. -The key is interpreted as a field name for struct literals, -an index for array and slice literals, and a key for map literals. -For map literals, all elements must have a key. It is an error -to specify multiple elements with the same field name or -constant key value. For non-constant map keys, see the section on -evaluation order. -
- --For struct literals the following rules apply: -
--
- -- A key must be a field name declared in the struct type. -
-- An element list that does not contain any keys must - list an element for each struct field in the - order in which the fields are declared. -
-- If any element has a key, every element must have a key. -
-- An element list that contains keys does not need to - have an element for each struct field. Omitted fields - get the zero value for that field. -
-- A literal may omit the element list; such a literal evaluates - to the zero value for its type. -
-- It is an error to specify an element for a non-exported - field of a struct belonging to a different package. -
--Given the declarations -
--type Point3D struct { x, y, z float64 } -type Line struct { p, q Point3D } -- --one may write -
- --origin := Point3D{} // zero value for Point3D -line := Line{origin, Point3D{y: -4, z: 12.3}} // zero value for line.q.x -- --For array and slice literals the following rules apply: -
--
- -- Each element has an associated integer index marking - its position in the array. -
-- An element with a key uses the key as its index. The - key must be a non-negative constant - representable by - a value of type
-int
; and if it is typed - it must be of integer type. -- An element without a key uses the previous element's index plus one. - If the first element has no key, its index is zero. -
--Taking the address of a composite literal -generates a pointer to a unique variable initialized -with the literal's value. -
--var pointer *Point3D = &Point3D{y: 1000} -- --The length of an array literal is the length specified in the literal type. -If fewer elements than the length are provided in the literal, the missing -elements are set to the zero value for the array element type. -It is an error to provide elements with index values outside the index range -of the array. The notation
- -...
specifies an array length equal -to the maximum element index plus one. --buffer := [10]string{} // len(buffer) == 10 -intSet := [6]int{1, 2, 3, 5} // len(intSet) == 6 -days := [...]string{"Sat", "Sun"} // len(days) == 2 -- --A slice literal describes the entire underlying array literal. -Thus the length and capacity of a slice literal are the maximum -element index plus one. A slice literal has the form -
- --[]T{x1, x2, … xn} -- --and is shorthand for a slice operation applied to an array: -
- --tmp := [n]T{x1, x2, … xn} -tmp[0 : n] -- --Within a composite literal of array, slice, or map type
- -T
, -elements or map keys that are themselves composite literals may elide the respective -literal type if it is identical to the element or key type ofT
. -Similarly, elements or keys that are addresses of composite literals may elide -the&T
when the element or key type is*T
. --[...]Point{{1.5, -3.5}, {0, 0}} // same as [...]Point{Point{1.5, -3.5}, Point{0, 0}} -[][]int{{1, 2, 3}, {4, 5}} // same as [][]int{[]int{1, 2, 3}, []int{4, 5}} -[][]Point{{{0, 1}, {1, 2}}} // same as [][]Point{[]Point{Point{0, 1}, Point{1, 2}}} -map[string]Point{"orig": {0, 0}} // same as map[string]Point{"orig": Point{0, 0}} -map[Point]string{{0, 0}: "orig"} // same as map[Point]string{Point{0, 0}: "orig"} - -type PPoint *Point -[2]*Point{{1.5, -3.5}, {}} // same as [2]*Point{&Point{1.5, -3.5}, &Point{}} -[2]PPoint{{1.5, -3.5}, {}} // same as [2]PPoint{PPoint(&Point{1.5, -3.5}), PPoint(&Point{})} -- --A parsing ambiguity arises when a composite literal using the -TypeName form of the LiteralType appears as an operand between the -keyword and the opening brace of the block -of an "if", "for", or "switch" statement, and the composite literal -is not enclosed in parentheses, square brackets, or curly braces. -In this rare case, the opening brace of the literal is erroneously parsed -as the one introducing the block of statements. To resolve the ambiguity, -the composite literal must appear within parentheses. -
- --if x == (T{a,b,c}[i]) { … } -if (x == T{a,b,c}[i]) { … } -- --Examples of valid array, slice, and map literals: -
- --// list of prime numbers -primes := []int{2, 3, 5, 7, 9, 2147483647} - -// vowels[ch] is true if ch is a vowel -vowels := [128]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true, 'y': true} - -// the array [10]float32{-1, 0, 0, 0, -0.1, -0.1, 0, 0, 0, -1} -filter := [10]float32{-1, 4: -0.1, -0.1, 9: -1} - -// frequencies in Hz for equal-tempered scale (A4 = 440Hz) -noteFrequency := map[string]float32{ - "C0": 16.35, "D0": 18.35, "E0": 20.60, "F0": 21.83, - "G0": 24.50, "A0": 27.50, "B0": 30.87, -} -- - -Function literals
- --A function literal represents an anonymous function. -
- --FunctionLit = "func" Signature FunctionBody . -- --func(a, b int, z float64) bool { return a*b < int(z) } -- --A function literal can be assigned to a variable or invoked directly. -
- --f := func(x, y int) int { return x + y } -func(ch chan int) { ch <- ACK }(replyChan) -- --Function literals are closures: they may refer to variables -defined in a surrounding function. Those variables are then shared between -the surrounding function and the function literal, and they survive as long -as they are accessible. -
- - -Primary expressions
- --Primary expressions are the operands for unary and binary expressions. -
- --PrimaryExpr = - Operand | - Conversion | - MethodExpr | - PrimaryExpr Selector | - PrimaryExpr Index | - PrimaryExpr Slice | - PrimaryExpr TypeAssertion | - PrimaryExpr Arguments . - -Selector = "." identifier . -Index = "[" Expression "]" . -Slice = "[" [ Expression ] ":" [ Expression ] "]" | - "[" [ Expression ] ":" Expression ":" Expression "]" . -TypeAssertion = "." "(" Type ")" . -Arguments = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" . -- - --x -2 -(s + ".txt") -f(3.1415, true) -Point{1, 2} -m["foo"] -s[i : j + 1] -obj.color -f.p[i].x() -- - -Selectors
- --For a primary expression
- -x
-that is not a package name, the -selector expression --x.f -- --denotes the field or method
- -f
of the valuex
-(or sometimes*x
; see below). -The identifierf
is called the (field or method) selector; -it must not be the blank identifier. -The type of the selector expression is the type off
. -Ifx
is a package name, see the section on -qualified identifiers. --A selector
- -f
may denote a field or methodf
of -a typeT
, or it may refer -to a field or methodf
of a nested -embedded field ofT
. -The number of embedded fields traversed -to reachf
is called its depth inT
. -The depth of a field or methodf
-declared inT
is zero. -The depth of a field or methodf
declared in -an embedded fieldA
inT
is the -depth off
inA
plus one. --The following rules apply to selectors: -
- --
- -- -For a value
- -x
of typeT
or*T
-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 value
- -x
of typeI
whereI
-is an interface type,x.f
denotes the actual method with name -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 defined -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 value -nil
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 value -nil
, calling or -evaluating the methodx.f
-causes a run-time panic. --For example, given the declarations: -
- --type T0 struct { - x int -} - -func (*T0) M0() - -type T1 struct { - y int -} - -func (T1) M1() - -type T2 struct { - z int - T1 - *T0 -} - -func (*T2) M2() - -type Q *T2 - -var t T2 // with t.T0 != nil -var p *T2 // with p != nil and (*p).T0 != nil -var q Q = p -- --one may write: -
- --t.z // t.z -t.y // t.T1.y -t.x // (*t.T0).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.M0() // ((*p).T0).M0() M0 expects *T0 receiver -p.M1() // ((*p).T1).M1() M1 expects T1 receiver -p.M2() // p.M2() M2 expects *T2 receiver -t.M2() // (&t).M2() M2 expects *T2 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 = Type . -- --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 -- --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) -- - -Index expressions
- --A primary expression of the form -
- --a[x] -- --denotes the element of the array, pointer to array, slice, string or map
- -a
indexed byx
. -The valuex
is called the index or map key, respectively. -The following rules apply: --If
-a
is not a map: --
- -- the index
-x
must be of integer type or an untyped constant- a constant index must be non-negative and - representable by a value of type
-int
- a constant index that is untyped is given type
-int
- the index
-x
is in range if0 <= x < len(a)
, - otherwise it is out of range-For
-a
of array typeA
: --
- -- a constant index must be in range
-- if
-x
is out of range at run time, - a run-time panic occurs- -
a[x]
is the array element at indexx
and the type of -a[x]
is the element type ofA
-For
-a
of pointer to array type: --
- -- -
a[x]
is shorthand for(*a)[x]
-For
-a
of slice typeS
: --
- -- if
-x
is out of range at run time, - a run-time panic occurs- -
a[x]
is the slice element at indexx
and the type of -a[x]
is the element type ofS
-For
-a
of string type: --
- -- a constant index must be in range - if the string
-a
is also constant- if
-x
is out of range at run time, - a run-time panic occurs- -
a[x]
is the non-constant byte value at indexx
and the type of -a[x]
isbyte
- -
a[x]
may not be assigned to-For
-a
of map typeM
: --
- -- -
x
's type must be - assignable - to the key type ofM
- if the map contains an entry with key
-x
, -a[x]
is the map element with keyx
- and the type ofa[x]
is the element type ofM
- if the map is
-nil
or does not contain such an entry, -a[x]
is the zero value - for the element type ofM
-Otherwise
- -a[x]
is illegal. --An index expression on a map
- -a
of typemap[K]V
-used in an assignment or initialization of the special form --v, ok = a[x] -v, ok := a[x] -var v, ok = a[x] -- --yields an additional untyped boolean value. The value of
- -ok
is -true
if the keyx
is present in the map, and -false
otherwise. --Assigning to an element of a
- - -nil
map causes a -run-time panic. -Slice expressions
- --Slice expressions construct a substring or slice from a string, array, pointer -to array, or slice. There are two variants: a simple form that specifies a low -and high bound, and a full form that also specifies a bound on the capacity. -
- -Simple slice expressions
- --For a string, array, pointer to array, or slice
- -a
, the primary expression --a[low : high] -- --constructs a substring or slice. The indices
- -low
and -high
select which elements of operanda
appear -in the result. The result has indices starting at 0 and length equal to -high
-low
. -After slicing the arraya
--a := [5]int{1, 2, 3, 4, 5} -s := a[1:4] -- --the slice
- -s
has type[]int
, length 3, capacity 4, and elements --s[0] == 2 -s[1] == 3 -s[2] == 4 -- --For convenience, any of the indices may be omitted. A missing
- -low
-index defaults to zero; a missinghigh
index defaults to the length of the -sliced operand: --a[2:] // same as a[2 : len(a)] -a[:3] // same as a[0 : 3] -a[:] // same as a[0 : len(a)] -- --If
- -a
is a pointer to an array,a[low : high]
is shorthand for -(*a)[low : high]
. --For arrays or strings, the indices are in range if -
- -0
<=low
<=high
<=len(a)
, -otherwise they are out of range. -For slices, the upper index bound is the slice capacitycap(a)
rather than the length. -A constant index must be non-negative and -representable by a value of type -int
; for arrays or constant strings, constant indices must also be in range. -If both indices are constant, they must satisfylow <= high
. -If the indices are out of range at run time, a run-time panic occurs. --Except for untyped strings, if the sliced operand is a string or slice, -the result of the slice operation is a non-constant value of the same type as the operand. -For untyped string operands the result is a non-constant value of type
- -string
. -If the sliced operand is an array, it must be addressable -and the result of the slice operation is a slice with the same element type as the array. --If the sliced operand of a valid slice expression is a
- -nil
slice, the result -is anil
slice. Otherwise, if the result is a slice, it shares its underlying -array with the operand. -Full slice expressions
- --For an array, pointer to array, or slice
- -a
(but not a string), the primary expression --a[low : high : max] -- --constructs a slice of the same type, and with the same length and elements as the simple slice -expression
- -a[low : high]
. Additionally, it controls the resulting slice's capacity -by setting it tomax - low
. Only the first index may be omitted; it defaults to 0. -After slicing the arraya
--a := [5]int{1, 2, 3, 4, 5} -t := a[1:3:5] -- --the slice
- -t
has type[]int
, length 2, capacity 4, and elements --t[0] == 2 -t[1] == 3 -- --As for simple slice expressions, if
- -a
is a pointer to an array, -a[low : high : max]
is shorthand for(*a)[low : high : max]
. -If the sliced operand is an array, it must be addressable. --The indices are in range if
- -0 <= low <= high <= max <= cap(a)
, -otherwise they are out of range. -A constant index must be non-negative and -representable by a value of type -int
; for arrays, constant indices must also be in range. -If multiple indices are constant, the constants that are present must be in range relative to each -other. -If the indices are out of range at run time, a run-time panic occurs. -Type assertions
- --For an expression
- -x
of interface type -and a typeT
, the primary expression --x.(T) -- --asserts that
-x
is notnil
-and that the value stored inx
is of typeT
. -The notationx.(T)
is called a type assertion. --More precisely, if
-T
is not an interface type,x.(T)
asserts -that the dynamic type ofx
is identical -to the typeT
. -In this case,T
must implement the (interface) type ofx
; -otherwise the type assertion is invalid since it is not possible forx
-to store a value of typeT
. -IfT
is an interface type,x.(T)
asserts that the dynamic type -ofx
implements the interfaceT
. --If the type assertion holds, the value of the expression is the value -stored in
- -x
and its type isT
. If the type assertion is false, -a run-time panic occurs. -In other words, even though the dynamic type ofx
-is known only at run time, the type ofx.(T)
is -known to beT
in a correct program. --var x interface{} = 7 // x has dynamic type int and value 7 -i := x.(int) // i has type int and value 7 - -type I interface { m() } - -func f(y I) { - s := y.(string) // illegal: string does not implement I (missing method m) - r := y.(io.Reader) // r has type io.Reader and the dynamic type of y must implement both I and io.Reader - … -} -- --A type assertion used in an assignment or initialization of the special form -
- --v, ok = x.(T) -v, ok := x.(T) -var v, ok = x.(T) -var v, ok T1 = x.(T) -- --yields an additional untyped boolean value. The value of
- - -ok
istrue
-if the assertion holds. Otherwise it isfalse
and the value ofv
is -the zero value for typeT
. -No run-time panic occurs in this case. -Calls
- --Given an expression
- -f
of function type -F
, --f(a1, a2, … an) -- --calls
- -f
with argumentsa1, a2, … an
. -Except for one special case, arguments must be single-valued expressions -assignable to the parameter types of -F
and are evaluated before the function is called. -The type of the expression is the result type -ofF
. -A method invocation is similar but the method itself -is specified as a selector upon a value of the receiver type for -the method. --math.Atan2(x, y) // function call -var pt *Point -pt.Scale(3.5) // method call with receiver pt -- --In a function call, the function value and arguments are evaluated in -the usual order. -After they are evaluated, the parameters of the call are passed by value to the function -and the called function begins execution. -The return parameters of the function are passed by value -back to the calling function when the function returns. -
- --Calling a
- -nil
function value -causes a run-time panic. --As a special case, if the return values of a function or method -
- -g
are equal in number and individually -assignable to the parameters of another function or method -f
, then the callf(g(parameters_of_g))
-will invokef
after binding the return values of -g
to the parameters off
in order. The call -off
must contain no parameters other than the call ofg
, -andg
must have at least one return value. -Iff
has a final...
parameter, it is -assigned the return values ofg
that remain after -assignment of regular parameters. --func Split(s string, pos int) (string, string) { - return s[0:pos], s[pos:] -} - -func Join(s, t string) string { - return s + t -} - -if Join(Split(value, len(value)/2)) != value { - log.Panic("test fails") -} -- --A method call
- -x.m()
is valid if the method set -of (the type of)x
containsm
and the -argument list can be assigned to the parameter list ofm
. -Ifx
is addressable and&x
's method -set containsm
,x.m()
is shorthand -for(&x).m()
: --var p Point -p.Scale(3.5) -- --There is no distinct method type and there are no method literals. -
- -Passing arguments to
- -...
parameters-If
- -f
is variadic with a final -parameterp
of type...T
, then withinf
-the type ofp
is equivalent to type[]T
. -Iff
is invoked with no actual arguments forp
, -the value passed top
isnil
. -Otherwise, the value passed is a new slice -of type[]T
with a new underlying array whose successive elements -are the actual arguments, which all must be assignable -toT
. The length and capacity of the slice is therefore -the number of arguments bound top
and may differ for each -call site. --Given the function and calls -
--func Greeting(prefix string, who ...string) -Greeting("nobody") -Greeting("hello:", "Joe", "Anna", "Eileen") -- --within
- -Greeting
,who
will have the value -nil
in the first call, and -[]string{"Joe", "Anna", "Eileen"}
in the second. --If the final argument is assignable to a slice type
- -[]T
, it may be -passed unchanged as the value for a...T
parameter if the argument -is followed by...
. In this case no new slice is created. --Given the slice
- -s
and call --s := []string{"James", "Jasmine"} -Greeting("goodbye:", s...) -- --within
- - -Greeting
,who
will have the same value ass
-with the same underlying array. -Operators
- --Operators combine operands into expressions. -
- --Expression = UnaryExpr | Expression binary_op Expression . -UnaryExpr = PrimaryExpr | unary_op UnaryExpr . - -binary_op = "||" | "&&" | rel_op | add_op | mul_op . -rel_op = "==" | "!=" | "<" | "<=" | ">" | ">=" . -add_op = "+" | "-" | "|" | "^" . -mul_op = "*" | "/" | "%" | "<<" | ">>" | "&" | "&^" . - -unary_op = "+" | "-" | "!" | "^" | "*" | "&" | "<-" . -- --Comparisons are discussed elsewhere. -For other binary operators, the operand types must be identical -unless the operation involves shifts or untyped constants. -For operations involving constants only, see the section on -constant expressions. -
- --Except for shift operations, if one operand is an untyped constant -and the other operand is not, the constant is implicitly converted -to the type of the other operand. -
- --The right operand in a shift expression must have unsigned integer type -or be an untyped constant representable by a -value of type
- -uint
. -If the left operand of a non-constant shift expression is an untyped constant, -it is first implicitly converted to the type it would assume if the shift expression were -replaced by its left operand alone. --var s uint = 33 -var i = 1<<s // 1 has type int -var j int32 = 1<<s // 1 has type int32; j == 0 -var k = uint64(1<<s) // 1 has type uint64; k == 1<<33 -var m int = 1.0<<s // 1.0 has type int; m == 0 if ints are 32bits in size -var n = 1.0<<s == j // 1.0 has type int32; n == true -var o = 1<<s == 2<<s // 1 and 2 have type int; o == true if ints are 32bits in size -var p = 1<<s == 1<<33 // illegal if ints are 32bits in size: 1 has type int, but 1<<33 overflows int -var u = 1.0<<s // illegal: 1.0 has type float64, cannot shift -var u1 = 1.0<<s != 0 // illegal: 1.0 has type float64, cannot shift -var u2 = 1<<s != 1.0 // illegal: 1 has type float64, cannot shift -var v float32 = 1<<s // illegal: 1 has type float32, cannot shift -var w int64 = 1.0<<33 // 1.0<<33 is a constant shift expression -var x = a[1.0<<s] // 1.0 has type int; x == a[0] if ints are 32bits in size -var a = make([]byte, 1.0<<s) // 1.0 has type int; len(a) == 0 if ints are 32bits in size -- - -Operator precedence
--Unary operators have the highest precedence. -As the
++
and--
operators form -statements, not expressions, they fall -outside the operator hierarchy. -As a consequence, statement*p++
is the same as(*p)++
. --There are five precedence levels for binary operators. -Multiplication operators bind strongest, followed by addition -operators, comparison operators,
- -&&
(logical AND), -and finally||
(logical OR): --Precedence Operator - 5 * / % << >> & &^ - 4 + - | ^ - 3 == != < <= > >= - 2 && - 1 || -- --Binary operators of the same precedence associate from left to right. -For instance,
- -x / y * z
is the same as(x / y) * z
. --+x -23 + 3*x[i] -x <= f() -^a >> b -f() || g() -x == y+1 && <-chanPtr > 0 -- - -Arithmetic operators
--Arithmetic operators apply to numeric values and yield a result of the same -type as the first operand. The four standard arithmetic operators (
- -+
, --
,*
,/
) apply to integer, -floating-point, and complex types;+
also applies to strings. -The bitwise logical and shift operators apply to integers only. --+ sum integers, floats, complex values, strings -- difference integers, floats, complex values -* product integers, floats, complex values -/ quotient integers, floats, complex values -% remainder integers - -& bitwise AND integers -| bitwise OR integers -^ bitwise XOR integers -&^ bit clear (AND NOT) integers - -<< left shift integer << unsigned integer ->> right shift integer >> unsigned integer -- - -Integer operators
- --For two integer values
- -x
andy
, the integer quotient -q = x / y
and remainderr = x % y
satisfy the following -relationships: --x = q*y + r and |r| < |y| -- --with
- -x / y
truncated towards zero -("truncated division"). -- x y x / y x % y - 5 3 1 2 --5 3 -1 -2 - 5 -3 -1 2 --5 -3 1 -2 -- --The one exception to this rule is that if the dividend
- -x
is -the most negative value for the int type ofx
, the quotient -q = x / -1
is equal tox
(andr = 0
) -due to two's-complement integer overflow: -- x, q -int8 -128 -int16 -32768 -int32 -2147483648 -int64 -9223372036854775808 -- --If the divisor is a constant, it must not be zero. -If the divisor is zero at run time, a run-time panic occurs. -If the dividend is non-negative and the divisor is a constant power of 2, -the division may be replaced by a right shift, and computing the remainder may -be replaced by a bitwise AND operation: -
- -- x x / 4 x % 4 x >> 2 x & 3 - 11 2 3 2 3 --11 -2 -3 -3 1 -- --The shift operators shift the left operand by the shift count specified by the -right operand. They implement arithmetic shifts if the left operand is a signed -integer and logical shifts if it is an unsigned integer. -There is no upper limit on the shift count. Shifts behave -as if the left operand is shifted
- -n
times by 1 for a shift -count ofn
. -As a result,x << 1
is the same asx*2
-andx >> 1
is the same as -x/2
but truncated towards negative infinity. --For integer operands, the unary operators -
- -+
,-
, and^
are defined as -follows: --+x is 0 + x --x negation is 0 - x -^x bitwise complement is m ^ x with m = "all bits set to 1" for unsigned x - and m = -1 for signed x -- - -Integer overflow
- --For unsigned integer values, the operations
-+
, --
,*
, and<<
are -computed modulo 2n, where n is the bit width of -the unsigned integer's type. -Loosely speaking, these unsigned integer operations -discard high bits upon overflow, and programs may rely on "wrap around". --For signed integers, the operations
- - -+
, --
,*
,/
, and<<
may legally -overflow and the resulting value exists and is deterministically defined -by the signed integer representation, the operation, and its operands. -Overflow does not cause a run-time panic. -A compiler may not optimize code under the assumption that overflow does -not occur. For instance, it may not assume thatx < x + 1
is always true. -Floating-point operators
- --For floating-point and complex numbers, -
- -+x
is the same asx
, -while-x
is the negation ofx
. -The result of a floating-point or complex division by zero is not specified beyond the -IEEE-754 standard; whether a run-time panic -occurs is implementation-specific. --An implementation may combine multiple floating-point operations into a single -fused operation, possibly across statements, and produce a result that differs -from the value obtained by executing and rounding the instructions individually. -An explicit floating-point type conversion rounds to -the precision of the target type, preventing fusion that would discard that rounding. -
- --For instance, some architectures provide a "fused multiply and add" (FMA) instruction -that computes
- -x*y + z
without rounding the intermediate resultx*y
. -These examples show when a Go implementation can use that instruction: --// FMA allowed for computing r, because x*y is not explicitly rounded: -r = x*y + z -r = z; r += x*y -t = x*y; r = t + z -*p = x*y; r = *p + z -r = x*y + float64(z) - -// FMA disallowed for computing r, because it would omit rounding of x*y: -r = float64(x*y) + z -r = z; r += float64(x*y) -t = float64(x*y); r = t + z -- -String concatenation
- --Strings can be concatenated using the
- -+
operator -or the+=
assignment operator: --s := "hi" + string(c) -s += " and good bye" -- --String addition creates a new string by concatenating the operands. -
- - -Comparison operators
- --Comparison operators compare two operands and yield an untyped boolean value. -
- --== equal -!= not equal -< less -<= less or equal -> greater ->= greater or equal -- --In any comparison, the first operand -must be assignable -to the type of the second operand, or vice versa. -
--The equality operators
- -==
and!=
apply -to operands that are comparable. -The ordering operators<
,<=
,>
, and>=
-apply to operands that are ordered. -These terms and the result of the comparisons are defined as follows: --
- -- - Boolean values are comparable. - Two boolean values are equal if they are either both -
- -true
or bothfalse
. -- - Integer values are comparable and ordered, in the usual way. -
- -- - Floating-point values are comparable and ordered, - as defined by the IEEE-754 standard. -
- -- - Complex values are comparable. - Two complex values
- -u
andv
are - equal if bothreal(u) == real(v)
and -imag(u) == imag(v)
. -- - String values are comparable and ordered, lexically byte-wise. -
- -- - Pointer values are comparable. - Two pointer values are equal if they point to the same variable or if both have value
- -nil
. - Pointers to distinct zero-size variables may or may not be equal. -- - Channel values are comparable. - Two channel values are equal if they were created by the same call to -
- -make
- or if both have valuenil
. -- - Interface values are comparable. - Two interface values are equal if they have identical dynamic types - and equal dynamic values or if both have value
- -nil
. -- - A value
- -x
of non-interface typeX
and - a valuet
of interface typeT
are comparable when values - of typeX
are comparable and -X
implementsT
. - They are equal ift
's dynamic type is identical toX
- andt
's dynamic value is equal tox
. -- - Struct values are comparable if all their fields are comparable. - Two struct values are equal if their corresponding - non-blank fields are equal. -
- -- - Array values are comparable if values of the array element type are comparable. - Two array values are equal if their corresponding elements are equal. -
--A comparison of two interface values with identical dynamic types -causes a run-time panic if values -of that type are not comparable. This behavior applies not only to direct interface -value comparisons but also when comparing arrays of interface values -or structs with interface-valued fields. -
- --Slice, map, and function values are not comparable. -However, as a special case, a slice, map, or function value may -be compared to the predeclared identifier
- -nil
. -Comparison of pointer, channel, and interface values tonil
-is also allowed and follows from the general rules above. --const c = 3 < 4 // c is the untyped boolean constant true - -type MyBool bool -var x, y int -var ( - // The result of a comparison is an untyped boolean. - // The usual assignment rules apply. - b3 = x == y // b3 has type bool - b4 bool = x == y // b4 has type bool - b5 MyBool = x == y // b5 has type MyBool -) -- -Logical operators
- --Logical operators apply to boolean values -and yield a result of the same type as the operands. -The right operand is evaluated conditionally. -
- --&& conditional AND p && q is "if p then q else false" -|| conditional OR p || q is "if p then true else q" -! NOT !p is "not p" -- - -Address operators
- --For an operand
- -x
of typeT
, the address operation -&x
generates a pointer of type*T
tox
. -The operand must be addressable, -that is, either a variable, pointer indirection, or slice indexing -operation; or a field selector of an addressable struct operand; -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 ofx
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 variable of typeT
pointed -to byx
. -Ifx
isnil
, an attempt to evaluate*x
-will cause a run-time panic. --&x -&a[f(2)] -&Point{2, 3} -*p -*pf(x) - -var x *int = nil -*x // causes a run-time panic -&*x // causes a run-time panic -- - -Receive operator
- --For an operand
- -ch
of channel type, -the value of the receive operation<-ch
is the value received -from the channelch
. The channel direction must permit receive operations, -and the type of the receive operation is the element type of the channel. -The expression blocks until a value is available. -Receiving from anil
channel blocks forever. -A receive operation on a closed channel can always proceed -immediately, yielding the element type's zero value -after any previously sent values have been received. --v1 := <-ch -v2 = <-ch -f(<-ch) -<-strobe // wait until clock pulse and discard received value -- --A receive expression used in an assignment or initialization of the special form -
- --x, ok = <-ch -x, ok := <-ch -var x, ok = <-ch -var x, ok T = <-ch -- --yields an additional untyped boolean result reporting whether the -communication succeeded. The value of
- - -ok
istrue
-if the value received was delivered by a successful send operation to the -channel, orfalse
if it is a zero value generated because the -channel is closed and empty. -Conversions
- --A conversion changes the type of an expression -to the type specified by the conversion. -A conversion may appear literally in the source, or it may be implied -by the context in which an expression appears. -
- --An explicit conversion is an expression of the form
- -T(x)
-whereT
is a type andx
is an expression -that can be converted to typeT
. --Conversion = Type "(" Expression [ "," ] ")" . -- --If the type starts with the operator
- -*
or<-
, -or if the type starts with the keywordfunc
-and has no result list, it must be parenthesized when -necessary to avoid ambiguity: --*Point(p) // same as *(Point(p)) -(*Point)(p) // p is converted to *Point -<-chan int(c) // same as <-(chan int(c)) -(<-chan int)(c) // c is converted to <-chan int -func()(x) // function signature func() x -(func())(x) // x is converted to func() -(func() int)(x) // x is converted to func() int -func() int(x) // x is converted to func() int (unambiguous) -- --A constant value
- -x
can be converted to -typeT
ifx
is representable -by a value ofT
. -As a special case, an integer constantx
can be explicitly converted to a -string type using the -same rule -as for non-constantx
. --Converting a constant yields a typed constant as result. -
- --uint(iota) // iota value of type uint -float32(2.718281828) // 2.718281828 of type float32 -complex128(1) // 1.0 + 0.0i of type complex128 -float32(0.49999999) // 0.5 of type float32 -float64(-1e-1000) // 0.0 of type float64 -string('x') // "x" of type string -string(0x266c) // "♬" of type string -MyString("foo" + "bar") // "foobar" of type MyString -string([]byte{'a'}) // not a constant: []byte{'a'} is not a constant -(*int)(nil) // not a constant: nil is not a constant, *int is not a boolean, numeric, or string type -int(1.2) // illegal: 1.2 cannot be represented as an int -string(65.0) // illegal: 65.0 is not an integer constant -- --A non-constant value
- -x
can be converted to typeT
-in any of these cases: --
- -- -
-x
is assignable - toT
. -- - ignoring struct tags (see below), -
-x
's type andT
have identical - underlying types. -- - ignoring struct tags (see below), -
-x
's type andT
are pointer types - that are not defined types, - and their pointer base types have identical underlying types. -- -
-x
's type andT
are both integer or floating - point types. -- -
-x
's type andT
are both complex types. -- -
-x
is an integer or a slice of bytes or runes - andT
is a string type. -- -
-x
is a string andT
is a slice of bytes or runes. --Struct tags are ignored when comparing struct types -for identity for the purpose of conversion: -
- --type Person struct { - Name string - Address *struct { - Street string - City string - } -} - -var data *struct { - Name string `json:"name"` - Address *struct { - Street string `json:"street"` - City string `json:"city"` - } `json:"address"` -} - -var person = (*Person)(data) // ignoring tags, the underlying types are identical -- --Specific rules apply to (non-constant) conversions between numeric types or -to and from a string type. -These conversions may change the representation of
- -x
-and incur a run-time cost. -All other conversions only change the type but not the representation -ofx
. --There is no linguistic mechanism to convert between pointers and integers. -The package
- -unsafe
-implements this functionality under -restricted circumstances. -Conversions between numeric types
- --For the conversion of non-constant numeric values, the following rules apply: -
- --
- -- -When converting between integer types, if the value is a signed integer, it is -sign extended to implicit infinite precision; otherwise it is zero extended. -It is then truncated to fit in the result type's size. -For example, if
-v := uint16(0x10F0)
, thenuint32(int8(v)) == 0xFFFFFFF0
. -The conversion always yields a valid value; there is no indication of overflow. -- -When converting a floating-point number to an integer, the fraction is discarded -(truncation towards zero). -
-- -When converting an integer or floating-point number to a floating-point type, -or a complex number to another complex type, the result value is rounded -to the precision specified by the destination type. -For instance, the value of a variable
-x
of typefloat32
-may be stored using additional precision beyond that of an IEEE-754 32-bit number, -but float32(x) represents the result of roundingx
's value to -32-bit precision. Similarly,x + 0.1
may use more than 32 bits -of precision, butfloat32(x + 0.1)
does not. --In all non-constant conversions involving floating-point or complex values, -if the result type cannot represent the value the conversion -succeeds but the result value is implementation-dependent. -
- -Conversions to and from a string type
- --
- - -- -Converting a signed or unsigned integer value to a string type yields a -string containing the UTF-8 representation of the integer. Values outside -the range of valid Unicode code points are converted to
- -"\uFFFD"
. - --string('a') // "a" -string(-1) // "\ufffd" == "\xef\xbf\xbd" -string(0xf8) // "\u00f8" == "ø" == "\xc3\xb8" -type MyString string -MyString(0x65e5) // "\u65e5" == "日" == "\xe6\x97\xa5" --- -Converting a slice of bytes to a string type yields -a string whose successive bytes are the elements of the slice. - -
- --string([]byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hellø" -string([]byte{}) // "" -string([]byte(nil)) // "" - -type MyBytes []byte -string(MyBytes{'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hellø" --- -Converting a slice of runes to a string type yields -a string that is the concatenation of the individual rune values -converted to strings. - -
- --string([]rune{0x767d, 0x9d6c, 0x7fd4}) // "\u767d\u9d6c\u7fd4" == "白鵬翔" -string([]rune{}) // "" -string([]rune(nil)) // "" - -type MyRunes []rune -string(MyRunes{0x767d, 0x9d6c, 0x7fd4}) // "\u767d\u9d6c\u7fd4" == "白鵬翔" --- -Converting a value of a string type to a slice of bytes type -yields a slice whose successive elements are the bytes of the string. - -
- --[]byte("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'} -[]byte("") // []byte{} - -MyBytes("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'} --- -Converting a value of a string type to a slice of runes type -yields a slice containing the individual Unicode code points of the string. - -
--[]rune(MyString("白鵬翔")) // []rune{0x767d, 0x9d6c, 0x7fd4} -[]rune("") // []rune{} - -MyRunes("白鵬翔") // []rune{0x767d, 0x9d6c, 0x7fd4} --Constant expressions
- --Constant expressions may contain only constant -operands and are evaluated at compile time. -
- --Untyped boolean, numeric, and string constants may be used as operands -wherever it is legal to use an operand of boolean, numeric, or string type, -respectively. -
- --A constant comparison always yields -an untyped boolean constant. If the left operand of a constant -shift expression is an untyped constant, the -result is an integer constant; otherwise it is a constant of the same -type as the left operand, which must be of -integer type. -
- --Any other operation on untyped constants results in an untyped constant of the -same kind; that is, a boolean, integer, floating-point, complex, or string -constant. -If the untyped operands of a binary operation (other than a shift) are of -different kinds, the result is of the operand's kind that appears later in this -list: integer, rune, floating-point, complex. -For example, an untyped integer constant divided by an -untyped complex constant yields an untyped complex constant. -
- --const a = 2 + 3.0 // a == 5.0 (untyped floating-point constant) -const b = 15 / 4 // b == 3 (untyped integer constant) -const c = 15 / 4.0 // c == 3.75 (untyped floating-point constant) -const Θ float64 = 3/2 // Θ == 1.0 (type float64, 3/2 is integer division) -const Π float64 = 3/2. // Π == 1.5 (type float64, 3/2. is float division) -const d = 1 << 3.0 // d == 8 (untyped integer constant) -const e = 1.0 << 3 // e == 8 (untyped integer constant) -const f = int32(1) << 33 // illegal (constant 8589934592 overflows int32) -const g = float64(2) >> 1 // illegal (float64(2) is a typed floating-point constant) -const h = "foo" > "bar" // h == true (untyped boolean constant) -const j = true // j == true (untyped boolean constant) -const k = 'w' + 1 // k == 'x' (untyped rune constant) -const l = "hi" // l == "hi" (untyped string constant) -const m = string(k) // m == "x" (type string) -const Σ = 1 - 0.707i // (untyped complex constant) -const Δ = Σ + 2.0e-4 // (untyped complex constant) -const Φ = iota*1i - 1/1i // (untyped complex constant) -- --Applying the built-in function
- -complex
to untyped -integer, rune, or floating-point constants yields -an untyped complex constant. --const ic = complex(0, c) // ic == 3.75i (untyped complex constant) -const iΘ = complex(0, Θ) // iΘ == 1i (type complex128) -- --Constant expressions are always evaluated exactly; intermediate values and the -constants themselves may require precision significantly larger than supported -by any predeclared type in the language. The following are legal declarations: -
- --const Huge = 1 << 100 // Huge == 1267650600228229401496703205376 (untyped integer constant) -const Four int8 = Huge >> 98 // Four == 4 (type int8) -- --The divisor of a constant division or remainder operation must not be zero: -
- --3.14 / 0.0 // illegal: division by zero -- --The values of typed constants must always be accurately -representable by values -of the constant type. The following constant expressions are illegal: -
- --uint(-1) // -1 cannot be represented as a uint -int(3.14) // 3.14 cannot be represented as an int -int64(Huge) // 1267650600228229401496703205376 cannot be represented as an int64 -Four * 300 // operand 300 cannot be represented as an int8 (type of Four) -Four * 100 // product 400 cannot be represented as an int8 (type of Four) -- --The mask used by the unary bitwise complement operator
- -^
matches -the rule for non-constants: the mask is all 1s for unsigned constants -and -1 for signed and untyped constants. --^1 // untyped integer constant, equal to -2 -uint8(^1) // illegal: same as uint8(-2), -2 cannot be represented as a uint8 -^uint8(1) // typed uint8 constant, same as 0xFF ^ uint8(1) = uint8(0xFE) -int8(^1) // same as int8(-2) -^int8(1) // same as -1 ^ int8(1) = -2 -- --Implementation restriction: A compiler may use rounding while -computing untyped floating-point or complex constant expressions; see -the implementation restriction in the section -on constants. This rounding may cause a -floating-point constant expression to be invalid in an integer -context, even if it would be integral when calculated using infinite -precision, and vice versa. -
- - -Order of evaluation
- --At package level, initialization dependencies -determine the evaluation order of individual initialization expressions in -variable declarations. -Otherwise, when evaluating the operands of an -expression, assignment, or -return statement, -all function calls, method calls, and -communication operations are evaluated in lexical left-to-right -order. -
- --For example, in the (function-local) assignment -
--y[f()], ok = g(h(), i()+x[j()], <-c), k() ---the function calls and communication happen in the order -
- -f()
,h()
,i()
,j()
, -<-c
,g()
, andk()
. -However, the order of those events compared to the evaluation -and indexing ofx
and the evaluation -ofy
is not specified. --a := 1 -f := func() int { a++; return a } -x := []int{a, f()} // x may be [1, 2] or [2, 2]: evaluation order between a and f() is not specified -m := map[int]int{a: 1, a: 2} // m may be {2: 1} or {2: 2}: evaluation order between the two map assignments is not specified -n := map[int]int{a: f()} // n may be {2: 3} or {3: 3}: evaluation order between the key and the value is not specified -- --At package level, initialization dependencies override the left-to-right rule -for individual initialization expressions, but not for operands within each -expression: -
- --var a, b, c = f() + v(), g(), sqr(u()) + v() - -func f() int { return c } -func g() int { return a } -func sqr(x int) int { return x*x } - -// functions u and v are independent of all other variables and functions -- --The function calls happen in the order -
- -u()
,sqr()
,v()
, -f()
,v()
, andg()
. --Floating-point operations within a single expression are evaluated according to -the associativity of the operators. Explicit parentheses affect the evaluation -by overriding the default associativity. -In the expression
- -x + (y + z)
the additiony + z
-is performed before addingx
. -Statements
- --Statements control execution. -
- --Statement = - Declaration | LabeledStmt | SimpleStmt | - GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt | - FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt | - DeferStmt . - -SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | Assignment | ShortVarDecl . -- -Terminating statements
- --A terminating statement prevents execution of all statements that lexically -appear after it in the same block. The following statements -are terminating: -
- --
- -- - A "return" or - "goto" statement. - -
- --
- - A call to the built-in function -
- -panic
. - --
- - A block in which the statement list ends in a terminating statement. - -
- --
- - An "if" statement in which: -
- --
-- the "else" branch is present, and
-- both branches are terminating statements.
-- - A "for" statement in which: -
- --
-- there are no "break" statements referring to the "for" statement, and
-- the loop condition is absent.
-- - A "switch" statement in which: -
- --
-- there are no "break" statements referring to the "switch" statement,
-- there is a default case, and
-- the statement lists in each case, including the default, end in a terminating - statement, or a possibly labeled "fallthrough" - statement.
-- - A "select" statement in which: -
- --
-- there are no "break" statements referring to the "select" statement, and
-- the statement lists in each case, including the default if present, - end in a terminating statement.
-- - A labeled statement labeling - a terminating statement. -
--All other statements are not terminating. -
- --A statement list ends in a terminating statement if the list -is not empty and its final non-empty statement is terminating. -
- - -Empty statements
- --The empty statement does nothing. -
- --EmptyStmt = . -- - -Labeled statements
- --A labeled statement may be the target of a
- -goto
, -break
orcontinue
statement. --LabeledStmt = Label ":" Statement . -Label = identifier . -- --Error: log.Panic("error encountered") -- - -Expression statements
- --With the exception of specific built-in functions, -function and method calls and -receive operations -can appear in statement context. Such statements may be parenthesized. -
- --ExpressionStmt = Expression . -- --The following built-in functions are not permitted in statement context: -
- --append cap complex imag len make new real -unsafe.Alignof unsafe.Offsetof unsafe.Sizeof -- --h(x+y) -f.Close() -<-ch -(<-ch) -len("foo") // illegal if len is the built-in function -- - -Send statements
- --A send statement sends a value on a channel. -The channel expression must be of channel type, -the channel direction must permit send operations, -and the type of the value to be sent must be assignable -to the channel's element type. -
- --SendStmt = Channel "<-" Expression . -Channel = Expression . -- --Both the channel and the value expression are evaluated before communication -begins. Communication blocks until the send can proceed. -A send on an unbuffered channel can proceed if a receiver is ready. -A send on a buffered channel can proceed if there is room in the buffer. -A send on a closed channel proceeds by causing a run-time panic. -A send on a
- -nil
channel blocks forever. --ch <- 3 // send value 3 to channel ch -- - -IncDec statements
- --The "++" and "--" statements increment or decrement their operands -by the untyped constant
- -1
. -As with an assignment, the operand must be addressable -or a map index expression. --IncDecStmt = Expression ( "++" | "--" ) . -- --The following assignment statements are semantically -equivalent: -
- --IncDec statement Assignment -x++ x += 1 -x-- x -= 1 -- - -Assignments
- --Assignment = ExpressionList assign_op ExpressionList . - -assign_op = [ add_op | mul_op ] "=" . -- --Each left-hand side operand must be addressable, -a map index expression, or (for
- -=
assignments only) the -blank identifier. -Operands may be parenthesized. --x = 1 -*p = f() -a[i] = 23 -(k) = <-ch // same as: k = <-ch -- --An assignment operation
- -x
op=
-y
where op is a binary arithmetic operator -is equivalent tox
=
x
op -(y)
but evaluatesx
-only once. The op=
construct is a single token. -In assignment operations, both the left- and right-hand expression lists -must contain exactly one single-valued expression, and the left-hand -expression must not be the blank identifier. --a[i] <<= 2 -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 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, if -
- -f
is a function returning two values, --x, y = f() -- --assigns the first value to
- -x
and the second toy
. -In the second form, the number of operands on the left must equal the number -of expressions on the right, each of which must be single-valued, and the -nth expression on the right is assigned to the nth -operand on the left: --one, two, three = '一', '二', '三' -- --The blank identifier provides a way to -ignore right-hand side values in an assignment: -
- --_ = x // evaluate x but ignore it -x, _ = f() // evaluate f() but ignore second result value -- --The assignment proceeds in two phases. -First, the operands of index expressions -and pointer indirections -(including implicit pointer indirections in selectors) -on the left and the expressions on the right are all -evaluated in the usual order. -Second, the assignments are carried out in left-to-right order. -
- --a, b = b, a // exchange a and b - -x := []int{1, 2, 3} -i := 0 -i, x[i] = 1, 2 // set i = 1, x[0] = 2 - -i = 0 -x[i], i = 2, 1 // set x[0] = 2, i = 1 - -x[0], x[0] = 1, 2 // set x[0] = 1, then x[0] = 2 (so x[0] == 2 at end) - -x[1], x[3] = 4, 5 // set x[1] = 4, then panic setting x[3] = 5. - -type Point struct { x, y int } -var p *Point -x[2], p.x = 6, 7 // set x[2] = 6, then panic setting p.x = 7 - -i = 2 -x = []int{3, 5, 7} -for i, x[i] = range x { // set i, x[2] = 0, x[0] - break -} -// after this loop, i == 0 and x == []int{3, 5, 3} -- --In assignments, each value must be assignable -to the type of the operand to which it is assigned, with the following special cases: -
- --
- -- - 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 implicitly converted to its - default type. -
- -- - If an untyped boolean value is assigned to a variable of interface type or - the blank identifier, it is first implicitly converted to type
-bool
. -If statements
- --"If" statements specify the conditional execution of two branches -according to the value of a boolean expression. If the expression -evaluates to true, the "if" branch is executed, otherwise, if -present, the "else" branch is executed. -
- --IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" ( IfStmt | Block ) ] . -- --if x > max { - x = max -} -- --The expression may be preceded by a simple statement, which -executes before the expression is evaluated. -
- --if x := f(); x < y { - return x -} else if x > z { - return z -} else { - return y -} -- - -Switch statements
- --"Switch" statements provide multi-way execution. -An expression or type specifier is compared to the "cases" -inside the "switch" to determine which branch -to execute. -
- --SwitchStmt = ExprSwitchStmt | TypeSwitchStmt . -- --There are two forms: expression switches and type switches. -In an expression switch, the cases contain expressions that are compared -against the value of the switch expression. -In a type switch, the cases contain types that are compared against the -type of a specially annotated switch expression. -The switch expression is evaluated exactly once in a switch statement. -
- -Expression switches
- --In an expression switch, -the switch expression is evaluated and -the case expressions, which need not be constants, -are evaluated left-to-right and top-to-bottom; the first one that equals the -switch expression -triggers execution of the statements of the associated case; -the other cases are skipped. -If no case matches and there is a "default" case, -its statements are executed. -There can be at most one default case and it may appear anywhere in the -"switch" statement. -A missing switch expression is equivalent to the boolean value -
- -true
. --ExprSwitchStmt = "switch" [ SimpleStmt ";" ] [ Expression ] "{" { ExprCaseClause } "}" . -ExprCaseClause = ExprSwitchCase ":" StatementList . -ExprSwitchCase = "case" ExpressionList | "default" . -- --If the switch expression evaluates to an untyped constant, it is first implicitly -converted to its default type; -if it is an untyped boolean value, it is first implicitly converted to type
- -bool
. -The predeclared untyped valuenil
cannot be used as a switch expression. --If a case expression is untyped, it is first implicitly converted -to the type of the switch expression. -For each (possibly converted) case expression
- -x
and the valuet
-of the switch expression,x == t
must be a valid comparison. --In other words, the switch expression is treated as if it were used to declare and -initialize a temporary variable
- -t
without explicit type; it is that -value oft
against which each case expressionx
is tested -for equality. --In a case or default clause, the last non-empty statement -may be a (possibly labeled) -"fallthrough" statement to -indicate that control should flow from the end of this clause to -the first statement of the next clause. -Otherwise control flows to the end of the "switch" statement. -A "fallthrough" statement may appear as the last statement of all -but the last clause of an expression switch. -
- --The switch expression may be preceded by a simple statement, which -executes before the expression is evaluated. -
- --switch tag { -default: s3() -case 0, 1, 2, 3: s1() -case 4, 5, 6, 7: s2() -} - -switch x := f(); { // missing switch expression means "true" -case x < 0: return -x -default: return x -} - -switch { -case x < y: f1() -case x < z: f2() -case x == 4: f3() -} -- --Implementation restriction: A compiler may disallow multiple case -expressions evaluating to the same constant. -For instance, the current compilers disallow duplicate integer, -floating point, or string constants in case expressions. -
- -Type switches
- --A type switch compares types rather than values. It is otherwise similar -to an expression switch. It is marked by a special switch expression that -has the form of a type assertion -using the reserved word
- -type
rather than an actual type: --switch x.(type) { -// cases -} -- --Cases then match actual types
- -T
against the dynamic type of the -expressionx
. As with type assertions,x
must be of -interface type, and each non-interface type -T
listed in a case must implement the type ofx
. -The types listed in the cases of a type switch must all be -different. --TypeSwitchStmt = "switch" [ SimpleStmt ";" ] TypeSwitchGuard "{" { TypeCaseClause } "}" . -TypeSwitchGuard = [ identifier ":=" ] PrimaryExpr "." "(" "type" ")" . -TypeCaseClause = TypeSwitchCase ":" StatementList . -TypeSwitchCase = "case" TypeList | "default" . -TypeList = Type { "," Type } . -- --The TypeSwitchGuard may include a -short variable declaration. -When that form is used, the variable is declared at the end of the -TypeSwitchCase in the implicit block of each clause. -In clauses with a case listing exactly one type, the variable -has that type; otherwise, the variable has the type of the expression -in the TypeSwitchGuard. -
- --Instead of a type, a case may use the predeclared identifier -
- -nil
; -that case is selected when the expression in the TypeSwitchGuard -is anil
interface value. -There may be at most onenil
case. --Given an expression
- -x
of typeinterface{}
, -the following type switch: --switch i := x.(type) { -case nil: - printString("x is nil") // type of i is type of x (interface{}) -case int: - printInt(i) // type of i is int -case float64: - printFloat64(i) // type of i is float64 -case func(int) float64: - printFunction(i) // type of i is func(int) float64 -case bool, string: - printString("type is bool or string") // type of i is type of x (interface{}) -default: - printString("don't know the type") // type of i is type of x (interface{}) -} -- --could be rewritten: -
- --v := x // x is evaluated exactly once -if v == nil { - i := v // type of i is type of x (interface{}) - printString("x is nil") -} else if i, isInt := v.(int); isInt { - printInt(i) // type of i is int -} else if i, isFloat64 := v.(float64); isFloat64 { - printFloat64(i) // type of i is float64 -} else if i, isFunc := v.(func(int) float64); isFunc { - printFunction(i) // type of i is func(int) float64 -} else { - _, isBool := v.(bool) - _, isString := v.(string) - if isBool || isString { - i := v // type of i is type of x (interface{}) - printString("type is bool or string") - } else { - i := v // type of i is type of x (interface{}) - printString("don't know the type") - } -} -- --The type switch guard may be preceded by a simple statement, which -executes before the guard is evaluated. -
- --The "fallthrough" statement is not permitted in a type switch. -
- -For statements
- --A "for" statement specifies repeated execution of a block. There are three forms: -The iteration may be controlled by a single condition, a "for" clause, or a "range" clause. -
- --ForStmt = "for" [ Condition | ForClause | RangeClause ] Block . -Condition = Expression . -- -For statements with single condition
- --In its simplest form, a "for" statement specifies the repeated execution of -a block as long as a boolean condition evaluates to true. -The condition is evaluated before each iteration. -If the condition is absent, it is equivalent to the boolean value -
- -true
. --for a < b { - a *= 2 -} -- -For statements with
- -for
clause-A "for" statement with a ForClause is also controlled by its condition, but -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. -
- --ForClause = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] . -InitStmt = SimpleStmt . -PostStmt = SimpleStmt . -- --for i := 0; i < 10; i++ { - f(i) -} -- --If non-empty, the init statement is executed once before evaluating the -condition for the first iteration; -the post statement is executed after each execution of the block (and -only if the block was executed). -Any element of the ForClause may be empty but the -semicolons are -required unless there is only a condition. -If the condition is absent, it is equivalent to the boolean value -
- -true
. --for cond { S() } is the same as for ; cond ; { S() } -for { S() } is the same as for true { S() } -- -For statements with
- -range
clause-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 if present and then executes the block. -
- --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, 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, 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
- -x
is evaluated once before beginning the loop, -with one exception: if at most one iteration variable is present and -len(x)
is constant, -the range expression is not evaluated. --Function calls on the left are evaluated once per iteration. -For each iteration, iteration values are produced as follows -if the respective iteration variables are 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 -map m map[K]V key k K m[k] V -channel c chan E, <-chan E element e E -- --
- -- -For an array, pointer to array, or slice value
- -a
, the index iteration -values are produced in increasing order, starting at element index 0. -If at most one iteration variable is present, the range loop produces -iteration values from 0 up tolen(a)-1
and does not index into the array -or slice itself. For anil
slice, the number of iterations is 0. -- -For a string value, the "range" clause iterates over the Unicode code points -in the string starting at byte index 0. On successive iterations, the index value will be the -index of the first byte of successive UTF-8-encoded code points in the string, -and the second value, of type
- -rune
, will be the value of -the corresponding code point. If the iteration encounters an invalid -UTF-8 sequence, the second value will be0xFFFD
, -the Unicode replacement character, and the next iteration will advance -a single byte in the string. -- -The iteration order over maps is not specified -and is not guaranteed to be the same from one iteration to the next. -If a map entry that has not yet been reached is removed during iteration, -the corresponding iteration value will not be produced. If a map entry is -created during iteration, that entry may be produced during the iteration or -may be skipped. The choice may vary for each entry created and from one -iteration to the next. -If the map is
- -nil
, the number of iterations is 0. -- -For channels, the iteration values produced are the successive values sent on -the channel until the channel is closed. If the channel -is
-nil
, the range expression blocks forever. --The iteration values are assigned to the respective -iteration variables as in an assignment statement. -
- --The iteration variables may be declared by the "range" clause using a form of -short variable declaration -(
- -:=
). -In this case their types are set to the types of the respective iteration values -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. --var testdata *struct { - a *[7]int -} -for i, _ := range testdata.a { - // testdata.a is never evaluated; len(testdata.a) is constant - // i ranges from 0 to 6 - f(i) -} - -var a [10]string -for i, s := range a { - // type of i is int - // type of s is string - // s == a[i] - g(i, s) -} - -var key string -var val interface {} // element type of m is assignable to val -m := map[string]int{"mon":0, "tue":1, "wed":2, "thu":3, "fri":4, "sat":5, "sun":6} -for key, val = range m { - h(key, val) -} -// key == last map key encountered in iteration -// val == map[key] - -var ch chan Work = producer() -for w := range ch { - doWork(w) -} - -// empty a channel -for range ch {} -- - -Go statements
- --A "go" statement starts the execution of a function call -as an independent concurrent thread of control, or goroutine, -within the same address space. -
- --GoStmt = "go" Expression . -- --The expression must be a function or method call; it cannot be parenthesized. -Calls of built-in functions are restricted as for -expression statements. -
- --The function value and parameters are -evaluated as usual -in the calling goroutine, but -unlike with a regular call, program execution does not wait -for the invoked function to complete. -Instead, the function begins executing independently -in a new goroutine. -When the function terminates, its goroutine also terminates. -If the function has any return values, they are discarded when the -function completes. -
- --go Server() -go func(ch chan<- bool) { for { sleep(10); ch <- true }} (c) -- - -Select statements
- --A "select" statement chooses which of a set of possible -send or -receive -operations will proceed. -It looks similar to a -"switch" statement but with the -cases all referring to communication operations. -
- --SelectStmt = "select" "{" { CommClause } "}" . -CommClause = CommCase ":" StatementList . -CommCase = "case" ( SendStmt | RecvStmt ) | "default" . -RecvStmt = [ ExpressionList "=" | IdentifierList ":=" ] RecvExpr . -RecvExpr = Expression . -- --A case with a RecvStmt may assign the result of a RecvExpr to one or -two variables, which may be declared using a -short variable declaration. -The RecvExpr must be a (possibly parenthesized) receive operation. -There can be at most one default case and it may appear anywhere -in the list of cases. -
- --Execution of a "select" statement proceeds in several steps: -
- --
- -- -For all the cases in the statement, the channel operands of receive operations -and the channel and right-hand-side expressions of send statements are -evaluated exactly once, in source order, upon entering the "select" statement. -The result is a set of channels to receive from or send to, -and the corresponding values to send. -Any side effects in that evaluation will occur irrespective of which (if any) -communication operation is selected to proceed. -Expressions on the left-hand side of a RecvStmt with a short variable declaration -or assignment are not yet evaluated. -
- -- -If one or more of the communications can proceed, -a single one that can proceed is chosen via a uniform pseudo-random selection. -Otherwise, if there is a default case, that case is chosen. -If there is no default case, the "select" statement blocks until -at least one of the communications can proceed. -
- -- -Unless the selected case is the default case, the respective communication -operation is executed. -
- -- -If the selected case is a RecvStmt with a short variable declaration or -an assignment, the left-hand side expressions are evaluated and the -received value (or values) are assigned. -
- -- -The statement list of the selected case is executed. -
--Since communication on
- -nil
channels can never proceed, -a select with onlynil
channels and no default case blocks forever. --var a []int -var c, c1, c2, c3, c4 chan int -var i1, i2 int -select { -case i1 = <-c1: - print("received ", i1, " from c1\n") -case c2 <- i2: - print("sent ", i2, " to c2\n") -case i3, ok := (<-c3): // same as: i3, ok := <-c3 - if ok { - print("received ", i3, " from c3\n") - } else { - print("c3 is closed\n") - } -case a[f()] = <-c4: - // same as: - // case t := <-c4 - // a[f()] = t -default: - print("no communication\n") -} - -for { // send random sequence of bits to c - select { - case c <- 0: // note: no statement, no fallthrough, no folding of cases - case c <- 1: - } -} - -select {} // block forever -- - -Return statements
- --A "return" statement in a function
- -F
terminates the execution -ofF
, and optionally provides one or more result values. -Any functions deferred byF
-are executed beforeF
returns to its caller. --ReturnStmt = "return" [ ExpressionList ] . -- --In a function without a result type, a "return" statement must not -specify any result values. -
--func noResult() { - return -} -- --There are three ways to return values from a function with a result -type: -
- --
- -- The return value or values may be explicitly listed - in the "return" statement. Each expression must be single-valued - and assignable - to the corresponding element of the function's result type. -
--func simpleF() int { - return 2 -} - -func complexF1() (re float64, im float64) { - return -7.0, -4.0 -} --- The expression list in the "return" statement may be a single - call to a multi-valued function. The effect is as if each value - returned from that function were assigned to a temporary - variable with the type of the respective value, followed by a - "return" statement listing these variables, at which point the - rules of the previous case apply. -
--func complexF2() (re float64, im float64) { - return complexF1() -} --- The expression list may be empty if the function's result - type specifies names for its result parameters. - The result parameters act as ordinary local variables - and the function may assign values to them as necessary. - The "return" statement returns the values of these variables. -
--func complexF3() (re float64, im float64) { - re = 7.0 - im = 4.0 - return -} - -func (devnull) Write(p []byte) (n int, _ error) { - n = len(p) - return -} ---Regardless of how they are declared, all the result values are initialized to -the zero values for their type upon entry to the -function. A "return" statement that specifies results sets the result parameters before -any deferred functions are executed. -
- --Implementation restriction: A compiler may disallow an empty expression list -in a "return" statement if a different entity (constant, type, or variable) -with the same name as a result parameter is in -scope at the place of the return. -
- --func f(n int) (res int, err error) { - if _, err := f(n-1); err != nil { - return // invalid return statement: err is shadowed - } - return -} -- -Break statements
- --A "break" statement terminates execution of the innermost -"for", -"switch", or -"select" statement -within the same function. -
- --BreakStmt = "break" [ Label ] . -- --If there is a label, it must be that of an enclosing -"for", "switch", or "select" statement, -and that is the one whose execution terminates. -
- --OuterLoop: - for i = 0; i < n; i++ { - for j = 0; j < m; j++ { - switch a[i][j] { - case nil: - state = Error - break OuterLoop - case item: - state = Found - break OuterLoop - } - } - } -- -Continue statements
- --A "continue" statement begins the next iteration of the -innermost "for" loop at its post statement. -The "for" loop must be within the same function. -
- --ContinueStmt = "continue" [ Label ] . -- --If there is a label, it must be that of an enclosing -"for" statement, and that is the one whose execution -advances. -
- --RowLoop: - for y, row := range rows { - for x, data := range row { - if data == endOfRow { - continue RowLoop - } - row[x] = data + bias(x, y) - } - } -- -Goto statements
- --A "goto" statement transfers control to the statement with the corresponding label -within the same function. -
- --GotoStmt = "goto" Label . -- --goto Error -- --Executing the "goto" statement must not cause any variables to come into -scope that were not already in scope at the point of the goto. -For instance, this example: -
- -- goto L // BAD - v := 3 -L: -- --is erroneous because the jump to label
- -L
skips -the creation ofv
. --A "goto" statement outside a block cannot jump to a label inside that block. -For instance, this example: -
- --if n%2 == 1 { - goto L1 -} -for n > 0 { - f() - n-- -L1: - f() - n-- -} -- --is erroneous because the label
- -L1
is inside -the "for" statement's block but thegoto
is not. -Fallthrough statements
- --A "fallthrough" statement transfers control to the first statement of the -next case clause in an expression "switch" statement. -It may be used only as the final non-empty statement in such a clause. -
- --FallthroughStmt = "fallthrough" . -- - -Defer statements
- --A "defer" statement invokes a function whose execution is deferred -to the moment the surrounding function returns, either because the -surrounding function executed a return statement, -reached the end of its function body, -or because the corresponding goroutine is panicking. -
- --DeferStmt = "defer" Expression . -- --The expression must be a function or method call; it cannot be parenthesized. -Calls of built-in functions are restricted as for -expression statements. -
- --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 is not invoked. -Instead, deferred functions are invoked immediately before -the surrounding function returns, in the reverse order -they were deferred. That is, if the surrounding function -returns through an explicit return statement, -deferred functions are executed after any result parameters are set -by that return statement but before the function returns to its caller. -If a deferred function value evaluates -to
- -nil
, execution panics -when the function is invoked, not when the "defer" statement is executed. --For instance, if the deferred function is -a function literal and the surrounding -function has named result parameters that -are in scope within the literal, the deferred function may access and modify -the result parameters before they are returned. -If the deferred function has any return values, they are discarded when -the function completes. -(See also the section on handling panics.) -
- --lock(l) -defer unlock(l) // unlocking happens before surrounding function returns - -// prints 3 2 1 0 before surrounding function returns -for i := 0; i <= 3; i++ { - defer fmt.Print(i) -} - -// f returns 42 -func f() (result int) { - defer func() { - // result is accessed after it was set to 6 by the return statement - result *= 7 - }() - return 6 -} -- -Built-in functions
- --Built-in functions are -predeclared. -They are called like any other function but some of them -accept a type instead of an expression as the first argument. -
- --The built-in functions do not have standard Go types, -so they can only appear in call expressions; -they cannot be used as function values. -
- -Close
- --For a channel
- - -c
, the built-in functionclose(c)
-records that no more values will be sent on the channel. -It is an error ifc
is a receive-only channel. -Sending to or closing a closed channel causes a run-time panic. -Closing the nil channel also causes a run-time panic. -After callingclose
, and after any previously -sent values have been received, receive operations will return -the zero value for the channel's type without blocking. -The multi-valued receive operation -returns a received value along with an indication of whether the channel is closed. -Length and capacity
- --The built-in functions
- -len
andcap
take arguments -of various types and return a result of typeint
. -The implementation guarantees that the result always fits into anint
. --Call Argument type Result - -len(s) string type string length in bytes - [n]T, *[n]T array length (== n) - []T slice length - map[K]T map length (number of defined keys) - chan T number of elements queued in channel buffer - -cap(s) [n]T, *[n]T array length (== n) - []T slice capacity - chan T channel buffer capacity -- --The capacity of a slice is the number of elements for which there is -space allocated in the underlying array. -At any time the following relationship holds: -
- --0 <= len(s) <= cap(s) -- --The length of a
- -nil
slice, map or channel is 0. -The capacity of anil
slice or channel is 0. --The expression
- -len(s)
is constant if -s
is a string constant. The expressionslen(s)
and -cap(s)
are constants if the type ofs
is an array -or pointer to an array and the expressions
does not contain -channel receives or (non-constant) -function calls; in this cases
is not evaluated. -Otherwise, invocations oflen
andcap
are not -constant ands
is evaluated. --const ( - c1 = imag(2i) // imag(2i) = 2.0 is a constant - c2 = len([10]float64{2}) // [10]float64{2} contains no function calls - c3 = len([10]float64{c1}) // [10]float64{c1} contains no function calls - c4 = len([10]float64{imag(2i)}) // imag(2i) is a constant and no function call is issued - c5 = len([10]float64{imag(z)}) // invalid: imag(z) is a (non-constant) function call -) -var z complex128 -- -Allocation
- --The built-in function
- -new
takes a typeT
, -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. --new(T) -- --For instance -
- --type S struct { a int; b float64 } -new(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 location. -Making slices, maps and channels
- --The built-in function
- -make
takes a typeT
, -which must be a slice, map or channel type, -optionally followed by a type-specific list of expressions. -It returns a value of typeT
(not*T
). -The memory is initialized as described in the section on -initial values. --Call Type T Result - -make(T, n) slice slice of type T with length n and capacity n -make(T, n, m) slice slice of type T with length n and capacity m - -make(T) map map of type T -make(T, n) map map of type T with initial space for approximately n elements - -make(T) channel unbuffered channel of type T -make(T, n) channel buffered channel of type T, buffer size n -- - --Each of the size arguments
- -n
andm
must be of integer type -or an untyped constant. -A constant size argument must be non-negative and representable -by a value of typeint
; if it is an untyped constant it is given typeint
. -If bothn
andm
are provided and are constant, then -n
must be no larger thanm
. -Ifn
is negative or larger thanm
at run time, -a run-time panic occurs. --s := make([]int, 10, 100) // slice with len(s) == 10, cap(s) == 100 -s := make([]int, 1e3) // slice with len(s) == cap(s) == 1000 -s := make([]int, 1<<63) // illegal: len(s) is not representable by a value of type int -s := make([]int, 10, 0) // illegal: len(s) > cap(s) -c := make(chan int, 10) // channel with a buffer size of 10 -m := make(map[string]int, 100) // map with initial space for approximately 100 elements -- --Calling
- - -make
with a map type and size hintn
will -create a map with initial space to holdn
map elements. -The precise behavior is implementation-dependent. -Appending to and copying slices
- --The built-in functions
- -append
andcopy
assist in -common slice operations. -For both functions, the result is independent of whether the memory referenced -by the arguments overlaps. --The variadic function
- -append
-appends zero or more valuesx
-tos
of typeS
, which must be a slice type, and -returns the resulting slice, also of typeS
. -The valuesx
are passed to a parameter of type...T
-whereT
is the element type of -S
and the respective -parameter passing rules apply. -As a special case,append
also accepts a first argument -assignable to type[]byte
with a second argument of -string type followed by...
. This form appends the -bytes of the string. --append(s S, x ...T) S // T is the element type of S -- --If the capacity of
- -s
is not large enough to fit the additional -values,append
allocates a new, sufficiently large underlying -array that fits both the existing slice elements and the additional values. -Otherwise,append
re-uses the underlying array. --s0 := []int{0, 0} -s1 := append(s0, 2) // append a single element s1 == []int{0, 0, 2} -s2 := append(s1, 3, 5, 7) // append multiple elements s2 == []int{0, 0, 2, 3, 5, 7} -s3 := append(s2, s0...) // append a slice s3 == []int{0, 0, 2, 3, 5, 7, 0, 0} -s4 := append(s3[3:6], s3[2:]...) // append overlapping slice s4 == []int{3, 5, 7, 2, 3, 5, 7, 0, 0} - -var t []interface{} -t = append(t, 42, 3.1415, "foo") // t == []interface{}{42, 3.1415, "foo"} - -var b []byte -b = append(b, "bar"...) // append string contents b == []byte{'b', 'a', 'r' } -- --The function
- -copy
copies slice elements from -a sourcesrc
to a destinationdst
and returns the -number of elements copied. -Both arguments must have identical element typeT
and must be -assignable to a slice of type[]T
. -The number of elements copied is the minimum of -len(src)
andlen(dst)
. -As a special case,copy
also accepts a destination argument assignable -to type[]byte
with a source argument of a string type. -This form copies the bytes from the string into the byte slice. --copy(dst, src []T) int -copy(dst []byte, src string) int -- --Examples: -
- --var a = [...]int{0, 1, 2, 3, 4, 5, 6, 7} -var s = make([]int, 6) -var b = make([]byte, 5) -n1 := copy(s, a[0:]) // n1 == 6, s == []int{0, 1, 2, 3, 4, 5} -n2 := copy(s, s[2:]) // n2 == 4, s == []int{2, 3, 4, 5, 4, 5} -n3 := copy(b, "Hello, World!") // n3 == 5, b == []byte("Hello") -- - -Deletion of map elements
- --The built-in function
- -delete
removes the element with key -k
from a mapm
. The -type ofk
must be assignable -to the key type ofm
. --delete(m, k) // remove element m[k] from map m -- --If the map
- - -m
isnil
or the elementm[k]
-does not exist,delete
is a no-op. -Manipulating complex numbers
- --Three functions assemble and disassemble complex numbers. -The built-in function
- -complex
constructs a complex -value from a floating-point real and imaginary part, while -real
andimag
-extract the real and imaginary parts of a complex value. --complex(realPart, imaginaryPart floatT) complexT -real(complexT) floatT -imag(complexT) floatT -- --The type of the arguments and return value correspond. -For
- -complex
, the two arguments must be of the same -floating-point type and the return type is the complex type -with the corresponding floating-point constituents: -complex64
forfloat32
arguments, and -complex128
forfloat64
arguments. -If one of the arguments evaluates to an untyped constant, it is first implicitly -converted to the type of the other argument. -If both arguments evaluate to untyped constants, they must be non-complex -numbers or their imaginary parts must be zero, and the return value of -the function is an untyped complex constant. --For
- -real
andimag
, the argument must be -of complex type, and the return type is the corresponding floating-point -type:float32
for acomplex64
argument, and -float64
for acomplex128
argument. -If the argument evaluates to an untyped constant, it must be a number, -and the return value of the function is an untyped floating-point constant. --The
- -real
andimag
functions together form the inverse of -complex
, so for a valuez
of a complex typeZ
, -z == Z(complex(real(z), imag(z)))
. --If the operands of these functions are all constants, the return -value is a constant. -
- --var a = complex(2, -2) // complex128 -const b = complex(1.0, -1.4) // untyped complex constant 1 - 1.4i -x := float32(math.Cos(math.Pi/2)) // float32 -var c64 = complex(5, -x) // complex64 -var s uint = complex(1, 0) // untyped complex constant 1 + 0i can be converted to uint -_ = complex(1, 2<<s) // illegal: 2 assumes floating-point type, cannot shift -var rl = real(c64) // float32 -var im = imag(a) // float64 -const c = imag(b) // untyped constant -1.4 -_ = imag(3 << s) // illegal: 3 assumes complex type, cannot shift -- -Handling panics
- -Two built-in functions,
- -panic
andrecover
, -assist in reporting and handling run-time panics -and program-defined error conditions. --func panic(interface{}) -func recover() interface{} -- --While executing a function
- -F
, -an explicit call topanic
or a run-time panic -terminates the execution ofF
. -Any functions deferred byF
-are then executed as usual. -Next, any deferred functions run byF's
caller are run, -and so on up to any deferred by the top-level function in the executing goroutine. -At that point, the program is terminated and the error -condition is reported, including the value of the argument topanic
. -This termination sequence is called panicking. --panic(42) -panic("unreachable") -panic(Error("cannot parse")) -- --The
- -recover
function allows a program to manage behavior -of a panicking goroutine. -Suppose a functionG
defers a functionD
that calls -recover
and a panic occurs in a function on the same goroutine in whichG
-is executing. -When the running of deferred functions reachesD
, -the return value ofD
's call torecover
will be the value passed to the call ofpanic
. -IfD
returns normally, without starting a new -panic
, the panicking sequence stops. In that case, -the state of functions called betweenG
and the call topanic
-is discarded, and normal execution resumes. -Any functions deferred byG
beforeD
are then run andG
's -execution terminates by returning to its caller. --The return value of
-recover
isnil
if any of the following conditions holds: --
- -- -
-panic
's argument wasnil
; -- -the goroutine is not panicking; -
-- -
-recover
was not called directly by a deferred function. --The
- -protect
function in the example below invokes -the function argumentg
and protects callers from -run-time panics raised byg
. --func protect(g func()) { - defer func() { - log.Println("done") // Println executes normally even if there is a panic - if x := recover(); x != nil { - log.Printf("run time panic: %v", x) - } - }() - log.Println("start") - g() -} -- - -Bootstrapping
- --Current implementations provide several built-in functions useful during -bootstrapping. These functions are documented for completeness but are not -guaranteed to stay in the language. They do not return a result. -
- --Function Behavior - -print prints all arguments; formatting of arguments is implementation-specific -println like print but prints spaces between arguments and a newline at the end -- --Implementation restriction:
- -println
need not -accept arbitrary argument types, but printing of boolean, numeric, and string -types must be supported. -Packages
- --Go programs are constructed by linking together packages. -A package in turn is constructed from one or more source files -that together declare constants, types, variables and functions -belonging to the package and which are accessible in all files -of the same package. Those elements may be -exported and used in another package. -
- -Source file organization
- --Each source file consists of a package clause defining the package -to which it belongs, followed by a possibly empty set of import -declarations that declare packages whose contents it wishes to use, -followed by a possibly empty set of declarations of functions, -types, variables, and constants. -
- --SourceFile = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } . -- -Package clause
- --A package clause begins each source file and defines the package -to which the file belongs. -
- --PackageClause = "package" PackageName . -PackageName = identifier . -- --The PackageName must not be the blank identifier. -
- --package math -- --A set of files sharing the same PackageName form the implementation of a package. -An implementation may require that all source files for a package inhabit the same directory. -
- -Import declarations
- --An import declaration states that the source file containing the declaration -depends on functionality of the imported package -(§Program initialization and execution) -and enables access to exported identifiers -of that package. -The import names an identifier (PackageName) to be used for access and an ImportPath -that specifies the package to be imported. -
- --ImportDecl = "import" ( ImportSpec | "(" { ImportSpec ";" } ")" ) . -ImportSpec = [ "." | PackageName ] ImportPath . -ImportPath = string_lit . -- --The PackageName is used in qualified identifiers -to access exported identifiers of the package within the importing source file. -It is declared in the file block. -If the PackageName is omitted, it defaults to the identifier specified in the -package clause of the imported package. -If an explicit period (
- -.
) appears instead of a name, all the -package's exported identifiers declared in that package's -package block will be declared in the importing source -file's file block and must be accessed without a qualifier. --The interpretation of the ImportPath is implementation-dependent but -it is typically a substring of the full file name of the compiled -package and may be relative to a repository of installed packages. -
- --Implementation restriction: A compiler may restrict ImportPaths to -non-empty strings using only characters belonging to -Unicode's -L, M, N, P, and S general categories (the Graphic characters without -spaces) and may also exclude the characters -
- -!"#$%&'()*,:;<=>?[\]^`{|}
-and the Unicode replacement character U+FFFD. --Assume we have compiled a package containing the package clause -
- -package math
, which exports functionSin
, and -installed the compiled package in the file identified by -"lib/math"
. -This table illustrates howSin
is accessed in files -that import the package after the -various types of import declaration. --Import declaration Local name of Sin - -import "lib/math" math.Sin -import m "lib/math" m.Sin -import . "lib/math" Sin -- --An import declaration declares a dependency relation between -the importing and imported package. -It is illegal for a package to import itself, directly or indirectly, -or to directly import a package without -referring to any of its exported identifiers. To import a package solely for -its side-effects (initialization), use the blank -identifier as explicit package name: -
- --import _ "lib/math" -- - -An example package
- --Here is a complete Go package that implements a concurrent prime sieve. -
- --package main - -import "fmt" - -// Send the sequence 2, 3, 4, … to channel 'ch'. -func generate(ch chan<- int) { - for i := 2; ; i++ { - ch <- i // Send 'i' to channel 'ch'. - } -} - -// Copy the values from channel 'src' to channel 'dst', -// removing those divisible by 'prime'. -func filter(src <-chan int, dst chan<- int, prime int) { - for i := range src { // Loop over values received from 'src'. - if i%prime != 0 { - dst <- i // Send 'i' to channel 'dst'. - } - } -} - -// The prime sieve: Daisy-chain filter processes together. -func sieve() { - ch := make(chan int) // Create a new channel. - go generate(ch) // Start generate() as a subprocess. - for { - prime := <-ch - fmt.Print(prime, "\n") - ch1 := make(chan int) - go filter(ch, ch1, prime) - ch = ch1 - } -} - -func main() { - sieve() -} -- -Program initialization and execution
- -The zero value
--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 -ofmake
, -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 numeric types,""
-for strings, andnil
for pointers, functions, interfaces, slices, channels, and maps. -This initialization is done recursively, so for instance each element of an -array of structs will have its fields zeroed if no value is specified. --These two simple declarations are equivalent: -
- --var i int -var i int = 0 -- --After -
- --type T struct { i int; f float64; next *T } -t := new(T) -- --the following holds: -
- --t.i == 0 -t.f == 0.0 -t.next == nil -- --The same would also be true after -
- --var t T -- -Package initialization
- --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, if a variable
- -x
's -initialization expression refers to a function whose body refers to -variabley
thenx
depends ony
. -Specifically: --
- -- -A reference to a variable or function is an identifier denoting that -variable or function. -
- -- -A reference to a method
- -m
is a -method value or -method expression of the form -t.m
, where the (static) type oft
is -not an interface type, and the methodm
is in the -method set oft
. -It is immaterial whether the resulting function value -t.m
is invoked. -- -A variable, function, or method
-x
depends on a variable -y
ifx
's initialization expression or body -(for functions and methods) contains a reference toy
-or to a function or method that depends ony
. --Dependency analysis is performed per package; only references referring -to variables, functions, and methods declared in the current package -are considered. -
- --For example, given the declarations -
- --var ( - a = c + b - b = f() - c = f() - d = 3 -) - -func f() int { - d++ - return d -} -- --the initialization order is
- -d
,b
,c
,a
. --Variables may also be initialized using functions named
- -init
-declared in the package block, with no arguments and no result parameters. --func init() { … } -- --Multiple such functions may be defined per package, even within a single -source file. In the package block, the
- -init
identifier can -be used only to declareinit
functions, yet the identifier -itself is not declared. Thus -init
functions cannot be referred to from anywhere -in a program. --A package with no imports is initialized by assigning initial values -to all its package-level variables followed by calling all
- -init
-functions in the order they appear in the source, possibly in multiple files, -as presented to the compiler. -If a package has imports, the imported packages are initialized -before initializing the package itself. If multiple packages import -a package, the imported package will be initialized only once. -The importing of packages, by construction, guarantees that there -can be no cyclic initialization dependencies. --Package initialization—variable initialization and the invocation of -
- -init
functions—happens in a single goroutine, -sequentially, one package at a time. -Aninit
function may launch other goroutines, which can run -concurrently with the initialization code. However, initialization -always sequences -theinit
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. -
- - -Program execution
--A complete program is created by linking a single, unimported package -called the main package with all the packages it imports, transitively. -The main package must -have package name
- -main
and -declare a functionmain
that takes no -arguments and returns no value. --func main() { … } -- --Program execution begins by initializing the main package and then -invoking the function
- -main
. -When that function invocation returns, the program exits. -It does not wait for other (non-main
) goroutines to complete. -Errors
- --The predeclared type
- -error
is defined as --type error interface { - Error() string -} -- --It is the conventional interface for representing an error condition, -with the nil value representing no error. -For instance, a function to read data from a file might be defined: -
- --func Read(f *File, b []byte) (n int, err error) -- -Run-time panics
- --Execution errors such as attempting to index an array out -of bounds trigger a run-time panic equivalent to a call of -the built-in function
- -panic
-with a value of the implementation-defined interface typeruntime.Error
. -That type satisfies the predeclared interface type -error
. -The exact error values that -represent distinct run-time error conditions are unspecified. --package runtime - -type Error interface { - error - // and perhaps other methods -} -- -System considerations
- -Package
- -unsafe
-The built-in package
- -unsafe
, known to the compiler -and accessible through the import path"unsafe"
, -provides facilities for low-level programming including operations -that violate the type system. A package usingunsafe
-must be vetted manually for type safety and may not be portable. -The package provides the following interface: --package unsafe - -type ArbitraryType int // shorthand for an arbitrary Go type; it is not a real type -type Pointer *ArbitraryType - -func Alignof(variable ArbitraryType) uintptr -func Offsetof(selector ArbitraryType) uintptr -func Sizeof(variable ArbitraryType) uintptr -- --A
- -Pointer
is a pointer type but aPointer
-value may not be dereferenced. -Any pointer or value of underlying typeuintptr
can be converted to -a type of underlying typePointer
and vice versa. -The effect of converting betweenPointer
anduintptr
is implementation-defined. --var f float64 -bits = *(*uint64)(unsafe.Pointer(&f)) - -type ptr unsafe.Pointer -bits = *(*uint64)(ptr(&f)) - -var p ptr = nil -- --The functions
-Alignof
andSizeof
take an expressionx
-of any type and return the alignment or size, respectively, of a hypothetical variablev
-as ifv
was declared viavar v = x
. --The function
- -Offsetof
takes a (possibly parenthesized) selector -s.f
, denoting a fieldf
of the struct denoted bys
-or*s
, and returns the field offset in bytes relative to the struct's address. -Iff
is an embedded field, it must be reachable -without pointer indirections through fields of the struct. -For a structs
with fieldf
: --uintptr(unsafe.Pointer(&s)) + unsafe.Offsetof(s.f) == uintptr(unsafe.Pointer(&s.f)) -- --Computer architectures may require memory addresses to be aligned; -that is, for addresses of a variable to be a multiple of a factor, -the variable's type's alignment. The function
- -Alignof
-takes an expression denoting a variable of any type and returns the -alignment of the (type of the) variable in bytes. For a variable -x
: --uintptr(unsafe.Pointer(&x)) % unsafe.Alignof(x) == 0 -- --Calls to
- -Alignof
,Offsetof
, and -Sizeof
are compile-time constant expressions of typeuintptr
. -Size and alignment guarantees
- --For the numeric types, the following sizes are guaranteed: -
- --type size in bytes - -byte, uint8, int8 1 -uint16, int16 2 -uint32, int32, float32 4 -uint64, int64, float64, complex64 8 -complex128 16 -- --The following minimal alignment properties are guaranteed: -
--
- -- For a variable
- -x
of any type:unsafe.Alignof(x)
is at least 1. -- For a variable
- -x
of struct type:unsafe.Alignof(x)
is the largest of - all the valuesunsafe.Alignof(x.f)
for each fieldf
ofx
, but at least 1. -- For a variable
-x
of array type:unsafe.Alignof(x)
is the same as - the alignment of a variable of the array's element type. --A struct or array type has size zero if it contains no fields (or elements, respectively) that have a size greater than zero. Two distinct zero-size variables may have the same address in memory. -
diff --git a/content/doc/gopher/README b/content/doc/gopher/README deleted file mode 100644 index d4ca8a1c..00000000 --- a/content/doc/gopher/README +++ /dev/null @@ -1,3 +0,0 @@ -The Go gopher was designed by Renee French. (http://reneefrench.blogspot.com/) -The design is licensed under the Creative Commons 3.0 Attributions license. -Read this article for more details: https://blog.golang.org/gopher diff --git a/content/doc/gopher/appenginegopher.jpg b/content/doc/gopher/appenginegopher.jpg deleted file mode 100644 index 0a64306666a6f9506c551760718cd3af71cd0e69..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 135882 zcmeFa2V7Ij@;H7F6%_?LiUmXwk={EIX@Vk1FJh#GfRs=I2ne}WR0O1pAW;#KE?sJD zfOP3qP^3sldP2&7gAL2|UhaF}|L48;uFvG#epW5TgPAAR1<9#e5usOlfv}jh~@8@EK &sm$NDe7a^@&g1gnN63XO8IMA@^- zYYDQdnV4DGQJ*0}egOeVeql*|F;)R_NdZAg5m5-Dy-V|{UJ3<*?k@XM{)(`>v|r-1 zmqA_BYb6csXBt;7YzNKmZ|$Jjzpx$4Xugy|!@KNj*;}uEDh@gVegQ{5{Zbb4k_rQ< zlwoM?e4F6%Y7h-&1Y($fg3SM*=A^Vim!P$)R;^mSYVGRPYd6rZq2I8DaqU{hE!#G2 z+OlcWwhe3Nug^c99)1jI*3r|iV_3JIfnoh-1_p-B)PQ00rz{)(P63ps(1ukI0=i2} z!v-zeKtsEMhVlk9dky6!4Gd7Zf@b~#1XC|speV~%tfX7DdJR2Lhwl? Kv}=Vx;s)B~do~KJkUL?riOu1>;L6Pb_fik<-M2;anW>Pl UkTt8v@vXumESJiX4^uqN|{*^Xgr<_6(F6;+jeftrCT zbX ;!{@^JiHWB|aZ!!lr z9iN+ulMBjk%=BFgC{YlJJ_HSI)Ve-$xk2zY#?m=II_G6>;{K*<8oO?ltTcCCNr6Tb zwFW7WuB3=Dix6*FVnsT0kkfJ783fG-a_X>!b5m*rNhZ`Ca~xNbd`Dxj!i>Oj!mL7| zIh&4UuTc-X$eStUfdp@&{{`tbe=T) ?{V4cipTw);iiBu8XUSPi!TL77%QcZ ~DGH@|Yb?#4m;SmH`Va#%Ndbkd;F zD}s^SNVr9TlC%n&L@F7qRy;VeS3^$a=z~BNP9Q*44CVEdcAyG7=e|&NEkgPEx^dZ; zWuw*ASDw5x(Y4D=a#*(&KFL{}@@8_}E{2_BP)2L|6iZ^6aY&GL+wuK-S6L_LP@u~C zrk0_kT*JAF?*eY@B;zEUYu#Dge_j%esxZlZ>k)Ut^bw<8=}tnPluN z%x*{}tlS!1SJd2B?w#sCV65U7H%joT@VcXj9ZO)(A{~EaD?t}Kb-cj9Ql#75tj|JQ zjsmSJw#aOzK+{E>oC9gO6zK2^Ol)|)g9COhtJ8=PpCyyPmE>tnNOD!JEJo_R@C-9+ zGcqi1?mBv__YWB{38wo vM0m;TSjE zt4b8NGaDaCZ7?%Q?VPb7P@uQ9T4sz%lPCLzo(*hkQD=!zYiRZw=;(2CbaS4Hx(82+ zm{O+Q^Fp^FC`4 Q)rA#f$Sg&nBOpVU8;)cClD_ z^o}ej+Co1t3KzdA0_#(|gII?%s`8%{ktp<&!j1KwKxR^)=vOa`s$w)>6`>lObWhP1 z?7lvDQOKSlvtinYc1OfTSdD?MVqRJ*=DsJkp)fu!7gyK#ysEtaen%!EagZd$uiNA- zEqc*YrxAW+%D%r-SBY2Xj%~} @0l7>~c?TAgnwZQu|wbBB6?F&<#D|oR-fy5NcAJvz&goMe*mD+t+m&e{b z8wTUd7$I?y4)RVm=k7e2c&@^IJk`dw{^V=IkV$AxY@VvBYM{!#SW3-&pAaGV*?Pia zdyuX42`?X(chIqCW;W)+Do B>pJzkGIUFfu3ecn+p)4$ zsQ+Gs)g-q^RAaBijhL|aveibze4Wa@`yS$s5}sl7ODIrO_${x9IF{2Nc8S$n7aa5H zXyqx$*{Y|GJ2-lj5kq=d63t@;54b#~#f&cq-{mBjZ862&);-5HEp>39wHG%OEHm_? z-&iy@y&-j~tBwMlnczy9I&*`c0wome-CZnGz_GHTJ-6S(#@cbnR=;A3#lW?04yo;d zsn#I`CFL|&oHX3gP?%bCWeoAu?6iTc_-w~SW>U7)vUcojMfpap=qdO>%&?Q>Xd`kb zInT1a`lNUEmIs6z(ac$y!8#tW7e;EwNPKZ0y!`PaN&5n|)Z-@o?lhzp%X;$U`0km? z(;#%n`evN0%&M`*)M`&*Uyn}+IHeE@>XTg5W`~&G_DZj7>I&*7hgVEX@iBD1HqV>% zN+zE3A1f~}%&sifQ{ zj7&&~Yi%A|A4UR6_AwwGc`f^7QVxxB;XPXt<*D+Fw~YenPw9@UYDU-h_ivw)dN9SO z)Yy~ZpVs_#=exOvEF+6vsrK?SGxZecZnFNVZSVD0yxnzoOuaWH!YX#UM5h8{JODE( zZLw`M4lK#3&cRNHR3LL>^FCmn4NVTFU}9BOJyAP`?=TF_`6T6W-5*Yu@^2zIpRbCQ zeAD6U;%vj*UzpuZfuusF`O@DEc;3g#>)d+sWP9JklBCyOkFz>e |m7Gj47(zzK&)Ft(!G)Z6~=rj{+&5xJ1AW#&MQ@fSn{iMuV{_gQPkjKJ+SjSEqUM zv`D8Vx0%>`M7yUEmlyGLIcnOIv6eUGuC~2opHaWgAN;KZr;p*hQVjZ;IXc49*yFfN zlQ%cZ2B*CqKei*3)Dc|a0|l;3F?~ovGg=s~%bwUg;8i;m3imQbOYO$0J&{eBz}A!2 z^n0bC2m9yLbt*l$2X^UHWW7JJKTErK=w(q%Ra;@MH7_PEH7cpe*i_YJqsqQu3Ph>> zG*UW|^oE*Q^f?DS<;~pfl=eOzDI6{g5fv@&HX~H0x9PYUB_rc0Pz_ gsY3Wmu3DC{vV+(bo9X zbx8`;Fm&BdE1u1#ef2{^tZR!9b8}82qEoT6)?QEsUPFOYiwZciYut o@))@82ywyDXJkzf=-fmRdS8m5Y!=@s2VojDrrOt~g*P0iW9`8`gGaZjR@ z!F0f-@-qcDEC~I;G`GAt9N$T1#AoirBo|oMIVth-X+7DL@h)5D(zWT4*l7!ED_5cg zoaDeR>Xk}?eAE-L`cBmvrDE^R^A)R$oea7EU~bZHOUTJ <16lbWel zYj2zzFye#eGe&+7UA6#GFkNEYeI !NN7ztueh< Hf`hZPUf!1RvyVdI=_aoK~pxWZUZQA`^q z`jp;z^1j^iG(*Wy7ZLsTg66rQ#}tS?DJ#)M%yo1W^q=I2IJ6i#a_Feg1kdKyUQ;vY zA*T<$wOvNj=T0RL+;(seT~}3dADe+VL6Cw)kzE^A)X(OS^J)qoYV rWoZ a*o>!xmyEi!1IUMm s?~(5@whgf_Kfv@2 zf`vwki*b)K@@lIFwukoIHYDYd%g_5?tb05_V421aWno_IdoY_LhEC)jO)N0DT%epF zn`JtQcNuH+)~R*Zv3Y|UbSW%p3+hkD6M+&veH~LjR-#0Km<(>| =VYU`xvtkK3;a7+INudP%#L9Ej@e7k?bq 6Tje6A8S7xBF-U&U#`^Eu_M;^6VWP1#EK%v&j)cyKiG6685n3 zG?CLMxd@`Cw$hy_uB@tzn|%^|!kWipqyUF3vA&FQDV7}Ep4%p>ox4_br6`a1(~-@M zt RhxJYl<^)=i&DPvxu3SUvgS;lOxeK_%d3NgX_q0*wh1!dVW7WUOLS zUd@RHlWrKL?vqI|^|YqBb<5!LGjIAwCM{2 -;2i}P(H} hXW*=0 e?U zBU8`QgqDWmh;6&Lm^Kb^9T&+)Aa-yu2@95FhM1ZW!o+H`vMG>+Uv5kZnjyWGz(ev% zP7goMAfNkC>Bz%5=91hn!IbniH9M&hL`Ku_B(95mTlHwIJGLqDo$a$b2M1EeQAJs} zMu9hZyGzVQ5xA7>$p|rwaI{}X+*DcQQOQtVStg}ewvujBLhSyw;iA;psrRicO0qKg zSj+fwJ95Av!C8j@t3BX(l2Bgb?!3KzO4`3A+bAsLj {``QszR*KMF dl_ z(--)MEz61^tF&A@?y{1U8P1ngB_%1OHOG-ny5d*b>Ugc*^(GALeXo}il1F}HWVJ7L z{UmR6lv%PfV}{w&H|M<#ic7rwtlNUsawNh<@-P#yGYQPqW6h2GlQJhqleW~hwjJlt zc$&hpncvph=9%X-DLe_48u8JoK-C%y#@8?ekteBMk4Gg6R%Ei&Mm<<{ad(Yx1Xwx0 z-F;ux JW+1A$M6$>ugQPp-I zScp>U+e&dTjvZoyEA7QesJmNRt0GJ096qYYh6h$Qv}8+7`_Zx}=4>TjY>KWedYB*p zcfM0rJV@f;*q1F8D;Ocz`ocfRHz3B~tUnpEa*nwvH`{uk3!YZ3)Tvnzbw&4Zkp-WD z$H8YQEJ?ZXE+WC*=I=~jGp{W6aSuDnH_)i31*^fa4PsuPRMagWr(^YW2t_`1`bG$u z{X!FeT+HgD)2sbBG~)^L1d1&`i9x(fC-PYD^wg}9G^n+=wdzS32p_c~=kXM!`jcDh zpMLN>mE|sC;QN}tRb|_q{ka`|;#b5P^7y27)Dk=IRz(bWGByTk#WdzN(#b#d^743< zxE^e;yg_71;q%YAQ=sRasNQUH4)Q~G0qs2#q;O}0WWo+T&4C> #6ImE%;E&*GH=W zRx8AO-4iuNzCTn8wr=(XKj0E@NXp7fiVHPTxt-`F=d>CatG;y=2II z_Z{2tMp9*83{_A^=>^Mheg4PdNlCQyJk5DGnA+jj21M`S8|$u@!v;mcly+6Njtx2D zVtt&gL?*p{iI26Q;k15d@96!3a-RDH3M4pis$4%X5|^mdZZi_z!2Pfy>dqf?#zDrc z1yhB^YXk`1EzL~^LApGsviN}k5 H~G&+;Z)J4Q2apWT&} zj@{%$XH;U+hhXQmSy8E1`#Q>HM6dK}mvQIq@^2PxsGo6P*V#{s;3MsF%i>zQONxWr znJ+$kcG4p3NgsM T4#Vkx~bvh}5xLZd;gzU>MMN)pGbN*23uya=P zJ6%~Bdz-ALWd>?SK1P# 1%s<_aXwqz?M9=u7%J&op?sD8aPj2OlAi_IHKl z_$Rd;xXv5RHk9bWEORv1TO&Jmk`(IYmmBJ>Suzm5OMPp8M7Xj}6+=nP6FU!b(FK@V zy_0oeYeXIwUv1IzIpbT+ IO3Z#Pt78>bZGc@OV zFAp^?+c45vXa|NiWluc{bh}Lu(>q-n>KWZnh;Sjtk+>#1%_cE-ZAj|1 G2sE#mBf R!5eU|B;fW^dq ztpO6>ga5-c0I)&@43A(n`(JI1e^%|^HSE8^M1P}S$Ij$`(nkNS7XI8d|DQ9`zvdHw z{_j}nzt_Z{b>aUxGi`5g{=aLg|EzHf%(add>wm%m=EvdY^HNDpLj^36se9YsX3?M5 zS^WIGf?!(tZPoR= hDTf zNa>gSKNI?8&-_P9zYr?TH@_1vyJr5Zpnv}G;OzW+^z-kyL(sC0Wrrvulo8sM%QR_` zD-O^S=im7MlG?oN!2DbC<{&3{SD$v?lK?{jaq7GCUoXp5&~}=e^N*}wfj>p&X&9ad zucy68@uZgW<#+y^WB+^_!?%pEKcG)1AnWE~RR4qB^O)Pef2N(7e_lNwf`H~zt~K+| zfKqB6;Hf~p)_kR$W}cqOdFVz+1pLxKJRk)A1=RR_>dbt6C-4UNgTW`3`Dj0wDrC zDMKg#wFGfT@Z =CZ76i=WJsGeyDCBD@{?( zcIHm%rf1B+)8~AeW@rKML=^|54O~5JP }aE{ zsILvG`pjG^^S_6vIUy0>K~|dBptVhq-@zEn5Fj7oELz3sh_>1>QxwXETHvZL;O~%E zTcRA@V;IFrcWw7-_w^ 6l!D#@$3T*>EKTBRh zOI|{~(@S1LOI|`tUP4P=LQ7skOI|`tUP4P=LQ7skOI|`tUP4P=LQ7skOI|`tUP4P= zLQ7skOI|`tUP4P=LjPx8Li79Dd%zAg1nGdAhPq+R2#$@+!4Z+^{9%y>I4D9vXmC5t z$Ls;droX^oh2$Zv&qqr0HGDdqqWkm}EgJA`G0C*gjzD%!ye8DIea-s;oi(xNqq+(~ zzy- hY(l&OyaGG|0s_Fth?SL9+R@xX zQd2?cb58Iiv(Q(`Rfremh~yKHkdWZx7vvKZ od?`l(;bi7$ zWl!~VVWpO90#3frGHh(rioRZ-Ni?xnQ~O%gFS%iB%lE6CPH0WUHzI$T(}{X)!Uy~e zP|l8K;KfmkZ*&4Oqyf9t)Fc&9X3n<2F-Ju~*4f$0TvAM4QB+<@K~zLRNnSuek^iu~ zlANM~yu6smVSX_oQ6Xu*pYnZc*XJ@-?7$1jc4mk#WeQ7(2nmXb$cZQ_0gnH9nG5p$ zRHg#L(aHs3uH=ZaooA}OiK7#O+CUk$FD?8kg-=WdXWgL9l2$(u^SOZ{f8M~K@_i$Q z%C}F+=D+6KUlzL{-?w7FGWA;{=hc#09UoPN7O2$MgdgC4L)Ct-Xbag#6{Ms*cy$Mj zPyn|q^`m<{{K7o^V%lFmx(DKt{NQzoA21g*ikhMZ{01%D{!SSSFn=rq^j&ikw8`Hp zWg+el<;=GS943MTP1*S`@cr301{XByGy3O}{%yiAH~T6JdvI<$Z(YpI_z*S-YF~5$ zW>A3dJ9(I!Nm|VNG|F1pg15l=&e$V>|JFC?zneh&FJE8$O6PYb=4 XEx5%;X_s&j5reF{CooZ z;QE|*Vfv4G4gMnU!t@{We#@$3XN8spKBV*H`~dzj*Ky#{>4H$OLL!_%9uZM)K@l-< zi-TK&TToPxTTo0G+yEvn%q=3s4{iYv2XJvAZb1oAZXtdFZXp42a7%ED2!dNk5Wqk= zV*KC+xMI|25s(gUAz>jwDLD~2B}HK+ej!mgIVFBMxx;dTq5|?Fg8X8K4~q+nAO1}E zca(i5``^}q5#ZaXzwR2;l%F+$3YFBbI*YK;SFi$oocaQqtbni(P>5e9EnxGvbc1hM zCHTL~xgh1oob$a<3(ThwvOHh%EP(xp{vFqZM8!pgxrO;9MEU1KASp2c!B3&!Jmga- z1mGe9pKye^sky}FLm*WkF#rJ}fC!6=@Xv=pq96|B2|}O&VnRSas3E`yp#(J)2bdtF z)+GeAg&I<85dvC74MAQI&gTU>BrG5dQmG-J7KEQ5V)JovYA6Bd1mQf6gb0X>2~y!= zK;J+Jv{G0=0+dM&sd**Dsd**DsW=kiR2&J3c^nCW`8c&SiTTnbB&an?%$F%ar38$W zqTE1pxq-HGi*k!`i*rkG1J(!#a0>`>3kY!w2y+8X21o*8+(7LG0WRnapf7-KA_960 zP ^Fxd|zkF3k>b2iPQf{_)X9LPm2Fk=u#z%V(t>Vme{o@4lD|JNxPQVwI~iO3VBJp zme{o@4lD|JNxPQVwI~iO3VBJpme{o@4lD|JNxPQVwI~iO3VBJpme{o@4lD|JNxPQV zwI~iO3VBJpme{o@4lD|JNxPQVwI~iO3VBJpme{o@4lD|JNxPQVwI~iO3VBJpme{o@ z4lD|JNxPQVwI~iO3VBJpme{o@4lD|JNxPQVwI~iO3VBJpme{o@4lD|JNxPQVwI~iO z3VBJpme{o@4lD}!x7xMloBt`o4mh2<0`F2v7wui(SOnM5R98|tra12^OM6pJ;jrQ| z@VQfaN3^4|rksJkfgvkhHTW7U_3O6aGBI bVT9hgczg=n$j Cxq_Vq0~6)#PfE)vwpc zt;wM0q`$kCd2PtLjq3s#HZg=U?qrN!&%OT12E`5a8xb34H~DVfx4B@8-j>O&flPu- z_1n&F-@Uz<8MR}_j#oQfc5&=#-R;Msz(Qor+~dH;%Qn0>X`em2Fgt$#Gmh&AbU4{K z#|}Q_3gkxcNb+vr9pHP(e^>6$()c?gh?F| zlH)$SU!F~YRgp!BReA3b4iz3%;iJ;Wl-0D3pH@d{U`_;R#%Seg*XZ=?Ez{p^AZe&? zboOMpasH{dr&pTrnChDSVV;O+L9VhCx3W5O$GXOr&JKn;YoF#Y;>3kM;~eiYbe7Kz z?Vfv%##7ZR1oQ4Z?}c+0D=+W9;^19$ZO3&-pK@Pzzw`cY0;B^Yf=D6o&= TE%w6X~&l*DkK%ANIcF;6Hd>_6wb ?!?1w?TpPA-qF!4!tew9;|9pD*F{C_&=vUERUJ*t^vjL*K0Uqq>l$TH~D4vdn zdd=4ag5@h{m#w6M=vJ*>L%$wcMng-xZ27X4bhIE?=0vlMcEfUL#h#4 Wa!rE9AF-QKk>4@dlKP%IV2{tsG(=d!sSZn!>r=Q-f1yqJ*2C5SZsDl zQ{RmE5q- X}=a#h&5GbwCDr#e3 z(A068mUN5C2+@D>M^r_Vop0}o6ZJuI0mjG)WSKjUB00fo2SfaRT@;>aJCXujezi3R z{2^-RZcoYktwuh*ETdPCu#D;LzT#BiL3Z+z*QpV{DZRVbkOGw+2*GquJNa6Z9rLQ) z17t(mT`Vyct28h#j_nU3v#>FH_c2AH2B&;YCoi@j(JW&E!P`_Edf%A#xs4{9r%W8{ zo64dIBzI{Uu)FLny7qE)a-S%7SbDMBKEK$P0^9cU@egQ>ZmAzs?+NfG+FrajF?#DX zc~GlBeadbhOWasl+k{V*Xy= cm?@<~UX2 z)cEm7hq4-Z dG zg}Dl1Th~8^ _=~77>6;a+d?0ly0+f1&-O!!AB+&F>uz{G;T4u4ISj{+Us`-%ch zS!7V4KfqtSU-0x2PIj1im3#moN8co=osR(xw;f+wfWB2yrlL$#I!OZ~c4gmW7h(3` zAY^aCY-iZoj;UgG+YNslc7g&WNKhc(hOvjEWc!4&G}MY7B1X&?*L&o-H4gu5SO(W& ze9D{xo!Ww$^(nd}hMTxZxUM&FJAdO@_nT>$m#0qp!+~OM#}{`z?6Br6!3*YM@thm| zXKj4Xz$b3(_Db!XL?spqsBOYLCqz=9caB`~UfTGSqjCAQD6 zS(W`&zB~LXR>2&~v+`~?yv!P@dGg_vDz?DU>YmqGe4YH=w1#BW6vYsd4h1^@WJ(F$ z$%Cn~a=ZTOQll-;X!I@vE_w>|j4zIf7*N&Jjl!2<54eSgb`0p&@kZE*X|Gbpi_z=j zx=}HAE^r2#Z&Y|zb6KAA5$g=yu7AzORa0vI#m*62v3aZ6A+ddZA`||^Zg`M%V&%G` z@%DB;{Uqi1hB01TjutsTA=0%1I}uU4QR`6c(_Ig8199U@%$QPQFEa%q_Ao_FU4K-# zH2~X^<*P+j<#)q%KXj@zt8_2SD#|?C=5rs@S(`_JUN*loj59lQ@c5BQR5?m;P@A;t zp>b90bSTq%3Pe}pO%y$j#^8(KvS+mUEJEWwss$Nm^;->K?*tv9fuuKBZ+ty)`%cDg zw#{zpL|DT(iVEF~cWl2>k4hdnG8D zgNX!cIZwXPY#|W~d4U#p_iMw@UDm#VT z*u6g-ZP|N?`4-Fjs}!huy965rN{oaP6DP$$AMO+3;dqbg&D(#TuzlETA3lS@Q-K1R z?86Q8og2sYZoSz1fn>a9dPh>c4znMu>GG2@>`>4?iGOAIg;8q%C9OQIrl*%)%hNh@ z; I8-kQN@)1_Pba8)V7 z`1Z7crj#iQ3gmwl=emA+vTm*#KVWWi&B|S-H%YS9>a~iK6#B@`JeKJLtE*CbfXXpS zS(}(YxgaCEx1(281onROsYLA9neh62s>tLK+twuw1eSTk b*U(h!<#@oo-S_P#``oAlOkN&5_j-`o#br*kvpG^P~MjyyT8N9<9KJeOU}72c$o z1#iyXc^li^&bJ-YZKgs_c1;1pNtFp6uK%7Pb7$_!-akTjKLFP8Myj6~DUyqv<&wly z!R(R;<<%ye=Keu$=iP~UzU#5qKcCT2>iz|#YNkEeG)Y?7k}_pXlZlMN(96hu1M8SI#b4qED<*GX63Vf7iGEl)1;W3e zr$3Y}YnLmgIVC#X{lKiH7gi8N@{W$WFy0rOf#q)VQQKO( {c$CC-wSl8+KYT3HSaSVarb=$pyEjajCLX4&8)1 zm#pnOM`kh3?B|Y_sB4kk6T_bp`+?SJxzTYFlg_25oLKkzEd^q~Em_=0vh1qb)H_-Z z6L6C&8w}lKbU=7&&G-#4U`wC7kD8U{sL328ZFF#rX+LT$IeFGN0QdIhjUlocu(`O2 zQ$EE!#- tq$-yo;@Gb-2jKK8~wmLil3t zTs&Ss>@2Q3P;5EEYUjU+PHWse{%zzxoH$}A_5WN=mN#Vj$n0(z&E$;E%DSQRAmqX$ z3S{2W$5MgAS42q3x|~w;9@HF>&E)6WCMzI6R?0`Hb+;zV_uV?z*5`|?Y}!9#oEtcB zs=fMo=I~DIxhG8|#gpRWblo%I=ceCUX5FwIRC*Hh_A;g~!7~@beG2r?ps0I9umFja zdo9e% #n(ZRNl@G+fS(SbrpF~P;p!rH@IRJ zP6~Cw?FV)P;TClCJww5A$w;<8o{%bVV-6QLVP0XU4c?rK0IM;z?rMRL*FCP(B{L2g zGjPGJnu1|tcHxb-e0%bJky!zVYehOW7dctF(}u7AqJe*{Iv7gBKh=^OQD@&Og<7m; zUS@FXH6$5o_8Lh;d<`U+Ta&@yBCB^IuH*Ve&V5GrD3Ja+J(h{;8<>wSZbz$GZV^WB zjCf_I7)y6=)RYZ~C7NFI0<#LE;p}12)#G$Muv__fv6y?U=`YvqcAYg q#MY@m}m1VTv+E)rQ^oKELxcnCxsTtnZv?dyAT>a`o^yI~=WlTE|a#vyKJ? zx#;XztM#3JM2McHBRjghY<8nSC%Cd7nFM3fu1iv&7vt4uE%okGAoZ;L9oO#psn4>n zyZEcYzuC7Zm?>4HpxsKCCw=cD1WW|wEx{Lw>)Vna-pi}mcBs|%1*)q4qv70B;=5R) znf}COw{o(5XGN|aX9nlJ`gdFIH`Rt>2ab5|r9j|+bKjN;x{ypbZ{?J+X|1&iCRCdX zKILZff^>32kH7R_lx|q#>rrIJnfj~kmtlh?q&5naesV *OEjmJHK3RXF1QU*n z@-ibnyZP{*ShR^@Qlf}{iFe$b77VY6d93}aDOlP!5&wKh-%>ZtSS_1(?>i058G{`& z4k?7;s5s(dz!aG}bTU&1>L&c;b(VzUBbU|jwqvC*Vvs*EtXjc9|Cz}e!&ar6&$e}4 zW4^4jdriVvGS5###zz)nud#Onv1jvSYggHRf=-M-S@`4>vU`{UH4(AV?VB`h?rKeF z>sJ$%_iz6-4^JDbt7bIp5zW0M(0=HRrZz(?$>%~&Nq!F)Z-RQ(c?9RWm&Ua38l*{d zp1E-RD7kpQkGL{eq4ljNw%i+!P@T*?>VO;ZUu`wI92YOaUL}%XnVl=$Tc>%!$f_w` z_3}1Msy)LI=?HvEFKYi|(rOI104=FTx(hb({5V)vJ|C|>Oon5sEMEw*r$q92GQak; zXx@k$RIzK1#8h(xkp=o5WU%n}lTT-;$*Vl^8)#Hd-)FP!9In)4PPKF6yDQ&D-M_a3 z1*0_mBgJ@}Ug2d?m!D})h)R_-GAx _)8RLxOoa6~$SvY2JJ+aMIG`6-*aVNR?_f|UzozRg(y2wI0cOqo=;(>7x_i*-n zabhAN!gAfJj2q;SxcAaH3zn%(!Pp*!mH~fWH?w2o4fp$7Me<#;N^ACR?!@0B#bU-g zyIx5D+z+C_k|FYK+Pk=Zv0(D}>gW`LUlIipO3%bp3BpNEub53nw}lFkiwz*KqgECD zlU{u(@o_qQyg0mf+q#FT*6Z3irV)qgDUe=R3#^CNo&rgMkzt1$M!N?Vh73}RtiRft z_5vP+HGp+nQ=qsgOJXrGY=Wa_u1PPu$5L%;FQ4E3u~`cA#s(9pqx2ld=4CeMrIgRq zy5+^;lHp=kKRIGr(KMWd%ECP^kE$U89gFm !G?lb;*xcox
D^Z1ph zss(`{> x-EmJo>nIx7EESj`Vc3m=;Q<&GK|kq!8iL z6sR*Fmk-x#Ygcw+uBPP<5MP`4U<>Oc!X%xuNa*i%=g*@i?4Rwd^x~r6ky*IVR=r30 zhz2`3BTGhqx0ulnC17&BW5#;!Sk#K9%)wE9_|fgD4PlJSjwRR>x~g zwSt!-rix28KGmA+q~up$)0Hlwchjr9om}sLooND+KL c$SG`8{gYq=im7@pR2ra-QW6o>&kl6`Wlua~Z;F|}LfQ2*`r z{bKDUY@<7U$V4zUTVh_s4##)*jVqHKSu}|SA?Udgz1w?Pu5a`@kkEM4v~vv1puno9 z8&(q4IgY!H9u;m@POz*?DtZw84l(2rozkkpG#yaL{^I0sl wt}0ZjJ=Y&w7?SjK z|M_gKnwmV7O;gHnd}a>sS@=ZQIEM}~J4Z0nF5?<=z{yAbrvi@SMshIk_L2Ns6%G&+ ziS3OrUKBa|Axz3@)zok#_V^)K*G9(X5HEJHJeAn*Q8L~+A$ElLtWHm>rn_B3jb5w% z8ZHnh!&O)_rlr*4Cvp5nz5dDKeoyCZmfMDUJsr1NLm#%soVm)XDN#m&%5Y^q qn<`O20apfld#6ye3M{?E!9XiMMz#ut3Ay AQ_E z;@SWl(K?caY=6DaFEb9zU1j27MEZ}wjD`>W&R_zjoi^4wn%R(K{up P^>PJ?`1Z@Z6UKu{lL95SDx&} z;YB-pFnNV#=U}@%WVdN9*Ei7!xVt9){vR}H@sB=4v;1nPqYn3%$gc8(Zd?X%dd>*) z3a~yZ&go^rKQF%!WtZ!d-mEgKveM(n#ng|wo%X=jToa6M%T}@7z1Z9ri0fm;^f6Ul z4XcP!yPEkVq21ta-0@+acyc|al5q%=OJ+PT-E-IN!d!V%>Y3Zxl_*zQM`igZU 5pT__H3=l5Q?Pabd{N4Q6obwr25L zPwpERKiZ7@6W_%o9PN`p(7wA~tf_wa)IM pCg z958wG`q}BD{yjlMrPBzq^T%^z##VYtobqjN+6q>Q=qZCW&vHNCsOLZ~pbtj|`&V3m z@!%gGy8Y<>Gy8ga*aejqUJRIa63yqluKw+Qv)IL5HAWaFonL@=+n{zBeu{WK=7GZY zbzY@G( RYOz(X!C@|CEEsjUj?4>@Zdkm4RtARe#`zP*1l+1N{O z& &Xh%;W!}+zpKDl*9aAqS zBl;c-{nG4z5A^l&1pP>+)$8=3)`y{6JB_b-F?~osUkla>VB_1fat>xfW=wrosim4< zgWC5P=Q}(y-02g2T@Y+pz`SLE(8MPILE?NeeBAirGwNwZ9TF`RD3mJ{Hd5UkL24ln z&5}7~V83b6cd}gEdW_x8ZCx;*6MAs7KpfI_kItciipsQPH|2>4vSWuq#cfzXbIJPn zf{!elFck;In&GoKWLUTMoLeu_!&m8TdRSDiMf>f%JOP5i8$WlZaeuPI4vj|DGp8JQ z%#i8yh*l)aM |vQvS>rQd!W4+t;9>ZKL!pfUp20UXFo_=N*~3!jZ0GdN ze%HuIEZOnStQUMhcGwQqoncT4>!aJ7)R;!z(8icw32ath;>7o&`Q;OG2k0CA#CtXQ z4bdm9n|QO_uVCqq@LHv_F`T;e7R830(Ho8?VOy2Pyj*dmaD17XeA!`{y%pz1GXfM< zxD4*Gbcd1&U 8_^GLknouI#blp_uM~N{AM01RNwiL|t|Q1|SMMag&Jx-3nW0 zVs6+bf30wpwNkKO(8; H`M>myc=-l63jg#>}?~$Oo*F$KeAk zgJAYo`XN08Q?-r)VUoaBhBcwDTK|{g`2kohf~m6bGWAqe&mO-VU2FZE zGCS;_G6Evg7#nbq$mk^Npv6 zl5NO}gV-=3rd)Vp{|&2M?We~?KBT40JyahzdWV`ZD%{`&_p%uDI$S`Q_LfkstG||g z9qgf$bdoTmo2FT0V)62zt8ThSJ{@oHO3^PxZMfSuaz?ZklZScFGK1?*Bf2&G9UZi& zUd+1e59b2M68VfEjRuaR*7}zXRn|e|Bw{>nlULPQqlt-$uD%K8i2+^dd#{IEQ PlG z25x_UO+Pa?+m5q@86>JTP>+ s3Rr9e7PeaQ)~kGve* z-rkC5uTNg4#6XVRi%7}X+FzwUZHtu?=GodN|2VrgQSWkQqV;AoV#rQKOc~i`g9l>8 zB%if2bNTW=5~BYodpf17+j7OtX#&`%jfD@Bx>3{(mnr(an9^`qv&yttHSZh4H&(7Z zE1rYRmUYz4mThM*Dk+_ugmsS+dop|d`}<{`dR#4Jx8&`pxJc$@`8bB{!2rX*-Knva zH^(g5Q2CLS6MJRi{kVM=cPS8Rg0J=D-+8qK`}fy<)RzJ>YI&mOz)JxhmPMyjwjDe_ zQW@n)tN;e>ReD+ ?g9{w%S!s|M$emkgJ4d9{N*IC7EKZgIEY8EtA>IjoPPOAr|DU{V0h+(RGnPU71M zO>jDNs&^Y>do42Q?{t}J?8Ghjt jX_kBC{)IyuF?c~==VwC zf&=(_DQ@F^gNDQ9NA5Q4fnNa=(Hjno-lPb}0G!oF@*!f}1S6JX5-p`0$Zt7;d$AFd z!r4Z;Ks|h$G{zFUbOU;@d;`p(>0D=+BXynfP0rjb?h-RMhi7x`^{V%MK|WZ800O{> z#r9o-_hsI}bb%M=nEP`6QnXHReCallI_tpmkOvOfT>S`fJ>t8y8I2-G22- fi z47KuzanxYTsgy!ej=uS@sQEC?#msa*cDV;c(Q0Ppeb};DB`CUZLt%i}<#pfIXI8$z z6g;ICi|}H#md$6^aEM&bTCR+)@ViyJX5}rje5am3&QQW0+<+Sj;Dg=re|&1%f1A__ zrn?9&d6&n=zLz~UbJ!=m&e&MgJdRENqvpUq;y%|EsmbyCSd?5^?|I~X 9t3?vBCGuvdtS=p-}dy;xq3#IVR!b9 G-Tw(6a zQa^)Zz0VzxC2&prr2gYNHYZ_G&wlO>M46fQ(&8gl;hL?yYPJk-8KU7IVdiY`%ogD6 zm26?}xzI$4vUS>*b#6H>IJcmsbFX+h4OP^c7(A0^@t06HLWdhLb&_8P5IVD`q(`T- z?C$#3<2ZWFtJm8V`w0sG@>dg=KOKkd;b4fd#YNN=udwNM^Dd|NHBfmlby$a HstoDTaw5L?_g;_CJ^B z9X!1EQnPAzdoX@d)yH;uTW-w?-x$Y!0nc<~u!3PP=O3ftOR-P+62^X4*PaI^HH?}? z@?sSi-+L#D$X_#ZqG_!SfVm@_T`h_5!#4+ea@wmwF8dyUEfL4BN&ksOct&lB3m{64 z>w?7MB;|tuw3$OkhWrt=ArH~Ofd?NEi976~|7c3rtL_}RwMN4~@CIDO=ALbNANVvo zuRP1q?tbZ`+14P$Av}QykEZ rsT;q zDiN>xSw@*3j6Sb&EZzQUb#xHt9gTvaV4_b1TDwj={wAgWA-m|Q&!WuCxmx%;@h-J) zmcc6@#c+eD30vN{U>W1=6+X?6hxA-1`NuH(Z2N9^qgvW4d_s $I!IzR`T;)Vg7EL?p6IHL&A-@njwF-!3y3WrDya z(o%e{s$f{xuOMP{i;-D@r?{DYOMCtkdU&r4M-%7BvMyiS$|u~lkqG}8Ix@T#jZN8x zqsM^M67cOK7Zx=B(J}l#pOUDkr#1~Ugq5?NQmohkA=`==*Sc0?Ft<`Sv0!Ss+q&g8ws zbV2Bj2>=r8Y_(6A1$G+p;d`=_5k |FR9>ASP)LB8ZV3rp*l3(J<$~?dReuF|?p+87N%D zvE`n_$CR|F{3etcAIF<$>YY{OsB$VWjdbkUD@Fl ?=l4McRws8s5LGOU&Zat{VZ-^6zi=&rjF9zE!&` zUl ;?lW z( ua9j9m$xPLHXE5sH3$LjFZKF* za3Eqe{M;k^a~sy7N}*7T8N8SfS{L-LI23iN!Xr#m7GRcB??G*9xH&yV-WF39KhH`S z4If(J%QUC{aG@T {#rzMEpQ^r0qm%8$t?fxn3=4jn?g}9nU>)BS9ws xIqU8@Zlw$nZcz?eZhe`7VOWK)@NK{QuB#vQ z3c5&Kc%_q!>xj2RCBlaa(-2m1^lPA_S;9rsRHFE!q83n#4ZIhcmiQ3FyS)*J|FkZs zy$7c*hO>p<+i9?IQo=9|xu|lLM`rU!P8St-$?B><`H?nt%j#LLYhM65AA1Zu^KJ$J z^^cSOPkwbf5%pR_qr5@t61J3?^q;>dckz+4G-rkHvs5Z*&lz)kjbraG4@S3e!cw!d zYNmb!xIp_o`HV%- $j=zF&ApC;UJbL*yenc-&yJtzuPdH>h`sVwWW=U!~ IJleC@|;6t856e?*PcVwo?T|3h?|y8o$xCE3mW+U&&99f0sVIs zb~ONUlqu}{P RywC@;#N4|r)Mr5OO^o5OQ~hWh~dBq_&R;33mFRl3Aw z_C#b&FZ3POU*S{p8u){QQj-A}@_7Sf)+d_J3uHM-F2{nRbG-5dxiR^IONwRNbk=2s zq^*Gt3d|M0EfKQ+6n8It(KP$Il`Y;!W#M9GUC{83iSOd`HaEAd@U3c$Ia3IlK5z$} zJJ(!N+^l+bXV?ngW&_(5zM#5WS>S7PnROe5gcM`f-o#cMgNB&I#S4#JAa0WIv_abF zZ#AlW92}8t2SLM)-DO~MNmbmO&H%wo%Qfxo4 ?larFrJmVHsvhYDWxx&`yRzJrL$UOySs-<5>q0KXN#SPHcWI)C=J zD6d-n{T1r4&j@Py%~_sq{2>>y#gE6X@SQpR8tUv~qndAsOWU`Iqi>6G9J!Ow*JsX{ zIqwfEeBsVdi0~JlEG5XKWX+%iZl*{KJk9;0b18e9p5Mv=ZAA&k&36FblytC*f59R(Uy$?4W9h??Ke))l{m!S&a<5}pZDcs& z#`_WU2D_y-;J%~OQa)yJP`&~P#H%s5vxY?m^>{`}D5`j~!Y>!DC1_X%d=#_AGo0wC ze%V!pX{K=EL@`DC( Ei`xcC#LK{O_~uAGqR@8aBDyz9?wwNilG&xO{=wBx z6t<}A#k7vxspo0SQ;vkiP`g(b5tQ3P!E2j+aDk{gu_!(}UbY>_#`@1V<8Aa@pX2E7 zRsp79vof}g%2u4)dBDZu!uF@EJr=kMP0Ar(ZG@E@^H#d_VKg&Oy+a~IBgKP?9MYd9 z!u8O>u_%EI*{zVn&D)^EW Z@ab>venx 0hWL@=f6o z?ZT44U&Aa(0QItLz?gJQsMT*rgbfl&I_Pawsea)$os7)X0m&>b5o|x{%T3tgnTv-! ze`Nx?v}1*D!%Qw>PxJcg{rvTU{|G^#|B9pxwy~~t+#Gwdc=t;aAKP9dPum5@CaMY? zLpV8ZTKa8{>7&|swpVv?2k)N8g?TbEOpMgJ%UGOdT3ER}b>F@49p~dt9s5ZzhDMIw zdh*NXqyR*hL~py`n-ZOIx8R-LM%+wT%xR$c !abJIZJdkz4JPI?=-@KqOXsY zx_ulN-x?HB6U2)O8-wa)*}iOq)m5x+s@tBEbN7dXBLKw}JZot49ajQ3Qp3N~Ma0nc zCNAGS7=x(f0^cTiVq+FuX4a*vl04Vksvcl&4YL31H(qU(&y^Zi`M5sW*2@btOB`L{ zn^~uP99Y-Baya91TU+Xr{oE6pix+;-e}2HWfm6N3pXq(pTQWI)y2ZqHK~p3bIdy)P z27l>)^rA!I0b$$Db=0909dPkIhuf*_O=`uvwoJ}V)PC9QL539pR(e#g5QGdnKAUtN zvuM7dz0C0eCsRu{yazo^+S`y4L%!~e0(BXZ;(X$)Jwxzl&*iZM`y`{$ioxSckz216 zJo@JGa2Nl*J2(@We_;{VSNSn{D$A~AW{3EB@ZMrX*Hbk;@FGbCeKVr{USh#)n;?Dn z+3*}~)WfGvu`EmpTv{I#0V Y%a(%F{ePrZ!K0_{n;z!48c@G|tW8;V)g^ zM*BW%2*_h*$~{4fSspY- _0 zI^bbpDG)w}yk0utxN-Y$wx<`r>ErPeOpXF4zs?+(hhk z!moV6F$QAG0}ifQPL1NyU%X^ow|{j8aSs5|V>*rK1^oyzTuDEGKIF`%T>W5SHAXhd zHP~#I4RKE3K`d;*>#5HF^ z68W!a>7-oL)3uo} zG%Z2c>3-5?rT`C*^QL*K*}X%8Sf_l~gs`G$xAJZ;?M=wQJ*cL4mVLhcYTM+&_Q{~# zZX-I+ZXfxTVQwms`D2wRV3i68IV78I0|S$SvP%Imn)bv+@6gpy%MMq_?5p>d!(sY` zU!w%qMXv_Ul+XQV-Tz#c%f~L6hw*)je1?|~^d%`as>Q7EU4EEqlUEU7nj5rR{UUB+ zkuA XnbX*`u}Ns?Znhq%_dn854M`>qt?%W?GG(WsMAev0gEI zh3}`DSDb4Ku}fhdn>F~&I+8k_>WKN>_VmM;dCoVbkhRYHW{uZI&TdZpfeR13+3j?_ zAn{pPYbrq#`u=vadFxFqTq&qvV^Am)s;8i?eJH$kd3Sd^pyWS%y@`h_)c5ZdwY*$X zqFyB(F1QF~?@Mu_b3;F!ZI`b3{H=tS!Mp|9HaCYu6?SYL4u5QcOJG>Ln_S)WKIt@c z16EdJb>i0ee+@7HYBTu`HI3WPr%GIE@V$3r>$y2<1NN}1x8joi>nFbNf(@t)J1Yz- zqKpD4pmdj!bLLI6`*pL~*;EGZyZc)Dj4WFPXa Ew9dSidb4Q z?&yk`V{U#Dg#Px{8!z)K1L{6E9D7+ay#nXJ =3UcC7+fqpivzmasa zLg|23c+ae{L47|jgiTWo#zIPJv$s2RGp!B$mTo+yaKw6XLnnWj#J>5G+IRMJ~wD)F?`E0$#UZ2_ig|C!F$1rF_=+?wP0qcL-LdXA#{7=Dy zAUVLr9xk9_U-Sy;W$-W6wg#aGHGYTKJJj-)99zB)sC3C`96pKr#l@gynZ0)zUtH7ZZ%9)yNb8H9aYK)#dX0$;Hb!{nNUmO9hbY{Vo8u!IB6 z =$GT$|o6AS i04zz9)T;%61Ae+s*{0qT)pOrC~ z;~ALNsG5y~i2MeC=0hhlNM5LiZC#(jUOnxP&jLG}9#R ;b!?4*(_dF9`|mgAj}`d4f4N(@ b!RL7ku z4Ph2O8fp>Vy!NnG;?2?Kk4hygd@{P>6u5$Z!1ygPbhB(zU%zRsW63k9UMZS7a)h0A z@^6cv<_7lu6;m+XwJYUHu(K!vz!pS3*q6q0vQYpMgxi*2UwpthXw`5D*l+S$B}tNR za;)0?74Uz7r7L{zX>R`kf#UwF>IMZzWgjZ9TymvZ+`VizdEOFR{N}kXu!4_Plc0M& z(0caf0N%=@oGV$1aq8~yg|gezkoCTfe;kFXDY-V5)IEa+<(*k;zHK{ml1+|rmp}@+ zh|Py1^8MV+4;IMb_q0H)UUSm1^}y*}qF@EWA(cQ!l25(IQo`hf$@KZhSq =hK&3v%vJjFSV}leP{WPFY!m+Bp 2{75ps40nD|J2kvFJ{B|X*uO{P-lV$z&3fzMzIe+ za_ez$!)-N68W7)E }^K8t8Fvf^!RE{{$WJCB@ObO1Id2u{X3+7{T7 zkl5Il^CpkTn|$5c#7|zorIr`lOH149{$lGZw_TI@o{w&Kog?nL+Kfjwe%bR+-uZ9# z{|9LKZ>lU+Z{HerNtHykiW^S&^X+@;|Eb$syK_z;`8=W6OFmMuxd%kvV8>55_TE{{ z*FnwpOCjnN3YC6K*=