Skip to content
Tutorials Center
My learning

Topics

Lesson 111 of 132 ยท Advanced Rust

What's New in Rust 2021 to 1.99

A guided tour of the Rust features added since the 2021 edition - let-else, GATs, async closures, LazyLock, trait upcasting, let chains and the 2024 edition changes - each with runnable code.

Rust ships a new stable release every six weeks, and the language you learn today is noticeably richer than the one in books and blog posts from 2020. Much older advice is still right, but a lot of it has a shorter, safer modern equivalent. This lesson walks through the changes that matter most between the 2021 edition and the current compiler (1.99 on our server, edition 2024), explains each in a few paragraphs and gives you a short program that runs here, so you can see the feature working instead of taking our word for it.

For every feature we name the Rust version that stabilized it. Features can be used on any compiler at least that new; the edition you choose in Cargo.toml (edition = "2024") only controls a small set of changes that would break old code. Editions are opt-in per crate, and crates of different editions work together in one program. The oldest feature here needs 1.56, so everything runs on today's toolchain.

The timeline at a glance

Feature Since What it replaces
2021 edition: disjoint closure captures, arrays by value in for, wider prelude 1.56 whole-struct captures, .iter() on arrays
Inline format arguments 1.58 println!("{}", name)
let ... else 1.65 match with an early return
Generic associated types (GATs) 1.65 boxing or workarounds for lending iterators
OnceCell / OnceLock, Option::is_some_and 1.70 lazy_static-style crates, map(..).unwrap_or(false)
async fn in traits 1.75 the async-trait crate (in many cases)
slice::chunk_by, c-string literals c"..." 1.77 manual grouping loops, CString::new
Inline const { } blocks 1.79 helper const items
LazyLock / LazyCell, exclusive range patterns a..b, Option::take_if 1.80 lazy_static, once_cell, a..=b-1
#[expect(lint)] 1.81 #[allow(lint)] that never gets cleaned up
&raw const/&raw mut, unsafe extern, Option::is_none_or, iter::repeat_n, is_sorted, use<..> precise capturing 1.82 addr_of!, bare extern, manual loops
isqrt on integers 1.84 float square-root tricks
Async closures, Waker::noop, edition 2024 1.85 closures returning boxed futures
Trait upcasting, Vec::pop_if, get_disjoint_mut 1.86 helper methods, split_at_mut
Let chains (2024 edition only) 1.88 nested if let pyramids

Release notes for later versions keep adding standard-library methods; the best habit is to read the notes for each release (rustc --version, then the release blog post) and use cargo clippy, which suggests modern replacements for old patterns.

Everyday ergonomics (2021 edition to 1.70)

Rust Format captures, let-else, array iteration and closure captures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

let ... else is the biggest readability win of this group. The else block must diverge: it has to return, break, continue or panic, because the bindings must exist afterwards. The compiler checks this:

