前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Go版本16-20迭代了什么?

Go版本16-20迭代了什么?

原创
作者头像
COY_fenfei
发布2023-06-07 16:49:40
5900
发布2023-06-07 16:49:40
举报
文章被收录于专栏:COYCOYCOY

序言

为什么要了解版本信息?

  1. 版本更新会引入新的语言特性和改进,可以让开发者更加高效地编写代码和解决问题。
  2. 版本更新可能会更改标准库、包和API的行为,需要开发者进行适应和更新。
  3. 了解版本更新可以帮助开发者更好地利用Go语言的性能和功能,提高代码的质量和效率。
  4. 版本更新通常会修复漏洞和错误,提高代码的安全性和可靠性。
  5. Go语言社区和生态系统的发展也与版本更新密切相关,了解版本更新可以帮助开发者更好地了解Go语言的生态环境和未来发展方向

如何全面的了解版本信息?

通过Go官网的The Go Blog可以检索出每个版本的发布信息,以及详细的版本说明。本文参考以下文章:

  1. Go 1.16 Release Notes
  2. Go 1.17 Release Notes
  3. Go 1.18 Release Notes
  4. Go 1.19 Release Notes
  5. Go 1.20 Release Notes

为了防止内容因为作者在翻译时理解错误,因此大部分会从官网原文摘取出来,其中也只会摘取一些重点的更新。

一、 Go1.16

发布时间

18 February 2021

版本概要

  1. new embed package provides access to files embedded at compile time using the new//go:embed directive.
  2. addsmacOS ARM64 support.
  3. requires use of Go modules by default.
  4. builds that are up to 25% faster and use as much as 15% less memory.

版本重点内容

Modules
  • Module-aware mode is enabled by default, regardless of whether ago.modfile is present in the current working directory or a parent directory.
  • Build commands like go build and go test no longer modify go.mod and go.sum by default.
  • go install now accepts arguments with version suffixes (for example, go install example.com/cmd@v1.0.0).
  • retract directives may now be used in a go.mod file to indicate that certain published versions of the module should not be used by other modules.
  • The go mod vendor and go mod tidy subcommands now accept the -e flag, which instructs them to proceed despite errors in resolving missing packages.
  • The go command now ignores requirements on module versions excluded by exclude directives in the main module. Previously, the go command used the next version higher than an excluded version, but that version could change over time, resulting in non-reproducible builds.
  • In module mode, the go command now disallows import paths that include non-ASCII characters or path elements with a leading dot character (.). Module paths with these characters were already disallowed (see Module paths and versions), so this change affects only paths within module subdirectories.
Embedding Files

The go command now supports including static files and file trees as part of the final executable, using the new//go:embeddirective.

GOVCS environment variable

GOVCS is a new environment variable that limits which version control tools the go command may use to download source code.

Cgo

The cgo tool will no longer try to translate C struct bitfields into Go struct fields, even if their size can be represented in Go. The order in which C bitfields appear in memory is implementation dependent, so in some cases the cgo tool produced results that were silently incorrect.

Runtime

  • The new runtime/metrics package introduces a stable interface for reading implementation-defined metrics from the Go runtime. It supersedes existing functions like runtime.ReadMemStats and debug.GCStats and is significantly more general and efficient.
  • Setting the GODEBUG environment variable to inittrace=1 now causes the runtime to emit a single line to standard error for each package init, summarizing its execution time and memory allocation. This trace can be used to find bottlenecks or regressions in Go startup performance. The GODEBUG documentation describes the format.
  • On Linux, the runtime now defaults to releasing memory to the operating system promptly (using MADV_DONTNEED), rather than lazily when the operating system is under memory pressure (using MADV_FREE). This means process-level memory statistics like RSS will more accurately reflect the amount of physical memory being used by Go processes. Systems that are currently using GODEBUG=madvdontneed=1 to improve memory monitoring behavior no longer need to set this environment variable.
  • Go 1.16 fixes a discrepancy between the race detector and the Go memory model. The race detector now more precisely follows the channel synchronization rules of the memory model. As a result, the detector may now report races it previously missed.

Linker

This release includes additional improvements to the Go linker, reducing linker resource usage (both time and memory) and improving code robustness/maintainability. These changes form the second half of a two-release project to modernize the Go linker.

Core library

1. Embedded Files

The new embed package provides access to files embedded in the program during compilation using the new //go:embed directive.

2. File Systems

The new io/fs package defines the fs.FS interface, an abstraction for read-only trees of files. The standard library packages have been adapted to make use of the interface as appropriate.

