🎓 A1Learner
🔍

Rust Freezing

Freezing is shadowing a mut variable with a plain let of the same name. The new binding is immutable, so the value cannot change.

Freeze with one line

Shadow a mut variable inside a block. The value is locked while that block runs. Code there can look, not touch:

let mut count = 7;
{
    let count = count;
    println!("frozen = {count}");
}

A frozen value refuses changes

Inside the block, this line fails — the name points at the new immutable binding, not the mut one:

let count = count;
count = 50; // error E0384: cannot assign twice to an immutable variable

The freeze ends with the block

After the block, the name points at the mut variable again, and changes work as before:

let mut count = 7;
{ let count = count; }
count = 3;
println!("count = {count}");

Example

fn main() {
    let mut count = 7;
    println!("before = {count}");
    {
        let count = count;
        println!("frozen = {count}");
    }
    count = 3;
    println!("after = {count}");
}

Key points

  • Freezing changes nothing underneath: the original variable keeps its value the whole time

In this example, count starts as a mut variable holding 7, and the first line prints before = 7. Inside the block, let count = count; creates a new immutable count that hides the mut one. That inner count is frozen. It prints frozen = 7. Trying to change it inside the block would fail with E0384. When the block ends, the frozen copy is gone. The outer mut count is back. Setting count to 3 works again. The last line prints after = 3.

Note

Freezing is not a special lock feature.

It is just shadowing plus the normal immutable rule — two simple rules, working together.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

Inside a block where a mut variable has been frozen by let count = count;, what does count = 50; do?