A new release of the Go language, version 1.24, comes six months after Go 1.23. Most of the changes are in the implementation of the toolchain, runtime and libraries. As always, the release provides promise of compatibility Go 1. The language designers expect that almost all Go programs will continue to compile and run as before.
Language changes
Go 1.24 now fully supports generic type aliases: a type alias can be parameterized as a declared type. See language specifications. For now, the feature can be disabled by setting GOEXPERIMENT=noaliastypeparams; however, the aliastypeparams option will be removed in Go 1.25.
Tools
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 typically called “tools.go.” The go tool command can now run these tools in addition to the tools that ship with Go. More information can be found in documentation.
The new -tool flag for go get causes tool directives to be added to the current module for the specified packages in addition to adding require directives.
New meta-pattern tool refers to all the tools in the current module. This can be used to update them all via go get tool or to install them into your GOBIN directory via go install tool.
Executables created via go run and the new go tool behavior are now cached in the Go build cache. This makes repeated runs possible by increasing the cache. #69290.
The go build and go install commands now accept the -json flag, which reports the build output and errors as structured JSON output on standard output. Format details can be found in go help buildjson .
Furthermore, go test -json now reports build output and errors in JSON, mixed in with the test result JSON. These can be distinguished by the new Action types, but if they cause problems in the test integration system, you can fall back to the text build output via GODEBUG setup gotestjsonbuildtext=1.
The new environment variable GOAUTH provides a flexible way to authorize private module pulls. See go help goauth for details.
The go build command is now installed version of the main module in the compiled binary, based on the version control tag and/or commit. The +dirty suffix will be added if there are uncommitted changes. The -buildvcs=false flag can be used to omit version control information from the binary.
new GODEBUG setup toolchaintrace=1 can now be used to track the toolchain selection process in the go command.
Cgo
Cgo supports new annotations for C functions to improve runtime performance. #cgo noescape cFunctionName tells the compiler that memory passed to the C function cFunctionName does not escape. #cgo nocallback cFunctionName tells the compiler that the C function cFunctionName does not call back any Go functions. More information can be found in cgo documentation.
Cgo currently refuses to compile calls to a C function that has 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 possibly generating an invalid sequence of calls to 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).
Fat
The new tests analyzer reports common errors in test, fuzzer, benchmark, and example declarations in test suites, such as malformed names, invalid signatures, or examples that document nonexistent identifiers. Some of these errors can cause tests to fail.
The existing printf parser now reports diagnostics for 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, since the value of s may contain the % character; use fmt.Print instead. 60529. This check tends to find things in existing code, and is therefore only applied when the language version (as specified by the go directive of the go.mod file or the `//go:build` comments) is at least Go 1.24, to avoid causing long integration breaks when upgrading to the Go 1.24 toolchain.
The existing buildtag analyzer now reports diagnostics when there is an incorrect buildtag older version build limitation Go in the //go:build directive. For example, //go:build go1.23.1 refers to a point release; use //go:build go1.23 instead. #64127.
The existing copylock analyzer now reports a diagnostic when a variable declared in a triple "for" loop, such as for i := iter(); done(i); i = next(i) { … }, contains a sync.Locker such as sync.Mutex. Go 1.22 changed the behavior of such loops to create a new variable on each iteration, copying the values from the previous iteration; this copying is not lock-safe. #66387.
GOCACHEPROG
The internal cmd/go binary and test caching mechanism can now be implemented by child processes implementing a JSON protocol between the cmd/go tool and the child process named by the GOCACHEPROG environment variable. Previously, this was GOEXPERIMENT. Details of the protocol can be seen in documentation.
Time of completion
Several runtime performance improvements reduced CPU overhead by 2-3% on average across a set of representative benchmarks. Results may vary by application. These improvements include a new built-in map implementation based on Swedish Tables, more efficient allocation of small object memory, and a new internal runtime implementation of the mutex.
The new built-in map implementation and the new internal runtime mutex can be disabled by setting GOEXPERIMENT=noswissmap and GOEXPERIMENT=nospinbitmutex at build time, respectively.
Compiler
The compiler already prohibited defining new methods with receiver types that were generated by cgo, but it was possible to work around this restriction via a type alias. Go 1.24 now always reports an error if the receiver denotes a cgo-generated type, either directly or indirectly (via a type alias).
Linker
The linker now generates a GNU build ID (ELF entry NT_GNU_BUILD_ID) on ELF platforms and a UUID (Mach-O load command LC_UUID) on macOS by default. The build ID or UUID is derived from the Go build ID. This can be disabled with the -B none linker flag, or overridden with the -B 0xNNNN linker flag with a user-specified hex value.
Promotion
As stated in Go 1.22 release notes, Go 1.24 now requires Go 1.22.6 or later to be promoted. The developers expect that Go 1.26 will require a point release of Go 1.24 or later to be promoted.
Standard Library
Directory-restricted file system access
New type os.root Provides the ability to perform file system operations within a specific directory.
Function os.OpenRoot opens the directory and returns os.root. Methods on os.root operate on that directory and do not allow paths to refer to locations outside the directory, including those that follow symbolic links outside the directory. The methods on os.Root mirror most of the filesystem operations available in the os package, including, for example, os.Root.Open, os.Root.Create, os.Root.Mkdir и os.Root.Stat.
New benchmark feature
Benchmarks can now use a faster, less error-prone method testing.B.Loop to iterate over a benchmark like for b.Loop() { … } instead of the typical loop structures involving bN like for range bN This offers two significant advantages:
- The benchmark function is executed exactly once per -count, so the expensive setup and cleanup steps are only performed once.
- The function call parameters and results live on, preventing the compiler from completely optimizing the loop body.
Improved finalizers
New feature runtime.AddCleanup is a completion mechanism that is more flexible, more efficient, and less error-prone than runtime.SetFinalizerAddCleanup attaches a cleanup function to an object that runs 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 do not typically cause leaks when objects form a cycle, and cleanups do not delay deallocation of the object or objects it points to. New code should prefer AddCleanup to SetFinalizer.
New weak package
New package weak provides weak pointers.
Weak pointers are a low-level primitive provided for creating memory-efficient structures such as weak dictionaries for mapping values, canonicalization dictionaries for anything not covered by a package. unique, and various types of caches. To support these use cases, this release also provides runtime.AddCleanup и maphash.Comparable.
New crypto/mlkem package
New package crypto/mlkem implements ML-KEM-768 and ML-KEM-1024.
ML-KEM is a post-quantum key exchange mechanism, formerly 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 “Extract-and-Expand” key derivation function HKDF as defined in RFC 5869.
New package crypto/pbkdf2 implements the password-based key derivation function PBKDF2 as defined in RFC 8018.
New package crypto/sha3 implements the SHA-3 hash function and the SHAKE and cSHAKE extensible output functions as defined in FIPS 202.
All three packages are based on the existing golang.org/x/crypto/… packages.
FIPS 140-3 Compliance
This release includes a new set of mechanisms to ensure FIPS 140-3 compliance.
The Go crypto module is a set of internal standard library packages that are transparently used to implement FIPS 140-3 approved algorithms. Applications do not require modifications to use the Go crypto module for approved algorithms.
The new environment variable GOFIPS140 can be used to select the version of the Go crypto module to use in a build. New GODEBUG setup fips140 can be used to enable FIPS 140-3 mode at runtime.
Go 1.24 includes the Go crypto module v1.0.0, which is currently being tested with a CMVP-accredited lab.
New experimental package testing/synctest
New experimental package testing/synctest Provides support for testing concurrent code.
- Function synctest.run runs a group of goroutines in an isolated "bubble". In the bubble, the package's functions team operate on false clocks.
- Functions synctest.wait wait until all goroutines are blocked 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. #67434 You can see more details and provide feedback.
Minor changes in the library
archive
The (*Writer.AddFS) implementations in archive/zip and archive/tar now write the directory header for an empty directory.
bytes
Plastic bag bytes adds several functions that work with iterators:
- Lines Returns an iterator over newline-separated strings in a byte slice.
- SplitSeq returns an iterator over all subslices of a byte slice separated by a separator.
- SplitAfterSeq returns an iterator over the subslices of a byte slice, split after each occurrence of the separator.
- FieldsSeq returns an iterator over subslices of a byte slice around sequences of space characters, as defined unicode.IsSpace
- FieldsFuncSeq returns an iterator over subslices of the byte slice around sequences of Unicode code points satisfying the predicate.
crypto/aes
Return value NewChipher no longer implements the NewCTR, NewGCM, NewCBCEncrypter, and NewCBCDecrypter methods. These methods were undocumented and not available on all architectures. The value is now Block must be passed directly to the appropriate 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
New feature NewGCMWithRandomNonce returns AEAD, which implements AES-GCM by generating a random nonce during Seal and prepending it to the ciphertext.
implementation Stream, returned NewCTR when used with crypto/aes now several times faster on amd64 and arm64.
NewOFB, NewCFBEncrypter и NewCFBDecrypter are now deprecated. OFB and CFB modes are unauthenticated, which generally allows active attacks to manipulate and recover plaintext. Applications are encouraged to use AEAD instead. If unauthenticated mode Stream necessary, can be used NewCTR instead.
crypto/ecdsa
PrivateKey.Sign now creates a deterministic signature according to RFC 6979, if the randomness source is nil.
crypto/md5
Return 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 exit permanently. Note that the default Reader is documented to always succeed, so this change should only affect programs that override the Reader variable. One exception is Linux kernels prior to 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).
New feature Text can now generate cryptographically secure random text strings.
crypto/rsa
GenerateKey now returns an error if a key shorter than 1024 bits is requested. All Sign, Verify, Encrypt, and Decrypt methods now return an error if used with a key shorter than 1024 bits. Such keys are insecure and should not be used. Setting up GODEBUG rsa1024min=0 restores the old behavior, but the Go developers recommend doing this only when necessary and only in tests, for example by adding the line //go:debug rsa1024min=0 to the test file. New example GenerateKey provides an easy to use standard 2024-bit test key.
It is now safer and more efficient to call PrivateKey.Precompute until PrivateKey.Validate. Precompute is now faster in the presence of partially filled PrecomputedValues, for example when extracting a key from JSON.
The package now rejects more invalid keys even when Validate is not called, and GenerateKey can now return new errors for broken random sources. Fields Primes и Precomputed structures PrivateKey are now used and validated even when some values are missing. Also made changes to crypto/x509 for parsing and extracting RSA keys, described below.
SignPKCS1v15 и VerifyPKCS1v15 now support SHA-512/224, SHA-512/256 and SHA-3.
GenerateKey now uses a slightly different method to generate the private exponent (Carmichael's function instead of Euler's). Rare applications that externally regenerate keys from only prime numbers may produce different but compatible results.
Operations on public and private keys are now up to two times faster on wasm.
crypto/sha*
- crypto/sha1: return value sha1.New now also implements the interface encoding.binaryappender.
- crypto/sha256: values returned sha256.New и sha256.New224 now also implement the interface encoding.binaryappender.
- crypto/sha512: values returned sha512.New, sha512.New384, sha512.New512_224 и sha512.New512_256, now also implement the interface encoding.binaryappender.
crypto/subtle
New feature WithDataIndependentTiming allows the user to execute a function with architecture-specific features enabled that ensure that certain instructions are constant with respect to the timing of the data value. This can be used to ensure that code written to run in constant time has not been optimized by processor-level features such that it runs in variable time. Currently WithDataIndependentTiming uses the PSTATE.DIT bit on arm64 and does nothing on all other architectures. Setting up GODEBUG dataindependenttiming=1 enables DIT mode for the entire Go program.
Final World XORBytes must overlap completely or not at all with the input. Previously the behavior was undefined otherwise, whereas now XORBytes will panic.
crypto/tls
The TLS server now supports Encrypted Client Hello (ECH). This feature can be enabled by filling in the field Config.EncryptedClientHelloKeys.
A New Post-Quantum Key Exchange Mechanism X25519MLKEM768 now supported and enabled by default when Config.CurvePreferences is nil. Setting up GODEBUG tlsmlkem=0 returns default.
Support for the experimental X25519Kyber768Draft00 key exchange has been removed.
The key exchange order is now handled entirely by the crypto/tls package. Order Config.CurvePreferences is now ignored and the contents are only used to determine which key exchanges to include when the field is filled.
New field ClientHelloInfo.Extensions Lists the list of extension identifiers received in the Client Hello message. This can be useful for fingerprinting TLS clients.
crypto/x509
Setting up GODEBUG x509sha1 has been removed. Certification.Verify no longer supports SHA-1 based signatures.
OID now implements interfaces encoding.binaryappender и encoding.TextAppender.
The default certificate policy field has been changed from Certificate.PolicyIdentifiers + Certificate.PoliciesWhen parsing certificates, both fields will be populated, but when creating a certificate policy, they will be taken from the Certificate.Policies field instead of Certificate.PolicyIdentifiers. This change can be reverted. GODEBUG setup x509usepolicies=0.
CreateCertificate will now generate a serial number using an RFC 5280 compliant method when passing a template field Certificate.SerialNumber nil, instead of crashing.
Certificate.Verify now supports policy validation as defined in RFC 5280 and RFC 9618. New field VerifyOptions.CertificatePolicies can be set to an acceptable set of policies OIDs. Only certificate chains with valid policy graphs will be returned from Certificate.Verify.
MarshalPKCS8PrivateKey now returns an error instead of retrieving an invalid RSA key. (MarshalPKCS1PrivateKey has no error return and its behavior when invalid keys are provided remains undefined.)
ParsePKCS1PrivateKey и ParsePKCS8PrivateKey now use and validate encoded CRT values, so they can reject invalid RSA keys that were previously accepted. Usage GODEBUG settings x509rsacrt=0 returns to recalculation of CRT values.
debug/elf
Plastic bag debug/elf adds support for handling symbol versions in dynamic ELF (Executable and Linkable Format) files. New method File.DynamicVersions returns a list of dynamic versions defined in an ELF file. 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 и Symbol.VersionIndex indicate the version of the symbol.
encoding
Two new interfaces TextAppender и BinaryAppender were introduced to add a text or binary representation of an object to a slice of bytes. These interfaces provide the same functionality as TextMarshaler и BinaryMarshaler, but instead of allocating a new slice each time, they append the data directly to an existing slice. These interfaces are now implemented by standard library types that already implement TextMarshaler and/or BinaryMarshaler.
encoding/json
When building, 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 an IsZero() bool method, it will be used to determine if the value is zero. Otherwise, the value will be zero if it is null value for its type. The omitzero field tag is cleaner and less error-prone than omitempty when the intent is to omit null values. In particular, unlike omitempty, omitzero omits null time.time values, which is a common source of problems.
If both omitempty and omitzero are specified, the field will be omitted if the value is empty or zero (or both).
UnmarshalTypeError.Field now includes built-in structures to provide more detailed error messages.
go/types
All go/types data structures that expose sequences of method pairs, like Len() int and At(int) T, now also have methods that return iterators, allowing simpler code like this:
params := fn.Type.(*types.Signature).Params() for i := 0; i < params.Len(); i++ { use(params.At(i)) }
On this one:
for param := range fn.Signature().Params().Variables() { use(param) }
Методы: Interface.EmbeddedTypes Interface.ExplicitMethods Interface.Methods MethodSet.Methods Named.Methods Scope.Children Structure.Fields Tuple.Variables TypeList.Types TypeParamList.TypeParams Union.Terms
hash/*
- hash/adler32: return value New, now also implements the interface encoding.binaryappender
- hash/crc32: values returned New и NewIEEE, now also implement the interface encoding.binaryappender
- hash/crc64: return value New, now also implements the interface encoding.binaryappender
- hash/fnv: values returned New32 New32a New64 New64a New128 и New128a, now also implement the interface encoding.binaryappender
- hash/maphash: new features Comparable и WriteComparable can compute the hash of any value that can be compared. This allows you to hash anything that can be used as a key in a Go dictionary.
log/slog
New DiscardHandler is a handler that is never enabled and always discards its output.
Level и LevelVar now implement the interface encoding.TextAppender.
math/*
- math/big: Float, Int и Steering now implement the interface encoding.TextAppender.
- math/rand: deprecated top-level function calls Seed no longer have any effect. To restore the old behavior, you can use GODEBUG setup randseednop=0. More context in offer 67273.
- math/rand/v2: ChaCha8 и PCG now implement the interface encoding.binaryappender.
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
The restriction has changed Transport on received 1xx informational responses in response to a request. Previously, this would stop the request and return an error after receiving more than 5 1xx responses. Now, this only returns an error if the total size of all 1xx responses exceeds the configuration setting Transport.MaxResponseHeaderBytes.
Also, when a request has a tracking hook net/http/httptrace.ClientTrace.Got1xxResponse, there is no limit on the total number of 1xx responses now. The Got1xxResponse hook can return an error to stop the request.
Transport и Server & Hosting now have an HTTP2 field that allows configuration of HTTP/2 protocol settings.
New fields Server.Protocols и Transport.Protocols provide a simple way to configure which HTTP protocols the server or client uses.
The server and client can be configured to support unencrypted HTTP/2 connections.
When the 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.
When the Transport.Protocols contains UnencryptedHTTP2 and does not contain HTTP1, the transport will use unencrypted HTTP/2 for addresses http://. If a 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 Forward-Learning" (RFC 9113, section 3.3). The deprecated "Upgrade: h2c" header is not supported.
net/netip
addr, AddrPort и Prefix now implement interfaces encoding.binaryappender и encoding.TextAppender.
net/url
URL now also implements the interface encoding.binaryappender.
os/user
On Windows Current can now be used in Windows Nano Server. The implementation has been updated to avoid using functions from the NetApi32 library, which is missing from Nano Server.
On Windows Current, Lookup и LookupId now supports the following built-in user service accounts:
- NT AUTHORITYSYSTEM
- NT AUTHORITYLOCAL SERVICE
- NT AUTHORITYNETWORK SERVICE
On Windows Current has been significantly sped up when the current user is joined to a slow domain, which is a common case for many enterprise users. The new implementation's performance is now in the order of milliseconds, compared to the previous implementation, which could take several seconds, even minutes, to complete.
On Windows Current now returns the process owner user when the current thread impersonates another user. Previously, this returned an error.
regexp
Regexp now implements the interface encoding.TextAdapter.
runtime
Function GOROOT is now deprecated. In newer environments, you should prefer to use the system path to determine the "go" binary, and use go env GOROOT to determine GOROOT.
strings
Plastic bag strings adds several functions for working with iterators:
- Lines Returns an iterator over newline-separated lines in a string.
- SplitSeq returns an iterator over all substrings of a string separated 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 string around sequences of Unicode code points that satisfy a predicate.
sync
implementation sync.map has been changed to improve performance, particularly for dictionary changes. For example, it is less likely to cause contention for disjoint set changes on large dictionaries, and it no longer requires build-up time to achieve a low contention dictionary load.
If you encounter any problems, set GOEXPERIMENT=nosynchashtriemap during build to revert back to the old implementation and please fill out the problem form.
testing
New methods T.Context и B.Context return a context that is discarded after the test completes and before the test cleanup functions are executed.
New methods T.Chdir и B.Chdir can be used to change the working directory for the duration of a test or benchmark.
text/template
Templates now support range-over-func and range-over-int.
team
Time now implements interfaces encoding.binaryappender и encoding.TextAppender.
Ports
Linux
As it was announced According to the Go 1.23 release notes, 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 certain types are allowed (see documentation), along with the 32-bit and 64-bit integer and floating-point types, and unsafe.Pointer, which are already permitted. These types are also permitted 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 footprint is significantly reduced, especially for small WebAssembly applications.
Windows
The 32-bit windows/arm port (GOOS=windows GOARCH=arm) has been marked as broken. Details in #70705
Source: linux.org.ru
