What's New in Go 1.21 Release? Exploring Three Handy Functions

Go 1.21, the latest release in the Go programming language series, brings a myriad of improvements in toolchain implementation, runtime, and libraries.

Exploring 3 Handy Functions in Go 1.21 Release
Go 1.21 has landed six months after 1.20. Let's discover sigificant changes in its features via this article!

Introduction To Go 1.21

Go 1.21, the latest release in the Go programming language series, brings a myriad of improvements in toolchain implementation, runtime, and libraries. Released six months after Go 1.20, this version maintains and enhances the Go 1 promise of compatibility. In this blog post, we'll delve into the key features and changes introduced in Go 1.21.

Changes to Release Numbering

A small but notable change has been introduced in the numbering of releases. In Go 1.21, the first release is now labeled as Go 1.N.0. This release includes the Go 1.21 language and its initial implementation, known as the Go 1.21.0 release. This blog will refer to it as "Go 1.21," while tools like go version will display "go1.21.0" until an upgrade to Go 1.21.1. Refer to the "Go Toolchains" documentation for a detailed explanation of the new version numbering.

Changes to the Language

New Built-ins

Go 1.21 introduces three new built-in functions:

min and max: Compute the smallest or largest value from a fixed number of given arguments.

clike
// Max
num := max(1, 2, 3)
fmt.Println("Max =", num)

// Min
minNum := min(1, 2, 3)
fmt.Println("Min =", minNum)
clike
myList := []int{1, 2, 3}

// Max in Slice
max := slices.Max(myList)
fmt.Println("Max in Slice =", max)

// Min in Slice
min := slices.Min(myList)
fmt.Println("Min in Slice =", min)

clear: Delete all elements from a map or zero all elements of a slice.

clike
m := map[string]int{"x": 1, "y": 2, "z": 3}
clear(m)
fmt.Println(m) // Outputs: map[]

New log/slog package: provides structured logging, in which log records include a message, a severity level, and various other attributes expressed as key-value pairs.

clike
slog.Info("hello", "count", 3)
// output is
// 2022/11/08 15:28:26 INFO hello count=3


logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
logger.Info("hello", "count", 3)
// output is
// time=2022-11-08T15:28:26.000-05:00 level=INFO msg=hello count=3


logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
logger.Info("hello", "count", 3)
// output is
// {"time":"2022-11-08T15:28:26.000000000-05:00","level":"INFO","msg":"hello","count":3}


slog.Group("request", "method", r.Method, "url", r.URL)
request.method=GET 
request.url=http://example.com
// output is
// "request":{"method":"GET","url":"http://example.com"}

Package Initialization Order

The package initialization order is now precisely specified. The new algorithm involves sorting all packages by import path and initializing them in a defined order. This change may impact programs relying on specific initialization orders, providing a more unambiguous definition.

Type Inference Improvements

Several improvements have been made to type inference, enhancing its power and precision:

  • A generic function can now be called with arguments that are themselves generic functions.
  • Type inference considers methods when a value is assigned to an interface.
  • Multiple enhancements in type inference accuracy.

Preview of Language Change

Go 1.21 includes a preview of a language change for loop variables, aiming to make them per-iteration rather than per-loop. This change helps avoid accidental sharing bugs. Check the LoopvarExperiment wiki page for details on trying out this language change.

Panicking and Recover

In Go 1.21, if a goroutine is panicking and recover was called directly by a deferred function, the return value of recover is guaranteed not to be nil. A runtime panic of type *runtime.PanicNilError will occur if panic is called with a nil interface value or an untyped nil. To support older Go versions, nil panics can be re-enabled by setting GODEBUG=panicnil=1.

>> You may consider:

Tools

Go 1.21 enhances support for both backward and forward compatibility in the Go toolchain.

Backward Compatibility

To handle changes that are non-breaking but may impact existing programs, Go 1.21 formalizes the use of the GODEBUG environment variable. The toolchain now chooses between old and new behaviors based on the go line in the workspace's go.work file or the main module's go.mod file.

Forward Compatibility

Go 1.21 reads the go line in a go.work or go.mod file as a strict minimum requirement. If a workspace or module specifies go 1.21.0, it cannot be used with Go 1.20 or Go 1.21rc1. The go command can now invoke other Go toolchain versions found in the PATH or downloaded on demand based on the version specified in go.mod or go.work.

Go Command Changes

  • The pgo build flag defaults to pgo=auto.
  • The C dir flag must be the first flag on the command line.
  • New options for go test: fullpath, c, and o.

Cgo

In files that import "C", the Go toolchain now correctly reports errors for attempts to declare Go methods on C types.

Runtime

Several enhancements and optimizations have been introduced in the runtime:

  • Improved stack trace printing for better debugging.
  • Transparent huge page management on Linux platforms for better memory utilization.
  • Garbage collection tuning for up to 40% reduction in application tail latency.
  • Reduced overhead of subsequent C to Go calls on Unix platforms.

Compiler

Profile-guided optimization (PGO) is now ready for general use, providing performance improvements of up to 7% for a representative set of Go programs. Assembler improvements and better build speed (up to 6%) have also been implemented.

Linker

On Windows/amd64, the linker emits SEH unwinding data by default, improving integration with Windows debuggers. The linker is now capable of deleting dead global map variables and offers better performance.

Core Library

New Packages

  • log/slog: Provides structured logging with levels.
  • testing/slogtest: A package to validate slog.Handler implementations.
  • slices: Offers common operations on slices using generic functions.
  • maps: Provides common operations on maps using generic functions.
  • cmp: Defines the type constraint Ordered and two new generic functions Less and Compare for ordered types.

Minor Changes

Various minor changes and updates have been made to the library, adhering to the Go 1 promise of compatibility. Performance improvements are included, though not explicitly detailed.

Archive and Compression Packages

Several improvements and additions have been made to packages such as archive/tar, archive/zip, and bytes.

Crypto Packages

  • crypto/ecdsa: Improvements in execution time for PublicKey.Equal and PrivateKey.Equal.
  • crypto/elliptic: Deprecated methods and recommendations for ECDH operations.
  • crypto/rand: Usage of getrandom system call on NetBSD 10.0 and later.

TLS Package

The net/http package introduces several new features and improvements, including enhanced support for errors, content control of session tickets, and improved handling of TLS alert codes for client authentication failures.

X.509 Package

The crypto/x509 package deprecates RevocationList.RevokedCertificates in favor of RevokedCertificateEntries for improved revocation list management.

Debugging and Profiling

Improvements have been made in various packages related to debugging and profiling, such as runtime/trace, offering a smaller CPU cost and explicit stop-the-world events in traces.

Other Packages

Numerous other packages, including unicode, syscall, and errors, have undergone enhancements and improvements. The unicode package, in particular, has been upgraded to Unicode 15.0.0.

Platform-Specific Changes

  • Darwin: Requires macOS 10.15 Catalina or later.
  • Windows: Support for Windows Server 2019.
  • Linux: Improved support for cgroups v2.

>> You may be interested in: 

Conclusion

Go 1.21 packs a punch with its array of features, optimizations, and improvements across the language, toolchain, runtime, compiler, linker, core library, and various packages. Go developers are encouraged to explore the release notes and upgrade their projects to leverage the benefits of Go 1.21.

To download and get started with Go 1.21, visit the official Go download page.

>>> Follow and Contact Relia Software for more information!

  • coding
  • golang
  • Mobile App Development
  • development
  • web development