skip to content

In Rust, why does an `if let` on `cache.borrow()` that calls `borrow_mut()` in its `else` panic on edition 2021 but run on 2024, and what changed for tail expressions?

level: seniorimportance: should knowfreq 35%

answer

  1. when the scrutinee's temporary is dropped
  2. dropped before else, from 2024
  3. tail temporaries now drop before locals
  4. if_let_rescope rewrites to match

basics

~20 s

On 2021 the Ref temporary from cache.borrow() in an if let scrutinee lives until the whole if let ends, so borrow_mut() in else panics. Rust 2024 drops it before entering else, and also drops tail-expression temporaries before the block's locals.

solid answer

~50 s

A temporary created while evaluating an `if let` scrutinee, here the `Ref` guard returned by `cache.borrow()`, used to live until the end of the enclosing statement, so the `else` branch still held a shared borrow and `borrow_mut()` panicked with "RefCell already borrowed". The 2024 edition drops scrutinee temporaries once the then-block finishes or before control enters `else`, so the same code runs. `cargo fix --edition` (lint `if_let_rescope`) rewrites such an `if let` into a `match`, whose scrutinee temporaries still live to the end of the statement; that preserves the 2021 behaviour, panic included, so revert it where the early drop is the fix. Tail expressions changed too: their temporaries are now dropped before the block's locals, so `q.borrow().len()` at the end of a function compiles instead of failing with E0597, while `{ &String::from("1234") }.len()` now fails with E0716.

code

rust · 17 lines
rust
use std::cell::RefCell;

fn cached(cache: &RefCell<Option<u32>>) -> u32 {
    if let Some(v) = *cache.borrow() {
        v
    } else {
        // compute the value and store it for the next call
        *cache.borrow_mut() = Some(42);
        42
    }
}

fn main() {
    let cache = RefCell::new(None);
    println!("first:  {}", cached(&cache));
    println!("second: {}", cached(&cache));
}

go deeper

for a junior

Recall that on Rust 2024 the temporary from an if let scrutinee, such as a RefCell borrow guard, is dropped before the else branch runs.

for a middle

Explain temporaries and their drop scopes, why the 2021 if let held a borrow through else, and how 2024 also drops tail-expression temporaries before the block's locals.

for a senior

Show how you review a migration: revert if let to match rewrites where early dropping is the fix, investigate each tail_expr_drop_order warning, and repair E0716 breakages with let bindings.

for a principal

Weigh accepting the new drop timing against preserving old behaviour crate-wide, and decide which drop-sensitive types, such as guards and span objects, earn a mandatory reviewer during migration.

