Updatify / Go lang | Release notes

Create your changelog

Go is a high-level, general-purpose programming language that is statically typed and compiled. It is known for the simplicity of its syntax and the efficiency of development that it enables through the inclusion of a large standard library supplying many needs for common projects.

Update Aug 11, 2020 tracked by Updatify

go1.15 (released 2020-08-11)

Introduction to Go 1.15

The latest Go release, version 1.15, arrives six months after Go 1.14. 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.

Go 1.15 includes substantial improvements to the linker, improves allocation for small objects at high core counts, and deprecates X.509 CommonName. GOPROXY now supports skipping proxies that return errors and a new embedded tzdata package has been added.

Changes to the language

There are no changes to the language.

Ports

Darwin

As announced in the Go 1.14 release notes, Go 1.15 requires macOS 10.12 Sierra or later; support for previous versions has been discontinued.

As announced in the Go 1.14 release notes, Go 1.15 drops support for 32-bit binaries on macOS, iOS, iPadOS, watchOS, and tvOS (the darwin/386 and darwin/arm ports). Go continues to support the 64-bit darwin/amd64 and darwin/arm64 ports.

Windows

Go now generates Windows ASLR executables when -buildmode=pie cmd/link flag is provided. Go command uses -buildmode=pie by default on Windows.

The -race and -msan flags now always enable -d=checkptr, which checks uses of unsafe.Pointer. This was previously the case on all OSes except Windows.

Go-built DLLs no longer cause the process to exit when it receives a signal (such as Ctrl-C at a terminal).

Android

When linking binaries for Android, Go 1.15 explicitly selects the lld linker available in recent versions of the NDK. The lld linker avoids crashes on some devices, and is planned to become the default NDK linker in a future NDK version.

OpenBSD

Go 1.15 adds support for OpenBSD 6.7 on GOARCH=arm and GOARCH=arm64. Previous versions of Go already supported OpenBSD 6.7 on GOARCH=386 and GOARCH=amd64.

RISC-V

There has been progress in improving the stability and performance of the 64-bit RISC-V port on Linux ( GOOS=linux, GOARCH=riscv64). It also now supports asynchronous preemption.

386

Go 1.15 is the last release to support x87-only floating-point hardware ( GO386=387). Future releases will require at least SSE2 support on 386, raising Go’s minimum GOARCH=386 requirement to the Intel Pentium 4 (released in 2000) or AMD Opteron/Athlon 64 (released in 2003).

Tools

Go command

The GOPROXY environment variable now supports skipping proxies that return errors. Proxy URLs may now be separated with either commas ( ,) or pipe characters ( |). If a proxy URL is followed by a comma, the go command will only try the next proxy in the list after a 404 or 410 HTTP response. If a proxy URL is followed by a pipe character, the go command will try the next proxy in the list after any error. Note that the default value of GOPROXY remains https://proxy.golang.org,direct, which does not fall back to direct in case of errors.

go test

Changing the -timeout flag now invalidates cached test results. A cached result for a test run with a long timeout will no longer count as passing when go test is re-invoked with a short one.

Flag parsing

Various flag parsing issues in go test and go vet have been fixed. Notably, flags specified in GOFLAGS are handled more consistently, and the -outputdir flag now interprets relative paths relative to the working directory of the go command (rather than the working directory of each individual test).

Module cache

The location of the module cache may now be set with the GOMODCACHE environment variable. The default value of GOMODCACHE is GOPATH[0]/pkg/mod, the location of the module cache before this change.