On the producer side of the interface, the new embed.FS type implements fs.FS, as does zip.Reader. The new os.DirFS function provides an implementation of fs.FS backed by a tree of operating system files.

3. Deprecation of io/ioutil

The io/ioutil package has turned out to be a poorly defined and hard to understand collection of things. All functionality provided by the package has been moved to other packages.

二、 Go1.17

发布时间

16 August 2021

版本概要

  1. brings additional improvements to the compiler, namely a new way of passing function arguments and results.
  2. adds support for the 64-bit ARM architecture on Windows.
  3. introduced pruned module graphs.
  4. three small changes to the language.

版本重点内容

Changes to the language

  • Conversions from slice to array pointer: An expression s of type []T may now be converted to array pointer type *[N]T. If a is the result of such a conversion, then corresponding indices that are in range refer to the same underlying elements: &a[i] == &s[i] for 0 <= i < N. The conversion panics if len(s) is less than N.
  • unsafe.Add: unsafe.Add(ptr, len) adds len to ptr and returns the updated pointer unsafe.Pointer(uintptr(ptr) + uintptr(len)).
  • unsafe.Slice: For expression ptr of type *T, unsafe.Slice(ptr, len) returns a slice of type []T whose underlying array starts at ptr and whose length and capacity are len.
Pruned module graphs in go 1.17 modules

Pruned module graphs in go 1.17 modules,If a module specifies go1.17 or higher, the module graph includes only the immediate dependencies of other go1.17 modules, not their full transitive dependencies.

Module deprecation comments

Module authors may deprecate a module by adding a // Deprecated: comment to go.mod, then tagging a new version. go get now prints a warning if a module needed to build packages named on the command line is deprecated. go list -m -u prints deprecations for all dependencies (use -f or -json to show the full message). The go command considers different major versions to be distinct modules, so this mechanism may be used, for example, to provide users with migration instructions for a new major version.

Compiler

Go 1.17 implements a new way of passing function arguments and results using registers instead of the stack. Benchmarks for a representative set of Go packages and programs show performance improvements of about 5%, and a typical reduction in binary size of about 2%. This is currently enabled for Linux, macOS, and Windows on the 64-bit x86 architecture (the linux/amd64, darwin/amd64, and windows/amd64 ports).

Linker

When the linker uses external linking mode, which is the default when linking a program that uses cgo, and the linker is invoked with a -I option, the option will now be passed to the external linker as a -Wl,--dynamic-linker option.

Core library

  • The runtime/cgo package now provides a new facility that allows to turn any Go values to a safe representation that can be used to pass values between C and Go safely. See runtime/cgo.Handle for more information.
  • The net/url and net/http packages used to accept ";" (semicolon) as a setting separator in URL queries, in addition to "&" (ampersand). Now, settings with non-percent-encoded semicolons are rejected and net/http servers will log a warning to Server.ErrorLog when encountering one in a request URL. For example, before Go 1.17 the Query method of the URL example?a=1;b=2&c=3 would have returned map[a:[1] b:[2] c:[3]], while now it returns map[c:[3]].

三、 Go1.18

发布时间

15 March 2022

版本概要

  1. support forgeneric code using parameterized types
  2. fuzzing fully integrated into its standard toolchain
  3. Workspaces with a newGo workspace mode, which makes it simple to work with multiple modules.
  4. Go 1.18 includes CPU performance improvements of up to 20%

版本重点内容

Changes to the language

Generics

Go 1.18 includes an implementation of generic features as described by the Type Parameters Proposal. This includes major - but fully backward-compatible - changes to the language.

These new language changes required a large amount of new code that has not had significant testing in production settings. That will only happen as more people write and use generic code. We believe that this feature is well implemented and high quality.

The following is a list of the most visible changes. For a more comprehensive overview, see the proposal. For details see the language spec.

  • The syntax for function and type declarations now accepts type parameters.
  • Parameterized functions and types can be instantiated by following them with a list of type arguments in square brackets.
  • The new token ~ has been added to the set of operators and punctuation.
  • The syntax for Interface types now permits the embedding of arbitrary types (not just type names of interfaces) as well as union and ~T type elements. Such interfaces may only be used as type constraints. An interface now defines a set of types as well as a set of methods.
  • The new predeclared identifier any is an alias for the empty interface. It may be used instead of interface{}.
  • The new predeclared identifier comparable is an interface that denotes the set of all types which can be compared using == or !=. It may only be used as (or embedded in) a type constraint.

Fuzzing