## Temporaries and their drop scopes A **temporary** is an unnamed value Rust creates while evaluating an expression: the `Ref` guard returned by `RefCell::borrow`, a `String` built only to be borrowed, a lock guard. Each temporary is dropped at the end of its **temporary scope**, which is usually the end of the enclosing statement. When a temporary has a `Drop` implementation with an effect, such as releasing a borrow, unlocking or flushing, the exact drop point decides what the surrounding code may do. The 2024 edition shortened two of those scopes. ## The `if let` change The **scrutinee** of `if let PAT = EXPR` is `EXPR`. Take a lazily filled cache: ```rust fn cached(cache: &RefCell<Option<u32>>) -> u32 { if let Some(v) = *cache.borrow() { v } else { *cache.borrow_mut() = Some(42); 42 } } ``` `cache.borrow()` returns a `Ref`, a temporary that keeps the `RefCell` marked as shared-borrowed until it is dropped. | Edition | When the scrutinee's `Ref` is dropped | First call to `cached` | |---|---|---| | 2021 | At the end of the whole `if let`, after `else` has run | Panics: "RefCell already borrowed" | | 2024 | When the then-block finishes, or before control enters `else` | Stores and returns 42 | On 2021, `borrow_mut()` inside `else` finds the shared borrow still alive and panics. On 2024, the guard is gone before `else` starts. The same shape with a lock guard in place of the `Ref` is a classic deadlock; guards and deadlocks are covered with `Mutex`. ## What `cargo fix --edition` does with it The `if_let_rescope` lint fires when an `if let` scrutinee creates a temporary with a non-trivial `Drop`, or when the change causes a lifetime problem. Its suggested fix rewrites the `if let` into a `match`: ```rust match *cache.borrow() { Some(v) => { v } _ => { *cache.borrow_mut() = Some(42); 42 }} ``` A `match` scrutinee's temporaries live past the end of the `match`, typically to the end of the statement, exactly like 2021's `if let`. The rewrite is **semantics-preserving**, and it preserves the bug: compiled on 2024, the migrated function still panics with "RefCell already borrowed". The edition guide's advice is to review every `if let` to `match` rewrite: 1. **Revert to `if let`** where holding the temporary through the fallback branch was never intended. That is most cases, and the 2024 behaviour is the fix. 2. **Keep the `match`** where code really relies on the temporary living through the `else`, for example a guard that must stay held while the fallback runs. ## The tail-expression change, in both directions A block's **tail expression** is its final expression without a semicolon, the block's value. Before 2024, temporaries created there outlived the block's own locals and were dropped at the end of the enclosing statement. In 2024 they are dropped at the end of the block, before the locals. Three consequences follow: - **Code that starts compiling.** In `let q = RefCell::new(vec![0u8; n]); q.borrow().len()` as a function's tail, 2021 dropped `q` while the `Ref` temporary still pointed into it: E0597, "`q` does not live long enough". On 2024 the `Ref` goes first and the function compiles. - **Code that stops compiling.** In `let n = { &String::from("1234") }.len();` the temporary `String` used to live until the end of the statement. On 2024 it is dropped at the end of the inner block, and rustc reports E0716, "temporary value dropped while borrowed". The fix is a `let` binding, `let s = { &String::from("1234") }; s.len()`, where temporary lifetime extension keeps the `String` alive. - **Drop order that silently changes.** With a local `_span` and a tail temporary that both implement `Drop`, 2021 drops the local first and the temporary second; 2024 reverses that order. Nothing fails to compile. ## Reviewing the tail-expression change There is no semantics-preserving rewrite for tail expressions, so the `tail_expr_drop_order` lint only warns ("relative drop order changing in Rust 2024") and `cargo fix --edition` changes nothing. Its note says most drop-order changes are harmless and to inspect the `impl Drop`s involved for side effects like releasing locks or sending messages. Review each warning where the two values interact: a span guard that must close after the work it measures, or a guard whose release another local's destructor depends on.

  • Why is rewriting `if let` into `match` the migration's fix if it keeps the old behaviour?
    `cargo fix --edition` only applies semantics-preserving changes, so code means the same on both editions. A `match` scrutinee's temporaries still live to the end of the statement, which is what 2021's `if let` did. Whether the shorter 2024 scope is a fix or a break depends on intent, so the edition guide leaves that review, and reverting to `if let`, to you.
  • How do you fix `let n = { &String::from("1234") }.len();` failing with E0716 on Rust 2024?
    Bind the block to a local first: `let s = { &String::from("1234") }; let n = s.len();`. Temporary lifetime extension then keeps the `String` alive as long as `s`, because the block is the whole `let` initializer and the `String` sits behind a reference. When the block is only an operand of a larger expression, as in the `.len()` call, 2024 drops the temporary at the block's end.

  • On 2024, if let and match still drop scrutinee temporaries at the same point
  • cargo fix's if let to match rewrite applies the new 2024 drop timing
  • The 2024 tail-expression change can only make more code compile
  • tail_expr_drop_order rewrites tail expressions automatically during migration
  • Rust 2024 removed temporary lifetime extension for let bindings

Assumes Rust 1.99; the if let scrutinee and tail-expression temporary scopes changed in the 2024 edition (stable since 1.85), and edition 2021 keeps the old scopes.