A workaround is now available for Windows “Access is denied” errors in go commands that access the module cache, caused by external programs concurrently scanning the file system (see issue #36568). The workaround is not enabled by default because it is not safe to use when Go versions lower than 1.14.2 and 1.13.10 are running concurrently with the same module cache. It can be enabled by explicitly setting the environment variable GODEBUG=modcacheunzipinplace=1.

Vet

New warning for string(x)

The vet tool now warns about conversions of the form string(x) where x has an integer type other than rune or byte. Experience with Go has shown that many conversions of this form erroneously assume that string(x) evaluates to the string representation of the integer x. It actually evaluates to a string containing the UTF-8 encoding of the value of x. For example, string(9786) does not evaluate to the string "9786"; it evaluates to the string "\xe2\x98\xba", or "☺".

Code that is using string(x) correctly can be rewritten to string(rune(x)). Or, in some cases, calling utf8.EncodeRune(buf, x) with a suitable byte slice buf may be the right solution. Other code should most likely use strconv.Itoa or fmt.Sprint.

This new vet check is enabled by default when using go test.

We are considering prohibiting the conversion in a future release of Go. That is, the language would change to only permit string(x) for integer x when the type of x is rune or byte. Such a language change would not be backward compatible. We are using this vet check as a first trial step toward changing the language.

New warning for impossible interface conversions

The vet tool now warns about type assertions from one interface type to another interface type when the type assertion will always fail. This will happen if both interface types implement a method with the same name but with a different type signature.

There is no reason to write a type assertion that always fails, so any code that triggers this vet check should be rewritten.

This new vet check is enabled by default when using go test.

We are considering prohibiting impossible interface type assertions in a future release of Go. Such a language change would not be backward compatible. We are using this vet check as a first trial step toward changing the language.

Runtime

If panic is invoked with a value whose type is derived from any of: bool, complex64, complex128, float32, float64, int, int8, int16, int32, int64, string, uint, uint8, uint16, uint32, uint64, uintptr, then the value will be printed, instead of just its address. Previously, this was only true for values of exactly these types.

On a Unix system, if the kill command or kill system call is used to send a SIGSEGV, SIGBUS, or SIGFPE signal to a Go program, and if the signal is not being handled via os/signal.Notify, the Go program will now reliably crash with a stack trace. In earlier releases the behavior was unpredictable.

Allocation of small objects now performs much better at high core counts, and has lower worst-case latency.

Converting a small integer value into an interface value no longer causes allocation.

Non-blocking receives on closed channels now perform as well as non-blocking receives on open channels.

Compiler

Package unsafe ’s safety rules allow converting an unsafe.Pointer into uintptr when calling certain functions. Previously, in some cases, the compiler allowed multiple chained conversions (for example, syscall.Syscall(…, uintptr(uintptr(ptr)), …)). The compiler now requires exactly one conversion. Code that used multiple conversions should be updated to satisfy the safety rules.

Go 1.15 reduces typical binary sizes by around 5% compared to Go 1.14 by eliminating certain types of GC metadata and more aggressively eliminating unused type metadata.

The toolchain now mitigates Intel CPU erratum SKX102 on GOARCH=amd64 by aligning functions to 32 byte boundaries and padding jump instructions. While this padding increases binary sizes, this is more than made up for by the binary size improvements mentioned above.

Go 1.15 adds a -spectre flag to both the compiler and the assembler, to allow enabling Spectre mitigations. These should almost never be needed and are provided mainly as a “defense in depth” mechanism. See the Spectre wiki page for details.

The compiler now rejects //go: compiler directives that have no meaning for the declaration they are applied to with a “misplaced compiler directive” error. Such misapplied directives were broken before, but were silently ignored by the compiler.

The compiler’s -json optimization logging now reports large (>= 128 byte) copies and includes explanations of escape analysis decisions.

Linker

This release includes substantial improvements to the Go linker, which reduce linker resource usage (both time and memory) and improve code robustness/maintainability.

For a representative set of large Go programs, linking is 20% faster and requires 30% less memory on average, for ELF -based OSes (Linux, FreeBSD, NetBSD, OpenBSD, Dragonfly, and Solaris) running on amd64 architectures, with more modest improvements for other architecture/OS combinations.

The key contributors to better linker performance are a newly redesigned object file format, and a revamping of internal phases to increase concurrency (for example, applying relocations to symbols in parallel). Object files in Go 1.15 are slightly larger than their 1.14 equivalents.

These changes are part of a multi-release project to modernize the Go linker, meaning that there will be additional linker improvements expected in future releases.

The linker now defaults to internal linking mode for -buildmode=pie on linux/amd64 and linux/arm64, so these configurations no longer require a C linker. External linking mode (which was the default in Go 1.14 for -buildmode=pie) can still be requested with -ldflags=-linkmode=external flag.

Objdump

The objdump tool now supports disassembling in GNU assembler syntax with the -gnu flag.

Standard library

New embedded tzdata package

Go 1.15 includes a new package, time/tzdata, that permits embedding the timezone database into a program. Importing this package (as import _ "time/tzdata") permits the program to find timezone information even if the timezone database is not available on the local system. You can also embed the timezone database by building with -tags timetzdata. Either approach increases the size of the program by about 800 KB.

Cgo

Go 1.15 will translate the C type EGLConfig to the Go type uintptr. This change is similar to how Go 1.12 and newer treats EGLDisplay, Darwin’s CoreFoundation and Java’s JNI types. See the cgo documentation for more information.

In Go 1.15.3 and later, cgo will not permit Go code to allocate an undefined struct type (a C struct defined as just struct S; or similar) on the stack or heap. Go code will only be permitted to use pointers to those types. Allocating an instance of such a struct and passing a pointer, or a full struct value, to C code was always unsafe and unlikely to work correctly; it is now forbidden. The fix is to either rewrite the Go code to use only pointers, or to ensure that the Go code sees the full definition of the struct by including the appropriate C header file.

X.509 CommonName deprecation

The deprecated, legacy behavior of treating the CommonName field on X.509 certificates as a host name when no Subject Alternative Names are present is now disabled by default. It can be temporarily re-enabled by adding the value x509ignoreCN=0 to the GODEBUG environment variable.

Note that if the CommonName is an invalid host name, it’s always ignored, regardless of GODEBUG settings. Invalid names include those with any characters other than letters, digits, hyphens and underscores, and those with empty labels or trailing dots.

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

When a Scanner is used with an invalid io.Reader that incorrectly returns a negative number from Read, the Scanner will no longer panic, but will instead return the new error ErrBadReadCount.

context

Creating a derived Context using a nil parent is now explicitly disallowed. Any attempt to do so with the WithValue, WithDeadline, or WithCancel functions will cause a panic.

crypto

The PrivateKey and PublicKey types in the crypto/rsa, crypto/ecdsa, and crypto/ed25519 packages now have an Equal method to compare keys for equivalence or to make type-safe interfaces for public keys. The method signature is compatible with go-cmp ’s definition of equality.

Hash now implements fmt.Stringer.

crypto/ecdsa

The new SignASN1 and VerifyASN1 functions allow generating and verifying ECDSA signatures in the standard ASN.1 DER encoding.

crypto/elliptic

The new MarshalCompressed and UnmarshalCompressed functions allow encoding and decoding NIST elliptic curve points in compressed format.

crypto/rsa

VerifyPKCS1v15 now rejects invalid short signatures with missing leading zeroes, according to RFC 8017.

crypto/tls

The new Dialer type and its DialContext method permit using a context to both connect and handshake with a TLS server.

The new VerifyConnection callback on the Config type allows custom verification logic for every connection. It has access to the ConnectionState which includes peer certificates, SCTs, and stapled OCSP responses.

Auto-generated session ticket keys are now automatically rotated every 24 hours, with a lifetime of 7 days, to limit their impact on forward secrecy.

Session ticket lifetimes in TLS 1.2 and earlier, where the session keys are reused for resumed connections, are now limited to 7 days, also to limit their impact on forward secrecy.

The client-side downgrade protection checks specified in RFC 8446 are now enforced. This has the potential to cause connection errors for clients encountering middleboxes that behave like unauthorized downgrade attacks.

SignatureScheme, CurveID, and ClientAuthType now implement fmt.Stringer.

The ConnectionState fields OCSPResponse and SignedCertificateTimestamps are now repopulated on client-side resumed connections.

tls.Conn now returns an opaque error on permanently broken connections, wrapping the temporary net.Error. To access the original net.Error, use errors.As (or errors.Unwrap) instead of a type assertion.

crypto/x509

If either the name on the certificate or the name being verified (with VerifyOptions.DNSName or VerifyHostname) are invalid, they will now be compared case-insensitively without further processing (without honoring wildcards or stripping trailing dots). Invalid names include those with any characters other than letters, digits, hyphens and underscores, those with empty labels, and names on certificates with trailing dots.

The new CreateRevocationList function and RevocationList type allow creating RFC 5280-compliant X.509 v2 Certificate Revocation Lists.

CreateCertificate now automatically generates the SubjectKeyId if the template is a CA and doesn’t explicitly specify one.

CreateCertificate now returns an error if the template specifies MaxPathLen but is not a CA.

On Unix systems other than macOS, the SSL_CERT_DIR environment variable can now be a colon-separated list.

On macOS, binaries are now always linked against Security.framework to extract the system trust roots, regardless of whether cgo is available. The resulting behavior should be more consistent with the OS verifier.

crypto/x509/pkix

Name.String now prints non-standard attributes from Names if ExtraNames is nil.

database/sql

The new DB.SetConnMaxIdleTime method allows removing a connection from the connection pool after it has been idle for a period of time, without regard to the total lifespan of the connection. The DBStats.MaxIdleTimeClosed field shows the total number of connections closed due to DB.SetConnMaxIdleTime.

The new Row.Err getter allows checking for query errors without calling Row.Scan.

database/sql/driver

The new Validator interface may be implemented by Conn to allow drivers to signal if a connection is valid or if it should be discarded.

debug/pe

The package now defines the IMAGE_FILE, IMAGE_SUBSYSTEM, and IMAGE_DLLCHARACTERISTICS constants used by the PE file format.

encoding/asn1

Marshal now sorts the components of SET OF according to X.690 DER.

Unmarshal now rejects tags and Object Identifiers which are not minimally encoded according to X.690 DER.

encoding/json

The package now has an internal limit to the maximum depth of nesting when decoding. This reduces the possibility that a deeply nested input could use large quantities of stack memory, or even cause a “goroutine stack exceeds limit” panic.

flag

When the flag package sees -h or -help, and those flags are not defined, it now prints a usage message. If the FlagSet was created with ExitOnError, FlagSet.Parse would then exit with a status of 2. In this release, the exit status for -h or -help has been changed to 0. In particular, this applies to the default handling of command line flags.

fmt

The printing verbs %#g and %#G now preserve trailing zeros for floating-point values.

go/format

The Source and Node functions now canonicalize number literal prefixes and exponents as part of formatting Go source code. This matches the behavior of the gofmt command as it was implemented since Go 1.13.

html/template

The package now uses Unicode escapes ( \uNNNN) in all JavaScript and JSON contexts. This fixes escaping errors in application/ld+json and application/json contexts.

io/ioutil

TempDir and TempFile now reject patterns that contain path separators. That is, calls such as ioutil.TempFile("/tmp", "../base*") will no longer succeed. This prevents unintended directory traversal.

math/big

The new Int.FillBytes method allows serializing to fixed-size pre-allocated byte slices.

math/cmplx

The functions in this package were updated to conform to the C99 standard (Annex G IEC 60559-compatible complex arithmetic) with respect to handling of special arguments such as infinity, NaN and signed zero.

net

If an I/O operation exceeds a deadline set by the Conn.SetDeadline, Conn.SetReadDeadline, or Conn.SetWriteDeadline methods, it will now return an error that is or wraps os.ErrDeadlineExceeded. This may be used to reliably detect whether an error is due to an exceeded deadline. Earlier releases recommended calling the Timeout method on the error, but I/O operations can return errors for which Timeout returns true although a deadline has not been exceeded.

The new Resolver.LookupIP method supports IP lookups that are both network-specific and accept a context.

net/http

Parsing is now stricter as a hardening measure against request smuggling attacks: non-ASCII white space is no longer trimmed like SP and HTAB, and support for the “ identityTransfer-Encoding was dropped.

net/http/httputil

ReverseProxy now supports not modifying the X-Forwarded-For header when the incoming Request.Header map entry for that field is nil.

When a Switching Protocol (like WebSocket) request handled by ReverseProxy is canceled, the backend connection is now correctly closed.

net/http/pprof

All profile endpoints now support a “ seconds ” parameter. When present, the endpoint profiles for the specified number of seconds and reports the difference. The meaning of the “ seconds ” parameter in the cpu profile and the trace endpoints is unchanged.

net/url

The new URL field RawFragment and method EscapedFragment provide detail about and control over the exact encoding of a particular fragment. These are analogous to RawPath and EscapedPath.

The new URL method Redacted returns the URL in string form with any password replaced with xxxxx.

os

If an I/O operation exceeds a deadline set by the File.SetDeadline, File.SetReadDeadline, or File.SetWriteDeadline methods, it will now return an error that is or wraps os.ErrDeadlineExceeded. This may be used to reliably detect whether an error is due to an exceeded deadline. Earlier releases recommended calling the Timeout method on the error, but I/O operations can return errors for which Timeout returns true although a deadline has not been exceeded.

Packages os and net now automatically retry system calls that fail with EINTR. Previously this led to spurious failures, which became more common in Go 1.14 with the addition of asynchronous preemption. Now this is handled transparently.

The os.File type now supports a ReadFrom method. This permits the use of the copy_file_range system call on some systems when using io.Copy to copy data from one os.File to another. A consequence is that io.CopyBuffer will not always use the provided buffer when copying to a os.File. If a program wants to force the use of the provided buffer, it can be done by writing io.CopyBuffer(struct{ io.Writer }{dst}, src, buf).

plugin

DWARF generation is now supported (and enabled by default) for -buildmode=plugin on macOS.

Building with -buildmode=plugin is now supported on freebsd/amd64.

reflect

Package reflect now disallows accessing methods of all non-exported fields, whereas previously it allowed accessing those of non-exported, embedded fields. Code that relies on the previous behavior should be updated to instead access the corresponding promoted method of the enclosing variable.

regexp

The new Regexp.SubexpIndex method returns the index of the first subexpression with the given name within the regular expression.

runtime

Several functions, including ReadMemStats and GoroutineProfile, no longer block if a garbage collection is in progress.

runtime/pprof

The goroutine profile now includes the profile labels associated with each goroutine at the time of profiling. This feature is not yet implemented for the profile reported with debug=2.

strconv

FormatComplex and ParseComplex are added for working with complex numbers.

FormatComplex converts a complex number into a string of the form (a+bi), where a and b are the real and imaginary parts.

ParseComplex converts a string into a complex number of a specified precision. ParseComplex accepts complex numbers in the format N+Ni.

sync

The new method Map.LoadAndDelete atomically deletes a key and returns the previous value if present.

The method Map.Delete is more efficient.

syscall

On Unix systems, functions that use SysProcAttr will now reject attempts to set both the Setctty and Foreground fields, as they both use the Ctty field but do so in incompatible ways. We expect that few existing programs set both fields.

Setting the Setctty field now requires that the Ctty field be set to a file descriptor number in the child process, as determined by the ProcAttr.Files field. Using a child descriptor always worked, but there were certain cases where using a parent file descriptor also happened to work. Some programs that set Setctty will need to change the value of Ctty to use a child descriptor number.

It is now possible to call system calls that return floating point values on windows/amd64.

testing

The testing.T type now has a Deadline method that reports the time at which the test binary will have exceeded its timeout.

A TestMain function is no longer required to call os.Exit. If a TestMain function returns, the test binary will call os.Exit with the value returned by m.Run.

The new methods T.TempDir and B.TempDir return temporary directories that are automatically cleaned up at the end of the test.

go test -v now groups output by test name, rather than printing the test name on each line.

text/template

JSEscape now consistently uses Unicode escapes ( \u00XX), which are compatible with JSON.

time

The new method Ticker.Reset supports changing the duration of a ticker.

When returning an error, ParseDuration now quotes the original value.

Update Feb 25, 2020 tracked by Updatify

go1.14 (released 2020-02-25)

Introduction to Go 1.14

The latest Go release, version 1.14, arrives six months after Go 1.13. 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.

Module support in the go command is now ready for production use, and we encourage all users to migrate to Go modules for dependency management. If you are unable to migrate due to a problem in the Go toolchain, please ensure that the problem has an open issue filed. (If the issue is not on the Go1.15 milestone, please let us know why it prevents you from migrating so that we can prioritize it appropriately.)

Changes to the language

Per the overlapping interfaces proposal, Go 1.14 now permits embedding of interfaces with overlapping method sets: methods from an embedded interface may have the same names and identical signatures as methods already present in the (embedding) interface. This solves problems that typically (but not exclusively) occur with diamond-shaped embedding graphs. Explicitly declared methods in an interface must remain unique, as before.

Ports

Darwin

Go 1.14 is the last release that will run on macOS 10.11 El Capitan. Go 1.15 will require macOS 10.12 Sierra or later.

Go 1.14 is the last Go release to support 32-bit binaries on macOS (the darwin/386 port). They are no longer supported by macOS, starting with macOS 10.15 (Catalina). Go continues to support the 64-bit darwin/amd64 port.

Go 1.14 will likely be the last Go release to support 32-bit binaries on iOS, iPadOS, watchOS, and tvOS (the darwin/arm port). Go continues to support the 64-bit darwin/arm64 port.

Windows

Go binaries on Windows now have DEP (Data Execution Prevention) enabled.

On Windows, creating a file via os.OpenFile with the os.O_CREATE flag, or via syscall.Open with the syscall.O_CREAT flag, will now create the file as read-only if the bit 0o200 (owner write permission) is not set in the permission argument. This makes the behavior on Windows more like that on Unix systems.

WebAssembly

JavaScript values referenced from Go via js.Value objects can now be garbage collected.

js.Value values can no longer be compared using the == operator, and instead must be compared using their Equal method.

js.Value now has IsUndefined, IsNull, and IsNaN methods.

RISC-V

Go 1.14 contains experimental support for 64-bit RISC-V on Linux ( GOOS=linux, GOARCH=riscv64). Be aware that performance, assembly syntax stability, and possibly correctness are a work in progress.

FreeBSD

Go now supports the 64-bit ARM architecture on FreeBSD 12.0 or later (the freebsd/arm64 port).

Native Client (NaCl)

As announced in the Go 1.13 release notes, Go 1.14 drops support for the Native Client platform ( GOOS=nacl).

Illumos

The runtime now respects zone CPU caps (the zone.cpu-cap resource control) for runtime.NumCPU and the default value of GOMAXPROCS.

Tools

Go command

Vendoring

When the main module contains a top-level vendor directory and its go.mod file specifies go 1.14 or higher, the go command now defaults to -mod=vendor for operations that accept that flag. A new value for that flag, -mod=mod, causes the go command to instead load modules from the module cache (as when no vendor directory is present).

When -mod=vendor is set (explicitly or by default), the go command now verifies that the main module’s vendor/modules.txt file is consistent with its go.mod file.

go list -m no longer silently omits transitive dependencies that do not provide packages in the vendor directory. It now fails explicitly if -mod=vendor is set and information is requested for a module not mentioned in vendor/modules.txt.

Flags

The go get command no longer accepts the -mod flag. Previously, the flag’s setting either was ignored or caused the build to fail.

-mod=readonly is now set by default when the go.mod file is read-only and no top-level vendor directory is present.

-modcacherw is a new flag that instructs the go command to leave newly-created directories in the module cache at their default permissions rather than making them read-only. The use of this flag makes it more likely that tests or other tools will accidentally add files not included in the module’s verified checksum. However, it allows the use of rm -rf (instead of go clean -modcache) to remove the module cache.

-modfile=file is a new flag that instructs the go command to read (and possibly write) an alternate go.mod file instead of the one in the module root directory. A file named go.mod must still be present in order to determine the module root directory, but it is not accessed. When -modfile is specified, an alternate go.sum file is also used: its path is derived from the -modfile flag by trimming the .mod extension and appending .sum.

Environment variables

GOINSECURE is a new environment variable that instructs the go command to not require an HTTPS connection, and to skip certificate validation, when fetching certain modules directly from their origins. Like the existing GOPRIVATE variable, the value of GOINSECURE is a comma-separated list of glob patterns.

Commands outside modules

When module-aware mode is enabled explicitly (by setting GO111MODULE=on), most module commands have more limited functionality if no go.mod file is present. For example, go build, go run, and other build commands can only build packages in the standard library and packages specified as .go files on the command line.

Previously, the go command would resolve each package path to the latest version of a module but would not record the module path or version. This resulted in slow, non-reproducible builds.

go get continues to work as before, as do go mod download and go list -m with explicit versions.

+incompatible versions

If the latest version of a module contains a go.mod file, go get will no longer upgrade to an incompatible major version of that module unless such a version is requested explicitly or is already required. go list also omits incompatible major versions for such a module when fetching directly from version control, but may include them if reported by a proxy.

go.mod file maintenance

go commands other than go mod tidy no longer remove a require directive that specifies a version of an indirect dependency that is already implied by other (transitive) dependencies of the main module.

go commands other than go mod tidy no longer edit the go.mod file if the changes are only cosmetic.

When -mod=readonly is set, go commands will no longer fail due to a missing go directive or an erroneous // indirect comment.

Module downloading

The go command now supports Subversion repositories in module mode.

The go command now includes snippets of plain-text error messages from module proxies and other HTTP servers. An error message will only be shown if it is valid UTF-8 and consists of only graphic characters and spaces.

Testing

go test -v now streams t.Log output as it happens, rather than at the end of all tests.

Runtime

This release improves the performance of most uses of defer to incur almost zero overhead compared to calling the deferred function directly. As a result, defer can now be used in performance-critical code without overhead concerns.

Goroutines are now asynchronously preemptible. As a result, loops without function calls no longer potentially deadlock the scheduler or significantly delay garbage collection. This is supported on all platforms except windows/arm, darwin/arm, js/wasm, and plan9/*.

A consequence of the implementation of preemption is that on Unix systems, including Linux and macOS systems, programs built with Go 1.14 will receive more signals than programs built with earlier releases. This means that programs that use packages like syscall or golang.org/x/sys/unix will see more slow system calls fail with EINTR errors. Those programs will have to handle those errors in some way, most likely looping to try the system call again. For more information about this see man 7 signal for Linux systems or similar documentation for other systems.

The page allocator is more efficient and incurs significantly less lock contention at high values of GOMAXPROCS. This is most noticeable as lower latency and higher throughput for large allocations being done in parallel and at a high rate.

Internal timers, used by time.After, time.Tick, net.Conn.SetDeadline, and friends, are more efficient, with less lock contention and fewer context switches. This is a performance improvement that should not cause any user visible changes.

Compiler

This release adds -d=checkptr as a compile-time option for adding instrumentation to check that Go code is following unsafe.Pointer safety rules dynamically. This option is enabled by default (except on Windows) with the -race or -msan flags, and can be disabled with -gcflags=all=-d=checkptr=0. Specifically, -d=checkptr checks the following:

  1. When converting unsafe.Pointer to *T, the resulting pointer must be aligned appropriately for T.
  2. If the result of pointer arithmetic points into a Go heap object, one of the unsafe.Pointer -typed operands must point into the same object.

Using -d=checkptr is not currently recommended on Windows because it causes false alerts in the standard library.

The compiler can now emit machine-readable logs of key optimizations using the -json flag, including inlining, escape analysis, bounds-check elimination, and nil-check elimination.

Detailed escape analysis diagnostics ( -m=2) now work again. This had been dropped from the new escape analysis implementation in the previous release.

All Go symbols in macOS binaries now begin with an underscore, following platform conventions.

This release includes experimental support for compiler-inserted coverage instrumentation for fuzzing. See issue 14565 for more details. This API may change in future releases.

Bounds check elimination now uses information from slice creation and can eliminate checks for indexes with types smaller than int.

Standard library

New byte sequence hashing package

Go 1.14 includes a new package, hash/maphash, which provides hash functions on byte sequences. These hash functions are intended to be used to implement hash tables or other data structures that need to map arbitrary strings or byte sequences to a uniform distribution on unsigned 64-bit integers.

The hash functions are collision-resistant but not cryptographically secure.

The hash value of a given byte sequence is consistent within a single process, but will be different in different processes.

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/tls

Support for SSL version 3.0 (SSLv3) has been removed. Note that SSLv3 is the cryptographically broken protocol predating TLS.

TLS 1.3 can’t be disabled via the GODEBUG environment variable anymore. Use the Config.MaxVersion field to configure TLS versions.

When multiple certificate chains are provided through the Config.Certificates field, the first one compatible with the peer is now automatically selected. This allows for example providing an ECDSA and an RSA certificate, and letting the package automatically select the best one. Note that the performance of this selection is going to be poor unless the Certificate.Leaf field is set. The Config.NameToCertificate field, which only supports associating a single certificate with a give name, is now deprecated and should be left as nil. Similarly the Config.BuildNameToCertificate method, which builds the NameToCertificate field from the leaf certificates, is now deprecated and should not be called.

The new CipherSuites and InsecureCipherSuites functions return a list of currently implemented cipher suites. The new CipherSuiteName function returns a name for a cipher suite ID.

The new (*ClientHelloInfo).SupportsCertificate and (*CertificateRequestInfo).SupportsCertificate methods expose whether a peer supports a certain certificate.

The tls package no longer supports the legacy Next Protocol Negotiation (NPN) extension and now only supports ALPN. In previous releases it supported both. There are no API changes and applications should function identically as before. Most other clients and servers have already removed NPN support in favor of the standardized ALPN.

RSA-PSS signatures are now used when supported in TLS 1.2 handshakes. This won’t affect most applications, but custom Certificate.PrivateKey implementations that don’t support RSA-PSS signatures will need to use the new Certificate.SupportedSignatureAlgorithms field to disable them.

Config.Certificates and Config.GetCertificate can now both be nil if Config.GetConfigForClient is set. If the callbacks return neither certificates nor an error, the unrecognized_name is now sent.

The new CertificateRequestInfo.Version field provides the TLS version to client certificates callbacks.

The new TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 and TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 constants use the final names for the cipher suites previously referred to as TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305 and TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305.

crypto/x509

Certificate.CreateCRL now supports Ed25519 issuers.

debug/dwarf

The debug/dwarf package now supports reading DWARF version 5.

The new method (*Data).AddSection supports adding arbitrary new DWARF sections from the input file to the DWARF Data.

The new method (*Reader).ByteOrder returns the byte order of the current compilation unit. This may be used to interpret attributes that are encoded in the native ordering, such as location descriptions.

The new method (*LineReader).Files returns the file name table from a line reader. This may be used to interpret the value of DWARF attributes such as AttrDeclFile.

encoding/asn1

Unmarshal now supports ASN.1 string type BMPString, represented by the new TagBMPString constant.

encoding/json

The Decoder type supports a new method InputOffset that returns the input stream byte offset of the current decoder position.

Compact no longer escapes the U+2028 and U+2029 characters, which was never a documented feature. For proper escaping, see HTMLEscape.

Number no longer accepts invalid numbers, to follow the documented behavior more closely. If a program needs to accept invalid numbers like the empty string, consider wrapping the type with Unmarshaler.

Unmarshal can now support map keys with string underlying type which implement encoding.TextUnmarshaler.

go/build

The Context type has a new field Dir which may be used to set the working directory for the build. The default is the current directory of the running process. In module mode, this is used to locate the main module.

go/doc

The new function NewFromFiles computes package documentation from a list of *ast.File ’s and associates examples with the appropriate package elements. The new information is available in a new Examples field in the Package, Type, and Func types, and a new Suffix field in the Example type.

io/ioutil

TempDir can now create directories whose names have predictable prefixes and suffixes. As with TempFile, if the pattern contains a ‘’, the random string replaces the last ‘’.

log

The new Lmsgprefix flag may be used to tell the logging functions to emit the optional output prefix immediately before the log message rather than at the start of the line.

math

The new FMA function computes x*y+z in floating point with no intermediate rounding of the x*y computation. Several architectures implement this computation using dedicated hardware instructions for additional performance.

math/big

The GCD method now allows the inputs a and b to be zero or negative.

math/bits

The new functions Rem, Rem32, and Rem64 support computing a remainder even when the quotient overflows.

mime

The default type of .js and .mjs files is now text/javascript rather than application/javascript. This is in accordance with an IETF draft that treats application/javascript as obsolete.

mime/multipart

The new Reader method NextRawPart supports fetching the next MIME part without transparently decoding quoted-printable data.

net/http

The new Header method Values can be used to fetch all values associated with a canonicalized key.

The new Transport field DialTLSContext can be used to specify an optional dial function for creating TLS connections for non-proxied HTTPS requests. This new field can be used instead of DialTLS, which is now considered deprecated; DialTLS will continue to work, but new code should use DialTLSContext, which allows the transport to cancel dials as soon as they are no longer needed.

On Windows, ServeFile now correctly serves files larger than 2GB.

net/http/httptest

The new Server field EnableHTTP2 supports enabling HTTP/2 on the test server.

net/textproto

The new MIMEHeader method Values can be used to fetch all values associated with a canonicalized key.

net/url

When parsing of a URL fails (for example by Parse or ParseRequestURI), the resulting Error message will now quote the unparsable URL. This provides clearer structure and consistency with other parsing errors.

os/signal

On Windows, the CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, and CTRL_SHUTDOWN_EVENT events now generate a syscall.SIGTERM signal, similar to how Control-C and Control-Break generate a syscall.SIGINT signal.

plugin

The plugin package now supports freebsd/amd64.

reflect

StructOf now supports creating struct types with unexported fields, by setting the PkgPath field in a StructField element.

runtime

runtime.Goexit can no longer be aborted by a recursive panic / recover.

On macOS, SIGPIPE is no longer forwarded to signal handlers installed before the Go runtime is initialized. This is necessary because macOS delivers SIGPIPE to the main thread rather than the thread writing to the closed pipe.

runtime/pprof

The generated profile no longer includes the pseudo-PCs used for inline marks. Symbol information of inlined functions is encoded in the format the pprof tool expects. This is a fix for the regression introduced during recent releases.

strconv

The NumError type now has an Unwrap method that may be used to retrieve the reason that a conversion failed. This supports using NumError values with errors.Is to see if the underlying error is strconv.ErrRange or strconv.ErrSyntax.

sync

Unlocking a highly contended Mutex now directly yields the CPU to the next goroutine waiting for that Mutex. This significantly improves the performance of highly contended mutexes on high CPU count machines.

testing

The testing package now supports cleanup functions, called after a test or benchmark has finished, by calling T.Cleanup or B.Cleanup respectively.

text/template

The text/template package now correctly reports errors when a parenthesized argument is used as a function. This most commonly shows up in erroneous cases like {{if (eq .F "a") or (eq .F "b")}}. This should be written as {{if or (eq .F "a") (eq .F "b")}}. The erroneous case never worked as expected, and will now be reported with an error can't give argument to non-function.

JSEscape now escapes the & and = characters to mitigate the impact of its output being misused in HTML contexts.

unicode

The unicode package and associated support throughout the system has been upgraded from Unicode 11.0 to Unicode 12.0, which adds 554 new characters, including four new scripts, and 61 new emoji.

Update Sep 3, 2019 tracked by Updatify

go1.13 (released 2019-09-03)

Introduction to Go 1.13

The latest Go release, version 1.13, arrives six months after Go 1.12. 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.

As of Go 1.13, the go command by default downloads and authenticates modules using the Go module mirror and Go checksum database run by Google. See https://proxy.golang.org/privacy for privacy information about these services and the go command documentation for configuration details including how to disable the use of these servers or use different ones. If you depend on non-public modules, see the documentation for configuring your environment.

Changes to the language

Per the number literal proposal, Go 1.13 supports a more uniform and modernized set of number literal prefixes.

  • Binary integer literals: The prefix 0b or 0B indicates a binary integer literal such as 0b1011.
  • Octal integer literals: The prefix 0o or 0O indicates an octal integer literal such as 0o660. The existing octal notation indicated by a leading 0 followed by octal digits remains valid.
  • Hexadecimal floating point literals: The prefix 0x or 0X may now be used to express the mantissa of a floating-point number in hexadecimal format such as 0x1.0p-1021. A hexadecimal floating-point number must always have an exponent, written as the letter p or P followed by an exponent in decimal. The exponent scales the mantissa by 2 to the power of the exponent.
  • Imaginary literals: The imaginary suffix i may now be used with any (binary, decimal, hexadecimal) integer or floating-point literal.
  • Digit separators: The digits of any number literal may now be separated (grouped) using underscores, such as in 1_000_000, 0b_1010_0110, or 3.1415_9265. An underscore may appear between any two digits or the literal prefix and the first digit.

Per the signed shift counts proposal Go 1.13 removes the restriction that a shift count must be unsigned. This change eliminates the need for many artificial uint conversions, solely introduced to satisfy this (now removed) restriction of the << and >> operators.

These language changes were implemented by changes to the compiler, and corresponding internal changes to the library packages go/scanner and text/scanner (number literals), and go/types (signed shift counts).

If your code uses modules and your go.mod files specifies a language version, be sure it is set to at least 1.13 to get access to these language changes. You can do this by editing the go.mod file directly, or you can run go mod edit -go=1.13.

Ports

Go 1.13 is the last release that will run on Native Client (NaCl).

For GOARCH=wasm, the new environment variable GOWASM takes a comma-separated list of experimental features that the binary gets compiled with. The valid values are documented here.

AIX

AIX on PPC64 ( aix/ppc64) now supports cgo, external linking, and the c-archive and pie build modes.

Android

Go programs are now compatible with Android 10.

Darwin

As announced in the Go 1.12 release notes, Go 1.13 now requires macOS 10.11 El Capitan or later; support for previous versions has been discontinued.

FreeBSD

As announced in the Go 1.12 release notes, Go 1.13 now requires FreeBSD 11.2 or later; support for previous versions has been discontinued. FreeBSD 12.0 or later requires a kernel with the COMPAT_FREEBSD11 option set (this is the default).

Illumos

Go now supports Illumos with GOOS=illumos. The illumos build tag implies the solaris build tag.

Windows

The Windows version specified by internally-linked Windows binaries is now Windows 7 rather than NT 4.0. This was already the minimum required version for Go, but can affect the behavior of system calls that have a backwards-compatibility mode. These will now behave as documented. Externally-linked binaries (any program using cgo) have always specified a more recent Windows version.

Tools

Modules

Environment variables

The GO111MODULE environment variable continues to default to auto, but the auto setting now activates the module-aware mode of the go command whenever the current working directory contains, or is below a directory containing, a go.mod file — even if the current directory is within GOPATH/src. This change simplifies the migration of existing code within GOPATH/src and the ongoing maintenance of module-aware packages alongside non-module-aware importers.

The new GOPRIVATE environment variable indicates module paths that are not publicly available. It serves as the default value for the lower-level GONOPROXY and GONOSUMDB variables, which provide finer-grained control over which modules are fetched via proxy and verified using the checksum database.

The GOPROXY environment variable may now be set to a comma-separated list of proxy URLs or the special token direct, and its default value is now https://proxy.golang.org,direct. When resolving a package path to its containing module, the go command will try all candidate module paths on each proxy in the list in succession. An unreachable proxy or HTTP status code other than 404 or 410 terminates the search without consulting the remaining proxies.

The new GOSUMDB environment variable identifies the name, and optionally the public key and server URL, of the database to consult for checksums of modules that are not yet listed in the main module’s go.sum file. If GOSUMDB does not include an explicit URL, the URL is chosen by probing the GOPROXY URLs for an endpoint indicating support for the checksum database, falling back to a direct connection to the named database if it is not supported by any proxy. If GOSUMDB is set to off, the checksum database is not consulted and only the existing checksums in the go.sum file are verified.

Users who cannot reach the default proxy and checksum database (for example, due to a firewalled or sandboxed configuration) may disable their use by setting GOPROXY to direct, and/or GOSUMDB to off. go env -w can be used to set the default values for these variables independent of platform:

go env -w GOPROXY=direct
go env -w GOSUMDB=off

go get

In module-aware mode, go get with the -u flag now updates a smaller set of modules that is more consistent with the set of packages updated by go get -u in GOPATH mode. go get -u continues to update the modules and packages named on the command line, but additionally updates only the modules containing the packages imported by the named packages, rather than the transitive module requirements of the modules containing the named packages.

Note in particular that go get -u (without additional arguments) now updates only the transitive imports of the package in the current directory. To instead update all of the packages transitively imported by the main module (including test dependencies), use go get -u all.

As a result of the above changes to go get -u, the go get subcommand no longer supports the -m flag, which caused go get to stop before loading packages. The -d flag remains supported, and continues to cause go get to stop after downloading the source code needed to build dependencies of the named packages.

By default, go get -u in module mode upgrades only non-test dependencies, as in GOPATH mode. It now also accepts the -t flag, which (as in GOPATH mode) causes go get to include the packages imported by tests of the packages named on the command line.

In module-aware mode, the go get subcommand now supports the version suffix @patch. The @patch suffix indicates that the named module, or module containing the named package, should be updated to the highest patch release with the same major and minor versions as the version found in the build list.

If a module passed as an argument to go get without a version suffix is already required at a newer version than the latest released version, it will remain at the newer version. This is consistent with the behavior of the -u flag for module dependencies. This prevents unexpected downgrades from pre-release versions. The new version suffix @upgrade explicitly requests this behavior. @latest explicitly requests the latest version regardless of the current version.

Version validation

When extracting a module from a version control system, the go command now performs additional validation on the requested version string.

The +incompatible version annotation bypasses the requirement of semantic import versioning for repositories that predate the introduction of modules. The go command now verifies that such a version does not include an explicit go.mod file.

The go command now verifies the mapping between pseudo-versions and version-control metadata. Specifically:

  • The version prefix must be of the form vX.0.0, or derived from a tag on an ancestor of the named revision, or derived from a tag that includes build metadata on the named revision itself.
  • The date string must match the UTC timestamp of the revision.
  • The short name of the revision must use the same number of characters as what the go command would generate. (For SHA-1 hashes as used by git, a 12-digit prefix.)

If a require directive in the main module uses an invalid pseudo-version, it can usually be corrected by redacting the version to just the commit hash and re-running a go command, such as go list -m all or go mod tidy. For example,

require github.com/docker/docker v1.14.0-0.20190319215453-e7b5f7dbe98c

can be redacted to

require github.com/docker/docker e7b5f7dbe98c

which currently resolves to

require github.com/docker/docker v0.7.3-0.20190319215453-e7b5f7dbe98c

If one of the transitive dependencies of the main module requires an invalid version or pseudo-version, the invalid version can be replaced with a valid one using a replace directive in the go.mod file of the main module. If the replacement is a commit hash, it will be resolved to the appropriate pseudo-version as above. For example,

replace github.com/docker/docker v1.14.0-0.20190319215453-e7b5f7dbe98c => github.com/docker/docker e7b5f7dbe98c

currently resolves to

replace github.com/docker/docker v1.14.0-0.20190319215453-e7b5f7dbe98c => github.com/docker/docker v0.7.3-0.20190319215453-e7b5f7dbe98c

Go command

The go env command now accepts a -w flag to set the per-user default value of an environment variable recognized by the go command, and a corresponding -u flag to unset a previously-set default. Defaults set via go env -w are stored in the go/env file within os.UserConfigDir().

The go version command now accepts arguments naming executables and directories. When invoked on an executable, go version prints the version of Go used to build the executable. If the -m flag is used, go version prints the executable’s embedded module version information, if available. When invoked on a directory, go version prints information about executables contained in the directory and its subdirectories.

The new go build flag -trimpath removes all file system paths from the compiled executable, to improve build reproducibility.

If the -o flag passed to go build refers to an existing directory, go build will now write executable files within that directory for main packages matching its package arguments.

The go build flag -tags now takes a comma-separated list of build tags, to allow for multiple tags in GOFLAGS. The space-separated form is deprecated but still recognized and will be maintained.

go generate now sets the generate build tag so that files may be searched for directives but ignored during build.

As announced in the Go 1.12 release notes, binary-only packages are no longer supported. Building a binary-only package (marked with a //go:binary-only-package comment) now results in an error.

Compiler toolchain

The compiler has a new implementation of escape analysis that is more precise. For most Go code should be an improvement (in other words, more Go variables and expressions allocated on the stack instead of heap). However, this increased precision may also break invalid code that happened to work before (for example, code that violates the unsafe.Pointer safety rules). If you notice any regressions that appear related, the old escape analysis pass can be re-enabled with go build -gcflags=all=-newescape=false. The option to use the old escape analysis will be removed in a future release.

The compiler no longer emits floating point or complex constants to go_asm.h files. These have always been emitted in a form that could not be used as numeric constant in assembly code.

Assembler

The assembler now supports many of the atomic instructions introduced in ARM v8.1.

gofmt

gofmt (and with that go fmt) now canonicalizes number literal prefixes and exponents to use lower-case letters, but leaves hexadecimal digits alone. This improves readability when using the new octal prefix ( 0O becomes 0o), and the rewrite is applied consistently. gofmt now also removes unnecessary leading zeroes from a decimal integer imaginary literal. (For backwards-compatibility, an integer imaginary literal starting with 0 is considered a decimal, not an octal number. Removing superfluous leading zeroes avoids potential confusion.) For instance, 0B1010, 0XabcDEF, 0O660, 1.2E3, and 01i become 0b1010, 0xabcDEF, 0o660, 1.2e3, and 1i after applying gofmt.

godoc and go doc

The godoc webserver is no longer included in the main binary distribution. To run the godoc webserver locally, manually install it first:

go get golang.org/x/tools/cmd/godoc
godoc

The go doc command now always includes the package clause in its output, except for commands. This replaces the previous behavior where a heuristic was used, causing the package clause to be omitted under certain conditions.

Runtime

Out of range panic messages now include the index that was out of bounds and the length (or capacity) of the slice. For example, s[3] on a slice of length 1 will panic with “runtime error: index out of range [3] with length 1”.

This release improves performance of most uses of defer by 30%.

The runtime is now more aggressive at returning memory to the operating system to make it available to co-tenant applications. Previously, the runtime could retain memory for five or more minutes following a spike in the heap size. It will now begin returning it promptly after the heap shrinks. However, on many OSes, including Linux, the OS itself reclaims memory lazily, so process RSS will not decrease until the system is under memory pressure.

Standard library

TLS 1.3

As announced in Go 1.12, Go 1.13 enables support for TLS 1.3 in the crypto/tls package by default. It can be disabled by adding the value tls13=0 to the GODEBUG environment variable. The opt-out will be removed in Go 1.14.

See the Go 1.12 release notes for important compatibility information.

crypto/ed25519

The new crypto/ed25519 package implements the Ed25519 signature scheme. This functionality was previously provided by the golang.org/x/crypto/ed25519 package, which becomes a wrapper for crypto/ed25519 when used with Go 1.13+.

Error wrapping

Go 1.13 contains support for error wrapping, as first proposed in the Error Values proposal and discussed on the associated issue.

An error e can wrap another error w by providing an Unwrap method that returns w. Both e and w are available to programs, allowing e to provide additional context to w or to reinterpret it while still allowing programs to make decisions based on w.

To support wrapping, fmt.Errorf now has a %w verb for creating wrapped errors, and three new functions in the errors package ( errors.Unwrap, errors.Is and errors.As) simplify unwrapping and inspecting wrapped errors.

For more information, read the errors package documentation, or see the Error Value FAQ. There will soon be a blog post as well.

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.

bytes

The new ToValidUTF8 function returns a copy of a given byte slice with each run of invalid UTF-8 byte sequences replaced by a given slice.

context

The formatting of contexts returned by WithValue no longer depends on fmt and will not stringify in the same way. Code that depends on the exact previous stringification might be affected.

crypto/tls

Support for SSL version 3.0 (SSLv3) is now deprecated and will be removed in Go 1.14. Note that SSLv3 is the cryptographically broken protocol predating TLS.

SSLv3 was always disabled by default, other than in Go 1.12, when it was mistakenly enabled by default server-side. It is now again disabled by default. (SSLv3 was never supported client-side.)

Ed25519 certificates are now supported in TLS versions 1.2 and 1.3.

crypto/x509

Ed25519 keys are now supported in certificates and certificate requests according to RFC 8410, as well as by the ParsePKCS8PrivateKey, MarshalPKCS8PrivateKey, and ParsePKIXPublicKey functions.

The paths searched for system roots now include /etc/ssl/cert.pem to support the default location in Alpine Linux 3.7+.

database/sql

The new NullTime type represents a time.Time that may be null.

The new NullInt32 type represents an int32 that may be null.

debug/dwarf

The Data.Type method no longer panics if it encounters an unknown DWARF tag in the type graph. Instead, it represents that component of the type with an UnsupportedType object.

errors

The new function As finds the first error in a given error’s chain (sequence of wrapped errors) that matches a given target’s type, and if so, sets the target to that error value.

The new function Is reports whether a given error value matches an error in another’s chain.

The new function Unwrap returns the result of calling Unwrap on a given error, if one exists.

fmt

The printing verbs %x and %X now format floating-point and complex numbers in hexadecimal notation, in lower-case and upper-case respectively.

The new printing verb %O formats integers in base 8, emitting the 0o prefix.

The scanner now accepts hexadecimal floating-point values, digit-separating underscores and leading 0b and 0o prefixes. See the Changes to the language for details.

The Errorf function has a new verb, %w, whose operand must be an error. The error returned from Errorf will have an Unwrap method which returns the operand of %w.

go/scanner

The scanner has been updated to recognize the new Go number literals, specifically binary literals with 0b / 0B prefix, octal literals with 0o / 0O prefix, and floating-point numbers with hexadecimal mantissa. The imaginary suffix i may now be used with any number literal, and underscores may be used as digit separators for grouping. See the Changes to the language for details.

go/types

The type-checker has been updated to follow the new rules for integer shifts. See the Changes to the language for details.

html/template

When using a <script> tag with “module” set as the type attribute, code will now be interpreted as JavaScript module script.

log

The new Writer function returns the output destination for the standard logger.

math/big

The new Rat.SetUint64 method sets the Rat to a uint64 value.

For Float.Parse, if base is 0, underscores may be used between digits for readability. See the Changes to the language for details.

For Int.SetString, if base is 0, underscores may be used between digits for readability. See the Changes to the language for details.

Rat.SetString now accepts non-decimal floating point representations.

math/bits

The execution time of Add, Sub, Mul, RotateLeft, and ReverseBytes is now guaranteed to be independent of the inputs.

net

On Unix systems where use-vc is set in resolv.conf, TCP is used for DNS resolution.

The new field ListenConfig.KeepAlive specifies the keep-alive period for network connections accepted by the listener. If this field is 0 (the default) TCP keep-alives will be enabled. To disable them, set it to a negative value.

Note that the error returned from I/O on a connection that was closed by a keep-alive timeout will have a Timeout method that returns true if called. This can make a keep-alive error difficult to distinguish from an error returned due to a missed deadline as set by the SetDeadline method and similar methods. Code that uses deadlines and checks for them with the Timeout method or with os.IsTimeout may want to disable keep-alives, or use errors.Is(syscall.ETIMEDOUT) (on Unix systems) which will return true for a keep-alive timeout and false for a deadline timeout.

net/http

The new fields Transport.WriteBufferSize and Transport.ReadBufferSize allow one to specify the sizes of the write and read buffers for a Transport. If either field is zero, a default size of 4KB is used.

The new field Transport.ForceAttemptHTTP2 controls whether HTTP/2 is enabled when a non-zero Dial, DialTLS, or DialContext func or TLSClientConfig is provided.

Transport.MaxConnsPerHost now works properly with HTTP/2.

TimeoutHandler ’s ResponseWriter now implements the Pusher interface.

The StatusCode 103 "Early Hints" has been added.

Transport now uses the Request.Body ’s io.ReaderFrom implementation if available, to optimize writing the body.

On encountering unsupported transfer-encodings, http.Server now returns a “501 Unimplemented” status as mandated by the HTTP specification RFC 7230 Section 3.3.1.

The new Server fields BaseContext and ConnContext allow finer control over the Context values provided to requests and connections.

http.DetectContentType now correctly detects RAR signatures, and can now also detect RAR v5 signatures.

The new Header method Clone returns a copy of the receiver.

A new function NewRequestWithContext has been added and it accepts a Context that controls the entire lifetime of the created outgoing Request, suitable for use with Client.Do and Transport.RoundTrip.

The Transport no longer logs errors when servers gracefully shut down idle connections using a "408 Request Timeout" response.

os

The new UserConfigDir function returns the default directory to use for user-specific configuration data.

If a File is opened using the O_APPEND flag, its WriteAt method will always return an error.

os/exec

On Windows, the environment for a Cmd always inherits the %SYSTEMROOT% value of the parent process unless the Cmd.Env field includes an explicit value for it.

reflect

The new Value.IsZero method reports whether a Value is the zero value for its type.

The MakeFunc function now allows assignment conversions on returned values, instead of requiring exact type match. This is particularly useful when the type being returned is an interface type, but the value actually returned is a concrete value implementing that type.

runtime

Tracebacks, runtime.Caller, and runtime.Callers now refer to the function that initializes the global variables of PKG as PKG.init instead of PKG.init.ializers.

strconv

For strconv.ParseFloat, strconv.ParseInt and strconv.ParseUint, if base is 0, underscores may be used between digits for readability. See the Changes to the language for details.

strings

The new ToValidUTF8 function returns a copy of a given string with each run of invalid UTF-8 byte sequences replaced by a given string.

sync

The fast paths of Mutex.Lock, Mutex.Unlock, RWMutex.Lock, RWMutex.RUnlock, and Once.Do are now inlined in their callers. For the uncontended cases on amd64, these changes make Once.Do twice as fast, and the Mutex / RWMutex methods up to 10% faster.

Large Pool no longer increase stop-the-world pause times.

Pool no longer needs to be completely repopulated after every GC. It now retains some objects across GCs, as opposed to releasing all objects, reducing load spikes for heavy users of Pool.

syscall

Uses of _getdirentries64 have been removed from Darwin builds, to allow Go binaries to be uploaded to the macOS App Store.

The new ProcessAttributes and ThreadAttributes fields in SysProcAttr have been introduced for Windows, exposing security settings when creating new processes.

EINVAL is no longer returned in zero Chmod mode on Windows.

Values of type Errno can be tested against error values in the os package, like ErrExist, using errors.Is.

syscall/js

TypedArrayOf has been replaced by CopyBytesToGo and CopyBytesToJS for copying bytes between a byte slice and a Uint8Array.

testing

When running benchmarks, B.N is no longer rounded.

The new method B.ReportMetric lets users report custom benchmark metrics and override built-in metrics.

Testing flags are now registered in the new Init function, which is invoked by the generated main function for the test. As a result, testing flags are now only registered when running a test binary, and packages that call flag.Parse during package initialization may cause tests to fail.

text/scanner

The scanner has been updated to recognize the new Go number literals, specifically binary literals with 0b / 0B prefix, octal literals with 0o / 0O prefix, and floating-point numbers with hexadecimal mantissa. Also, the new AllowDigitSeparators mode allows number literals to contain underscores as digit separators (off by default for backwards-compatibility). See the Changes to the language for details.

text/template

The new slice function returns the result of slicing its first argument by the following arguments.

time

Day-of-year is now supported by Format and Parse.

The new Duration methods Microseconds and Milliseconds return the duration as an integer count of their respectively named units.

unicode

The unicode package and associated support throughout the system has been upgraded from Unicode 10.0 to Unicode 11.0, which adds 684 new characters, including seven new scripts, and 66 new emoji.