Go 1.22 Released: What Changed in the Language
The Go development team has released the long-awaited version 1.22. This update brings a number of significant changes aimed at improving performance, security, and development convenience. Let's look at the most important innovations.
Key New Features of Version 1.22
1. Improved for-range Loops
One of the most anticipated changes is the reworking of variable behavior in for-range loops. Previously, a variable declared in the loop header was created once and reused on each iteration. This led to hard-to-find bugs, especially when capturing the variable in closures (for example, when passing to goroutines).
Starting with Go 1.22, each iteration of a for-range loop creates its own new variable. This makes the code more predictable and safer.
- Old behavior: one variable for the entire loop, frequent errors with pointers and goroutines.
- New behavior: each iteration gets its own copy of the variable, eliminating common bugs.
This change affects loops over slices, maps, and channels, as well as traditional three-component for loops.
2. Integer Range Support in for-range
Go 1.22 introduces the ability to iterate directly over an integer range. Now you can simply write for i := range 10 instead of cumbersome constructs like for i:=0; i < 10; i++.
This syntactic simplification makes code cleaner and reduces the likelihood of "off-by-one" errors.
// Before:for i := 0; i < 5; i++ { ... }
// After:for i := range 5 { ... }3. New Implementation of the math/rand/v2 Package
The math/rand package has received a second version — math/rand/v2. This is not just an update, but a complete overhaul focused on speed and quality of random number generation.
- Performance: Number generation has become significantly faster (in some benchmarks, up to 2-3 times).
- Algorithms: Modern and more reliable algorithms are used (e.g., ChaCha8 for the default generator).
- Convenience: The new API simplifies working with generators, and a number of deprecated functions have been removed.
The old math/rand package is still available for backward compatibility, but for new projects it is recommended to use math/rand/v2.
Other Important Improvements
- Improved routing in net/http: The
net/httppackage now supports a new way of registering handlers using patterns, close to the style of standard frameworks. Developers can define more flexible routes, including substitutions and HTTP methods. - Garbage collection optimization: The garbage collector has become more efficient, leading to reduced latency and lower peak memory consumption in some scenarios.
- Standard library updates: Small but useful changes have been made to working with slices, maps, and strings, improving performance and stability.
- Tooling improvements