Rust The else block of let-else must diverge (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The error is error[E0308]: elseclause oflet...else does not diverge. Adding return 0; after the println! fixes it. (See Patterns in Depth for more on destructuring and Option for is_some_and.)

Before the 2021 edition, a closure that used p.score captured the whole p, so name_ref and bump could not coexist. Now the closure captures precisely the field it touches. That is the "disjoint captures" change, and it removes a whole class of confusing borrow errors (The Borrow Checker in Practice).

Smaller language additions (1.80 to 1.84)

Rust Exclusive range patterns, expect and friends

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Exclusive ranges make match arms line up with half-open intervals, the convention used for slices and for loops. #[expect] is the better allow: when the code is fixed and the lint stops firing, the compiler tells you to remove the attribute, so suppressions never rot. See Attributes and Conditional Compilation.

Generic associated types (1.65)

An associated type could not be generic over a lifetime until GATs. That made "lending" iterators, whose items borrow from the iterator itself, impossible to write as a trait. The standard Iterator cannot do it either: every item must outlive the call to next.

Rust A lending iterator: overlapping mutable windows

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The standard library's windows_mut does not exist for exactly this reason: overlapping &mut windows can only be handed out one at a time. The trait above encodes that rule in the type: each returned window borrows the iterator, so you cannot call next again until the window is gone. GATs also power async-friendly traits and database "row" abstractions. Read Associated Types and Generic Traits for the details.

Async: traits, closures and a mini executor (1.75, 1.85)

async fn can be used in traits since 1.75, and async closures (async |x| ..., with the AsyncFn family of traits in the prelude) since 1.85. Rust's standard library has no executor, but with Waker::noop() (1.85) we can write a tiny one and run futures that never wait for I/O, which is enough to show the syntax:

Rust async fn in a trait and an async closure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

An async closure can borrow from its environment (here source) and return a future that borrows from the closure itself. With a normal closure returning an async block this was awkward or impossible to express. For the full story see Async/Await Basics and Futures by Hand.

Statics, constants and C strings (1.70 to 1.79)

Rust LazyLock, OnceLock, inline const and c-string literals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

These replace the lazy_static and once_cell crates in most code. Do not put a Mutex around a LazyLock unless you really mutate the value (Mutex and RwLock). C-string literals matter mainly for FFI (Foreign Function Interface), where a CString::new("...").unwrap() allocation used to be necessary.

Unsafe made explicit (1.82 and the 2024 edition)

Rust 1.82 let you write unsafe extern blocks, in which each declaration can be marked safe or unsafe; the 2024 edition requires unsafe extern, and requires the longer attribute spelling #[unsafe(no_mangle)], because a duplicate symbol name is a soundness problem. &raw const x and &raw mut x create raw pointers directly, without going through a reference (which would be a promise about validity and aliasing).

Rust unsafe extern, safe fn declarations and raw borrows

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The safe fn line is a promise you make about code you did not write, so use it sparingly. More background is in Unsafe Rust and Foreign Function Interface.

Standard library additions worth knowing (1.77 to 1.86)

Rust Trait upcasting and new slice, Vec and Option methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

get_disjoint_mut replaces the old dance with split_at_mut and returns an error if two indices are equal or out of range. pop_if, chunk_by and is_none_or are all small, but they remove loops and map(...).unwrap_or(...) chains that used to appear everywhere. Compare the last with is_some_and: both answer a yes/no question about an Option without a match.

Let chains (1.88, 2024 edition)

Before let chains, combining a pattern match with extra conditions meant nesting if let inside if let or using match with guards. Now you can join let patterns and boolean conditions with && in if and while:

Rust Let chains in if and while

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Let chains are available only in edition 2024, because they depend on the new scoping rules for temporaries described below. Bindings from an earlier let are visible in the later conditions, and are dropped properly if a later condition fails. See if, else if and else.

What the 2024 edition changed

An edition may change small things that would otherwise break code. 2024 (stabilized with Rust 1.85) mostly tidies up places where earlier rules were surprising. cargo fix --edition migrates a project automatically. The changes you will notice:

  1. impl Trait in return position captures all in-scope lifetimes.
  2. Temporaries in the tail expression of a block are dropped before the block's local variables.
  3. if let temporaries are dropped before the else branch.
  4. unsafe extern blocks and #[unsafe(no_mangle)] are required (shown above), and unsafe_op_in_unsafe_fn warns by default.
  5. gen is a reserved keyword (write r#gen if you need the name); Box<[T]> iterates by value; Cargo's resolver understands rust-version.

Returned iterators capture lifetimes

Before 2024, fn evens(v: &[i32]) -> impl Iterator<Item = i32> captured no lifetime from v, so the body that really borrows v was a compile error, and you needed + '_ or a trick. Now the compiler captures every generic and lifetime in scope. That is what you almost always want, but it makes the returned value borrow its input:

Rust The returned iterator borrows its input (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The real message is error[E0505]: cannot move out of data because it is borrowed: the iterator returned by evens still holds the borrow. The compiler even notes that "Rust 2024 has adjusted the impl Trait lifetime capture rules" and suggests the use<> fix below. If a function really returns something that does not depend on its arguments, say so with the use<> precise-capturing syntax (1.82):

Rust Opting out of capturing with use

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Temporaries drop earlier

A temporary is a value created in the middle of an expression and never named, such as the guard returned by mutex.lock(). In edition 2021, a temporary created in the last expression of a block lived longer than the block's local variables, which led to errors where a lock guard borrowed from a local that was already gone. In 2024 the temporary is dropped first. Likewise the temporaries of an if let scrutinee no longer live into the else branch, which removes a classic source of deadlocks (a lock still held while the else branch tries to take it again). Watch the order of drops:

Rust Drop order of temporaries in edition 2024

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

In edition 2024 the temporary in the tail expression is dropped before the local variable, and the scrutinee temporary is dropped before the else block runs. In edition 2021 both orders were the other way round. If you maintain old code and see lock or borrow errors after migrating, these are the likely cause; cargo fix --edition inserts explicit let bindings to keep the old behavior where it matters.

How to stay current

  • Read the release notes every six weeks (or at least before updating); skim the "Stabilized APIs" list.
  • Run cargo clippy regularly: many lints exist exactly to point at old idioms (for example manual_let_else, manual_is_variant_and).
  • Set rust-version in Cargo.toml to the oldest compiler you support, so Cargo and Clippy do not suggest features that are too new.
  • Start new projects on edition = "2024" and migrate old ones with cargo fix --edition.
  • Be skeptical of a feature's version number if you are not sure; the standard library docs show "Stable since" next to every item.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What must the else block of a let ... else statement do?

    The bindings must exist after the statement, so the else block cannot fall through. Otherwise the compiler reports E0308.
  2. 2. Which problem do generic associated types (GATs) solve?

    With type Item<'a>, each item can borrow from the iterator for a different lifetime, which a plain Iterator cannot express.
  3. 3. What replaced the lazy_static crate in the standard library?

    LazyLock (1.80) initializes a static on first use; OnceLock (1.70) covers set-once cases.
  4. 4. What does edition 2024 change about impl Trait in return position?

    That default removes the old need for + '_ tricks. Precise capturing with use<..> (1.82) lists exactly what is captured.
  5. 5. Let chains (if let ... && let ... && condition) require which edition?

    Let chains were stabilized in Rust 1.88 for the 2024 edition only, because they rely on its new temporary-scope rules.

Summary

  • Features depend on the compiler version; only a few breaking changes depend on the edition. Use edition = "2024" for new code.
  • Everyday wins: inline format captures, let ... else, is_some_and/is_none_or, exclusive range patterns, #[expect], chunk_by, pop_if, repeat_n, get_disjoint_mut.
  • Type-system growth: GATs, async fn in traits, async closures, trait upcasting, inline const, precise capturing with use<..>.
  • LazyLock, OnceLock and c-string literals replace common external crates and allocations.
  • Unsafe is more explicit: unsafe extern, safe fn declarations, #[unsafe(no_mangle)], &raw.
  • Edition 2024 captures lifetimes in returned impl Trait, drops tail-expression and if let temporaries earlier, and enables let chains.
  • Read each release's notes and let Clippy suggest modern replacements.

Next: Project: Guessing Game