Go 1.18 includes an implementation of fuzzing as described by the fuzzing proposal.

See the fuzzing landing page to get started.

Please be aware that fuzzing can consume a lot of memory and may impact your machine’s performance while it runs. Also be aware that the fuzzing engine writes values that expand test coverage to a fuzz cache directory within $GOCACHE/fuzz while it runs. There is currently no limit to the number of files or total bytes that may be written to the fuzz cache, so it may occupy a large amount of storage (possibly several GBs).

go mod vendor

The go mod vendor subcommand now supports a -o flag to set the output directory. (Other go commands still read from the vendor directory at the module root when loading packages with -mod=vendor, so the main use for this flag is for third-party tools that need to collect package source code.)

go work

The go command now supports a "Workspace" mode. If a go.work file is found in the working directory or a parent directory, or one is specified using the GOWORK environment variable, it will put the go command into workspace mode. In workspace mode, the go.work file will be used to determine the set of main modules used as the roots for module resolution, instead of using the normally-found go.mod file to specify the single main module. For more information see the go work documentation.

go test

The go command now supports additional command line options for the new fuzzing support described above:

  • go test supports -fuzz, -fuzztime, and -fuzzminimizetime options. For documentation on these see go help testflag.
  • go clean supports a -fuzzcache option. For documentation see go help clean.

Runtime

  • The garbage collector now includes non-heap sources of garbage collector work (e.g., stack scanning) when determining how frequently to run. As a result, garbage collector overhead is more predictable when these sources are significant. For most applications these changes will be negligible; however, some Go applications may now use less memory and spend more time on garbage collection, or vice versa, than before. The intended workaround is to tweak GOGC where necessary.
  • The runtime now returns memory to the operating system more efficiently and has been tuned to work more aggressively as a result.
  • Go 1.17 generally improved the formatting of arguments in stack traces, but could print inaccurate values for arguments passed in registers. This is improved in Go 1.18 by printing a question mark (?) after each value that may be inaccurate.
  • The built-in function append now uses a slightly different formula when deciding how much to grow a slice when it must allocate a new underlying array. The new formula is less prone to sudden transitions in allocation behavior.

Compiler

  • The compiler now can inline functions that contain range loops or labeled for loops.
  • The new -asan compiler option supports the new go command -asan option.
  • Because the compiler's type checker was replaced in its entirety to support generics, some error messages now may use different wording than before. In some cases, pre-Go 1.18 error messages provided more detail or were phrased in a more helpful way. We intend to address these cases in Go 1.19.
  • Because of changes in the compiler related to supporting generics, the Go 1.18 compile speed can be roughly 15% slower than the Go 1.17 compile speed. The execution time of the compiled code is not affected. We intend to improve the speed of the compiler in future releases.

Linker

The linker emits far fewer relocations. As a result, most codebases will link faster, require less memory to link, and generate smaller binaries. Tools that process Go binaries should use Go 1.18's debug/gosym package to transparently handle both old and new binaries.

四、 Go1.19

发布时间

2 August 2022

版本概要

  1. focused Go 1.19’s generics development on addressing the subtle issues and corner cases
  2. Doc comments now supportlinks, lists, and clearer heading syntax.
  3. Go’s memory modelnow explicitly defines the behavior of thesync/atomic package.
  4. the formal definition of the happens-before relation has been revised to align with the memory models used by C, C++, Java, JavaScript, Rust, and Swift.
  5. the garbage collector adds support for a soft memory limit.
  6. Go 1.19 includes a wide variety of performance and implementation improvements

版本重点内容

Memory Model

The Go memory model has been revised to align Go with the memory model used by C, C++, Java, JavaScript, Rust, and Swift. Go only provides sequentially consistent atomics, not any of the more relaxed forms found in other languages. Along with the memory model update, Go 1.19 introduces new types in the sync/atomic package that make it easier to use atomic values, such as atomic.Int64 and atomic.Pointer[T].

Doc Comments

Go 1.19 adds support for links, lists, and clearer headings in doc comments.

Runtime

The runtime now includes support for a soft memory limit. This memory limit includes the Go heap and all other memory managed by the runtime, and excludes external memory sources such as mappings of the binary itself, memory managed in other languages, and memory held by the operating system on behalf of the Go program. This limit may be managed viaruntime/debug.SetMemoryLimitor the equivalentGOMEMLIMITenvironment variable. The limit works in conjunction withruntime/debug.SetGCPercent/GOGC, and will be respected even ifGOGC=off, allowing Go programs to always make maximal use of their memory limit, improving resource efficiency in some cases.

