Go 1.24

Go 1.24

The new release of the Go language, version 1.24, comes six months after Go 1.23. Most changes pertain to the implementation of the toolchain, runtime, and libraries. As always, the release ensures the promise of compatibility Go 1. Developers expect nearly all Go programs to continue compiling and running as before.

Changes to the language

Go 1.24 now fully supports type parameterized type aliases: a type alias can be parameterized like a declared type. Details can be found in the language specification. While this feature can be disabled by setting GOEXPERIMENT=noaliastypeparams; however, the aliastypeparams option will be removed in Go 1.25.

Tools

The go command

Go modules can now track executable dependencies using the tool directive in go.mod. This removes the need for the previous workaround of adding tools as empty imports in a file commonly called "tools.go". The go tool command can now run these tools in addition to the tools provided with Go. More information can be found in the documentation.

The new -tool flag for go get adds a tool directive to the current module for the specified packages in addition to adding requirement directives.

CSIStorageCapacity The meta-pattern tool refers to all tools in the current module. This can be used to update all of them via go get tool or to install them into your GOBIN directory via go install tool.

Executable files created via go run and the new behavior of go tool are now cached in the Go build cache. This enhances repeat launches due to increased caching. #69290.

The go build and go install commands now accept the -json flag, which reports output and build errors as structured JSON output to standard output. Details of the format can be seen in go help buildjson.

Moreover, go test -json now reports output and build errors in JSON, interspersed with the JSON of the test results. They can be distinguished by new Action types, but if they cause issues in the test integration system, you can revert to text output of the build through the GODEBUG setting gotestjsonbuildtext=1.

The new GOAUTH environment variable provides a flexible way to authorize private module pulls. See details in go help goauth.

The go build command now installs the version of the main module in the compiled binary, based on the tag and/or commit of the version control system. The suffix +dirty will be added if there are uncommitted changes. You can use the flag -buildvcs=false to omit version control information from the binary.

New GODEBUG configuration toolchaintrace=1 can now be used to track the process of toolchain selection in the go team.

Cgo

Cgo supports new annotations for C functions to improve runtime performance. #cgo noescape cFunctionName tells the compiler that the memory passed to the C function cFunctionName does not escape. #cgo nocallback cFunctionName tells the compiler that the C function cFunctionName does not callback any Go functions. More information can be found in the cgo documentation.

Cgo currently refuses to compile calls to C functions that have multiple incompatible declarations. For example, if f is declared as both void f(int) and void f(double), cgo will report an error instead of potentially generating an incorrect call sequence f(0). New in this release is improved detection of this error condition when incompatible declarations appear in different files. #67699.

Objdump

The objdump tool now supports disassembly on 64-bit LoongArch (GOARCH=loong64), RISC-V (GOARCH=riscv64), and S390X (GOARCH=s390x).

Vet

The new tests analyzer reports common errors in test declarations, fuzzers, benchmarks, and examples in test packages, such as improperly formed names, incorrect signatures, or examples documenting non-existent identifiers. Some of these errors can result in tests not running.

