Search⌘ K

Let Without Assignment

Explore how to use the let statement in Rust without immediate assignment, understand the rules for immutable and mutable variables, and learn best practices to avoid unassigned variables and compilation errors.

We'll cover the following...

So far, we’ve immediately assigned values to variables with let. However, it’s valid in Rust to separate these steps out. For example:

Rust 1.40.0
fn main() {
let x;
x = 5;
println!("x == {}", x);
let mut y;
y = 5;
y += 1;
println!("y == {}", y);
}

I point this out now because it may be surprising that:

  • x is an immutable variable

  • But we’re allowed to say x = 5 ...