In order to limit the effects of GC thrashing when the program's live heap size approaches the soft memory limit, the Go runtime also attempts to limit total GC CPU utilization to 50%, excluding idle time, choosing to use more memory over preventing application progress.

The runtime now schedules many fewer GC worker goroutines on idle operating system threads when the application is idle enough to force a periodic GC cycle.

The runtime will now allocate initial goroutine stacks based on the historic average stack usage of goroutines. This avoids some of the early stack growth and copying needed in the average case in exchange for at most 2x wasted space on below-average goroutines.

Unrecoverable fatal errors (such as concurrent map writes, or unlock of unlocked mutexes) now print a simpler traceback excluding runtime metadata (equivalent to a fatal panic) unless GOTRACEBACK=system or crash. Runtime-internal fatal error tracebacks always include full metadata regardless of the value of GOTRACEBACK.

Compiler

The compiler now uses a jump table to implement large integer and string switch statements. Performance improvements for the switch statement vary but can be on the order of 20% faster. (GOARCH=amd64 and GOARCH=arm64 only)

Core library

The sync/atomic package defines new atomic types Bool, Int32, Int64, Uint32, Uint64, Uintptr, and Pointer. These types hide the underlying values so that all accesses are forced to use the atomic APIs. Pointer also avoids the need to convert to unsafe.Pointer at call sites. Int64 and Uint64 are automatically aligned to 64-bit boundaries in structs and allocated data, even on 32-bit systems.

四、 Go1.20

发布时间

1 February 2023

版本概要

  1. launch a preview of profile-guided optimization (PGO)
  2. includes a handful of language changes
  3. The cover tool now can collect coverage profiles of whole programs, not just of unit tests.
  4. Compiler and garbage collector improvements have reduced memory overhead and improved overall CPU performance by up to 2%.

版本重点内容

Changes to the language

  • Go 1.17 added conversions from slice to an array pointer. Go 1.20 extends this to allow conversions from a slice to an array: given a slice x, [4]byte(x) can now be written instead of *(*[4]byte)(x).
  • The unsafe package defines three new functions SliceData, String, and StringData.
  • Comparable types (such as ordinary interfaces) may now satisfy comparable constraints, even if the type arguments are not strictly comparable (comparison may panic at runtime).

Cgo

The go command now disables cgo by default on systems without a C toolchain. More specifically, when the CGO_ENABLED environment variable is unset, the CC environment variable is unset, and the default C compiler (typically clang or gcc) is not found in the path, CGO_ENABLED defaults to 0. As always, you can override the default by setting CGO_ENABLED explicitly.

Cover

Go 1.20 supports collecting code coverage profiles for programs (applications and integration tests), as opposed to just unit tests.

Runtime

Some of the garbage collector's internal data structures were reorganized to be both more space and CPU efficient. This change reduces memory overheads and improves overall CPU performance by up to 2%.

The garbage collector behaves less erratically with respect to goroutine assists in some circumstances.

Go 1.20 adds a new runtime/coverage package containing APIs for writing coverage profile data at runtime from long-running and/or server programs that do not terminate via os.Exit().

Compiler

Go 1.20 adds preview support for profile-guided optimization (PGO). PGO enables the toolchain to perform application- and workload-specific optimizations based on run-time profile information. Currently, the compiler supports pprof CPU profiles, which can be collected through usual means,。

The compiler now rejects anonymous interface cycles with a compiler error by default.

Go 1.18 and 1.19 saw regressions in build speed, largely due to the addition of support for generics and follow-on work. Go 1.20 improves build speeds by up to 10%, bringing it back in line with Go 1.17. Relative to Go 1.19, generated code performance is also generally slightly improved.

下一篇文章打算把每个版本开发者需要关注的特性筛选出来,并通过一些 case 来理解

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 序言
    • 为什么要了解版本信息?
      • 如何全面的了解版本信息?
      • 一、 Go1.16
        • 发布时间
          • 版本概要
            • 版本重点内容
              • Cgo
          • 二、 Go1.17
            • 发布时间
              • 版本概要
                • 版本重点内容
                  • Linker
              • 三、 Go1.18
                • 发布时间
                  • 版本概要
                    • 版本重点内容
                      • Generics
                      • Fuzzing
                  • 四、 Go1.19
                    • 发布时间
                      • 版本概要
                        • 版本重点内容
                          • Doc Comments
                      • 四、 Go1.20
                        • 发布时间
                          • 版本概要
                            • 版本重点内容
                              • Cgo
                              • Cover
                          领券
                          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档