The existing printf analyzer now reports diagnostics on calls of the form fmt.Printf(s), where s is a non-constant format string with no other arguments. Such calls are almost always an error, as the value of s may contain a %; instead, use fmt.Print. 60529This check tends to make findings in existing code and is therefore only applied when the language version (as specified by the directive in the go.mod file or comments `//go:build) is at least Go 1.24, to avoid causing build breaks in CI when upgrading to the Go 1.24 toolchain.

The existing buildtag analyzer now reports diagnostics when there is an incorrect build constraint of an older version Go in the directive //go:build. For example, //go:build go1.23.1 refers to a point release; instead use //go:build go1.23. #64127.

The existing copylock analyzer now reports diagnostics when a variable declared in a triple 'for' loop, such as for i := iter(); done(i); i = next(i) { … }, contains sync.Locker, such as sync.Mutex. Go 1.22 changed the behavior of such loops to create a new variable for each iteration, copying values from the previous iteration; this copying is unsafe for locks. #66387.

GOCACHEPROG

The internal cmd/go binary and test caching mechanism can now be implemented by child processes that implement the JSON protocol between the cmd/go tool and a child process named by the environment variable GOCACHEPROG. Previously this was under GOEXPERIMENT. Protocol details can be found in the documentation.

Runtime

Several performance improvements in the runtime have reduced CPU overhead by 2-3% on average across a set of representative benchmarks. Results may vary based on the application. These improvements include a new built-in map implementation based on Swedish Tables, more efficient memory allocation for small objects, and a new internal mutex implementation in the runtime.

The new built-in map implementation and the new internal runtime mutex can be disabled with the settings GOEXPERIMENT=noswissmap and GOEXPERIMENT=nospinbitmutex during the build respectively.

Compiler

The compiler has already forbidden the definition of new methods with receiver types that were generated by cgo, but it was possible to bypass this restriction via type aliasing. Go 1.24 now always reports an error if the receiver designates a generated cgo type, either directly or indirectly (via type alias).

Linker

The linker now generates a GNU build ID (ELF NT_GNU_BUILD_ID record) on ELF platforms and a UUID (Mach-O LC_UUID load command) on macOS by default. The build ID or UUID is derived from the Go build ID. This can be disabled with the linker flag -B none, or overridden with the linker flag -B 0xNNNN with the user-specified hexadecimal value.

Rollout

As stated in the Go 1.22 release notesGo 1.24 now requires Go 1.22.6 or later for promotion. Developers expect that Go 1.26 will require a patch release of Go 1.24 or later for promotion.

Standard library

Directory-restricted access to the filesystem

New type os.Root provides the ability to perform filesystem operations within a specific directory.

Function os.OpenRoot opens a directory and returns os.Root. Methods on os.Root operate within this directory and do not allow paths to reference locations outside the directory, including those that follow symbolic links beyond the directory. Methods on os.Root mirror most filesystem operations available in the os package, including, for example, os.Root.Open, os.Root.Create, os.Root.Mkdir and os.Root.Stat.

New benchmarking function

Benchmarks can now use a faster and less error-prone method testing.B.Loop for iterating the benchmark like for b.Loop() { … } instead of the typical loop structures involving b.N like for range b.N. This offers two significant advantages:

  • The benchmark function executes exactly once per -count, meaning costly setup and teardown steps are executed only once.
  • Function call parameters and results live on, preventing the compiler from fully optimizing the loop body.

Improved finalizers

A new function runtime.AddCleanup is a cleanup mechanism that is more flexible, more efficient, and less error-prone than runtime.SetFinalizer. AddCleanup attaches a cleanup function to an object that will be executed as soon as the object becomes unreachable. However, unlike SetFinalizer, multiple cleanups can be attached to a single object, cleanups can be attached to internal pointers, cleanups generally do not cause leaks when objects form cycles, and cleanups do not defer the release of the object or objects they point to. New code should prefer AddCleanup over SetFinalizer.

New weak package

New package weak provides weak pointers.

Weak pointers are a low-level primitive provided for creating structures that efficiently use memory, such as weak dictionaries for mapping values, canonical dictionaries for anything not covered by the unique, and various types of caches. To support these use cases, this release also provides runtime.AddCleanup and maphash.Comparable.

A new package crypto/mlkem

New package crypto/mlkem implements ML-KEM-768 and ML-KEM-1024.

ML-KEM is a post-quantum key exchange mechanism, previously known as Kyber and specified in FIPS 203.

New packages crypto/hkdf, crypto/pbkdf2, and crypto/sha3

New package crypto/hkdf implements the HMAC-based key output function “Extract-and-Expand” HKDF, as defined in RFC 5869.

New package crypto/pbkdf2 implements the password-based key output function PBKDF2, as defined in RFC 8018.

New package crypto/sha3 implements the SHA-3 hashing function and SHAKE and cSHAKE extendable-output functions, as defined in FIPS 202.

All three packages are based on the previously existing packages from golang.org/x/crypto/….

Compliance with FIPS 140-3

This release includes a new set of mechanisms for ensuring compliance with FIPS 140-3.

The Go cryptographic module is a set of internal packages in the standard library that are transparently used to implement approved FIPS 140-3 algorithms. Applications do not require changes to use the Go cryptographic module for approved algorithms.

The new environment variable GOFIPS140 can be used to select the version of the Go cryptographic module to be used in the build. The new GODEBUG configuration fips140 can be used to enable FIPS 140-3 mode at runtime.

Go 1.24 includes the Go cryptographic module version v1.0.0, which is currently being tested with an accredited CMVP laboratory.

A new experimental package testing/synctest

A new experimental package testing/synctest provides support for testing concurrent code.

  • Function synctest.Run launches a group of goroutines in an isolated “bubble.” In the bubble, package functions time operate on fake clocks.
  • Features synctest.Wait waits for all goroutines to block in the current bubble.

Details can be found in the package documentation.

The synctest package is experimental and must be enabled by setting GOEXPERIMENT=synctest. The package API may change in future releases. In #67434 more details can be found and feedback can be provided.

Minor changes in the library

archive

Implementations (*Writer.AddFS) in archive/zip and archive/tar now write a directory header for an empty directory.

bytes

The package bytes adds several functions that work with iterators:

  • Lines returns an iterator over lines split by new lines in a byte slice.
  • SplitSeq returns an iterator over all sub-slices of the byte slice separated by the separator.
  • SplitAfterSeq returns an iterator over sub-slices of the byte slice split after each occurrence of the separator.
  • FieldsSeq returns an iterator over sub-slices of the byte slice around sequences of whitespace characters as defined by unicode.IsSpace
  • FieldsFuncSeq returns an iterator over sub-slices of the byte slice around sequences of Unicode code points that satisfy the predicate.

crypto/aes

The returned value NewChipher no longer implements the methods NewCTR, NewGCM, NewCBCEncrypter, and NewCBCDecrypter. These methods were undocumented and not available on all architectures. The value Block must be passed directly to the corresponding functions crypto/cipher. Currently, crypto/cipher still checks these methods on Block values, even though they are no longer supported by the standard library.

crypto/cipher

A new function NewGCMWithRandomNonce brings back Support for OpenVPN;, which implements AES-GCM, generating a random nonce during Seal and prepending it to the encrypted text.

Implementation Stream, returned NewCTR when used with crypto/aes is now several times faster on amd64 and arm64.

NewOFB, NewCFBEncrypter and NewCFBDecrypter are now marked as deprecated. The OFB and CFB modes are unauthenticated, which generally allows active attacks to manipulate and recover plaintext. Applications are advised to use Support for OpenVPN; instead. If an unauthenticated mode Stream is necessary, one can use NewCTR instead.

crypto/ecdsa

PrivateKey.Sign now creates a deterministic signature in accordance with RFC 6979, if the source of randomness is nil.

crypto/md5

The returned value md5.New, now also implements the interface encoding.BinaryAppender.

crypto/rand

Function Read now guarantees no failures. If Read encounters an error while reading Reader, the program will terminate irretrievably. Note that the default Reader is documented to always succeed, so this change should only affect those programs that override the Reader variable. One exception is Linux kernels prior to version 3.17, where the default Reader still opens /dev/urandom and may fail.

On Linux 6.11 and later, Reader now uses the getrandom system call via vDSO. This is several times faster, typically for small reads.

On OpenBSD, Reader now uses arc4random_buf(3).

A new function Text can now generate cryptographically secure random strings of text.

crypto/rsa

GenerateKey now returns an error if a key shorter than 1024 bits is requested. All methods Sign, Verify, Encrypt, and Decrypt now return an error if used with a key size of less than 1024 bits. Such keys are unsafe and should not be used. Setting GODEBUG rsa1024min=0 restores the old behavior, but Go developers recommend doing this only when necessary and only in tests, for example by adding the line //go:debug rsa1024min=0 in the test file. The new an example GenerateKey provides an easy-to-use standard 2024-bit test key.

It is now safe and more efficient to call PrivateKey.Precompute up to PrivateKey.Validate. Precompute is now faster in the presence of a partially filled PrecomputedValues, such as when extracting a key from JSON.

The package now rejects more incorrect keys, even when Validate is not called, and GenerateKey can now return new errors for broken sources of randomness. The fields Primes and Precomputed struct PrivateKey are now used and validated even when some values are absent. Changes have also been made in crypto/x509 regarding the parsing and extraction of RSA keys as noted below.

SignPKCS1v15 and VerifyPKCS1v15 now support SHA-512/224, SHA-512/256, and SHA-3.

GenerateKey now uses a slightly different method for generating the private exponent (Carmichael function instead of Euler's function). Rare applications that recreate keys externally only from prime numbers might produce different but compatible results.

Operations on public and private keys are now up to twice as fast on wasm.

crypto/sha*

crypto/subtle

A new function WithDataIndependentTiming allows the user to execute functions with architecture-specific features that ensure the immutability of certain instructions regarding the timing of data values. This can be used to ensure that code designed to operate in constant time has not been optimized by processor-level features in such a way that it performs in variable time. Currently, WithDataIndependentTiming uses the PSTATE.DIT bit on arm64 and does nothing on all other architectures. Setting GODEBUG dataindependenttiming=1 enables DIT mode for the entire Go program.

Output XORBytes must fully overlap or not at all with the input. The previous behavior was undefined otherwise, while now XORBytes will panic.

crypto/tls

The TLS server now supports Encrypted Client Hello (ECH). This feature can be enabled by populating the field Config.EncryptedClientHelloKeys.

A new post-quantum key exchange mechanism X25519MLKEM768 is now supported and enabled by default when Config.CurvePreferences is nil. Setting GODEBUG tlsmlkem=0 returns the default.

Support for the experimental key exchange X25519Kyber768Draft00 has been removed.

The key exchange order is now fully handled by the crypto/tls package. The order Config.CurvePreferences is now ignored, and the content is only used to determine which key exchanges to include when the field is populated.

A new field ClientHelloInfo.Extensions lists the extension identifiers received in the Client Hello message. This can be useful for fingerprinting TLS clients.

crypto/x509

Setting GODEBUG x509sha1 has been removed. Certficicate.Verify no longer supports signatures based on SHA-1.

OID now implements the interfaces encoding.BinaryAppender and encoding.TextAppender.

The default certificate policies field has been changed from Certificate.PolicyIdentifiers to Certificate.Policies. When parsing certificates, both fields will be populated, but when creating certificate policies, they will be taken from the Certificate.Policies field instead of Certificate.PolicyIdentifiers. This change can be reverted by setting GODEBUG x509usepolicies=0.

CreateCertificate will now generate a serial number using an RFC 5280 compliant method when passing the template via the field Certificate.SerialNumber nil, instead of failing.

Certificate.Verify now supports policy validation as defined in RFC 5280 and RFC 9618. The new field VerifyOptions.CertificatePolicies can be set to an acceptable set of policies OIDsOnly certificate chains with valid policy graphs will be returned from Certificate.Verify.

MarshalPKCS8PrivateKey now returns an error instead of extracting the wrong RSA key. (MarshalPKCS1PrivateKey does not return an error, and its behavior with provided incorrect keys remains undefined.)

ParsePKCS1PrivateKey and ParsePKCS8PrivateKey now utilizes and validates CRT encoded values, thus can reject incorrect RSA keys that were previously accepted. Using the GODEBUG settings x509rsacrt=0 reverts to recalculating CRT values.

debug/elf

The package debug/elf adds support for handling symbol versioning in dynamic ELF (Executable and Linkable Format) files. The new method File.DynamicVersions returns a list of dynamic versions defined in the ELF file. The new method File.DynamicVersionNeeds returns a list of dynamic versions required by this ELF file that are defined in other ELF objects. Finally, the new fields Symbol.HasVersion and Symbol.VersionIndex indicate the symbol's version.

encoding

Two new interfaces TextAppender and BinaryAppender have been introduced to append a textual or binary representation of the object to a byte slice. These interfaces provide the same functionality as TextMarshaler and BinaryMarshaler, but instead of allocating a new slice each time, they append data directly to the existing slice. These interfaces are now implemented by standard library types that already implement TextMarshaler and/or BinaryMarshaler.

encoding/json

When compiling, a struct field with the new omitzero option in the struct field tag will be omitted if its value is zero. If the field type has a method IsZero() bool, it will be used to determine whether the value is zero. Otherwise, the value will be zero if it is the zero value for its type. The omitzero field tag is cleaner and less error-prone than omitempty when the intent is to omit zero values. Specifically, unlike omitempty, omitzero omits zero time.Time values, which is a common source of issues.

If both omitempty and omitzero are specified, the field will be omitted if the value is empty or zero (or both at the same time).

UnmarshalTypeError.Field now includes built-in structs to provide more detailed error messages.

go/types

All data structures go/types that reveal sequences of method pairs, like Len() int and At(int) T, now also have methods that return iterators, simplifying code like this:

params := fn.Type.(*types.Signature).Params() for i := 0; i < params.Len(); i++ { use(params.At(i)) }

For this:

for param := range fn.Signature().Params().Variables() { use(param) }

Methods: Interface.EmbeddedTypes Interface.ExplicitMethods Interface.Methods MethodSet.Methods Named.Methods Scope.Children Struct.Fields Tuple.Variables TypeList.Types TypeParamList.TypeParams Union.Terms

hash/*

log/slog

CSIStorageCapacity DiscardHandler is a handler that is never activated and always discards its output.

Level and LevelVar now implements the interface encoding.TextAppender.

math/*

net

ListenCondig now uses MPTCP by default on systems where it is supported (currently only Linux).

IP now implements the interface encoding.TextAppender.

net/http

Changed restriction Transport on received informational responses 1xx to the request. Previously, this would stop the request and return an error after receiving more than 5 1xx responses. Now it returns an error only if the total size of all 1xx responses exceeds the configuration setting Transport.MaxResponseHeaderBytes.

Additionally, when the request has a hook for tracking net/http/httptrace.ClientTrace.Got1xxResponse, there is now no limit on the total number of 1xx responses. The Got1xxResponse hook can return an error to stop the request.

Transport and Server now has an HTTP2 field that allows configuration of HTTP/2 protocol settings.

New fields Server.Protocols and Transport.Protocols provide a simple way to configure which protocols the HTTP server or client uses.

The server and client can be configured to support unencrypted HTTP/2 connections.

Once Server.Protocols contains UnencrypterHTTP2, the server will accept HTTP/2 connections on unencrypted ports. The server can accept both HTTP/1 and unencrypted HTTP/2 on the same port.

Once Transport.Protocols contains UnencryptedHTTP2 and does not include HTTP1, the transport will use unencrypted HTTP/2 for addresses http://. If the transport is configured to use both HTTP/1 and unencrypted HTTP/2, it will use HTTP/1.

Support for unencrypted HTTP/2 uses 'HTTP/2 with prior knowledge' (RFC 9113, section 3.3). The deprecated header 'Upgrade: h2c' is not supported.

net/netip

Addr, AddrPort and Prefix now implement interfaces encoding.BinaryAppender and encoding.TextAppender.

net/url

URL now also implements the interface encoding.BinaryAppender.

os/user

In Windows, Current can now be used in Windows Nano Server. The implementation was updated to avoid using functions from the NetApi32 library, which is missing in Nano Server.

In Windows, Current, Lookup and LookupId now support the following built-in user service accounts:

  • NT AUTHORITY\SYSTEM
  • NT AUTHORITY\LOCAL SERVICE
  • NT AUTHORITY\NETWORK SERVICE

In Windows, Current was significantly accelerated when the current user is part of a slow domain, which is common for many corporate users. The new performance of the implementation is now in the order of milliseconds, compared to the previous implementation which could take several seconds, even minutes, to complete.

In Windows, Current now returns the user of the process owner when the current thread impersonates another user. Previously, it returned an error.

regexp

Regexp now implements the interface encoding.TextAdapter.

runtime

Function GOROOT is now declared deprecated. In new code, it is recommended to prefer using the system path for locating the 'go' binary, and to use 'go env GOROOT' to determine GOROOT.

strings

The package strings adds several functions for working with iterators:

  • Lines returns an iterator over lines in a string split by new lines.
  • SplitSeq returns an iterator over all substrings of a string, split by a separator.
  • SplitAfterSeq returns an iterator over substrings of a string, split after each occurrence of the separator.
  • FieldsSeq returns an iterator over substrings of a string around sequences of whitespace characters, as definedunicode.IsSpace
  • FieldsFuncSeq returns an iterator over substrings of a string around sequences of Unicode code points that satisfy the predicate.

sync

Implementation sync.Map has been modified to improve performance, especially for dictionary changes. For example, contention among disjoint sets in large dictionaries is less likely, and no grow time is needed to achieve low contention load on the dictionary.

If you encounter any issues, set GOEXPERIMENT=nosynchashtriemap during the build to revert to the old implementation, and please fill out the issue form.

testing

New methods T.Context and B.Context return the context that is canceled after the test completes and before the test cleanup functions are executed.

New methods T.Chdir and B.Chdir can be used to change the working directory for the duration of the test or benchmark.

text/template

Templates now support range-over-func and range-over-int.

time

Time now implements the interfaces encoding.BinaryAppender and encoding.TextAppender.

Ports

Linux

How it was announced In the release notes for Go 1.23, Go 1.24 requires Linux kernel version 3.2 or later.

Darwin

Go 1.24 is the last release that will run on macOS 11 Big Sur. Go 1.25 will require macOS 12 Monterey or later.

WebAssembly

The go:wasmexport compiler directive has been added to Go programs to export functions to the WebAssembly host.

In WebAssembly System Interface Preview 1 (GOOS=wasip1 GOARCH=wasm), Go 1.24 supports building a Go program as reactor/library by specifying the build flag -buildmode=c-shared.

More types are now allowed as argument or result types for go:wasmimport functions. In particular, bool, string, uintptr, and pointers to specific types are allowed (details can be found in the documentation), along with 32-bit and 64-bit integer types and floating-point types, and unsafe.Pointer, which are already allowed. These types are also allowed as argument or result types for go:wasmexport functions.

Support files for WebAssembly have been moved to lib/wasm from misc/wasm.

The initial memory size has been significantly reduced, especially for small WebAssembly applications.

Windows

The 32-bit port windows/arm (GOOS=windows GOARCH=arm) has been marked as broken. Details can be found in #70705

Source: linux.org.ru

Buy reliable website hosting with DDoS protection, VPS VDS servers 🔥 Buy reliable website hosting with DDoS protection, VPS VDS servers | ProHoster