🎓 A1Learner
🔍

Rust Declare First

A declare-first let statement names a variable without giving it a value. A later line fills the value in.

Declare now, fill later

The first fill is initialisation, not a change. So no mut is needed. That holds even though the value arrives a line later:

let total;
total = 6 * 7;
println!("total = {total}");

The type rides on the declare line

The type can ride on the declare line. Both branches fill level, so every path reaches the print with a value:

let level: u8;
let marks = 72;
if marks >= 40 { level = 2; } else { level = 1; }
println!("level = {level}");

Fill it inside a block

The value can be worked out inside a block. The helper name price dies at the closing brace, but the fill stays:

let total;
{
    let price = 30;
    total = price + 5;
}
println!("total = {total}");

Using it too early fails

Read the name before any fill and the compiler stops you:

let x: i32;
println!("{x}"); // error E0381: x is not initialised yet
x = 5;

Example

fn main() {
    let score;
    {
        let bonus = 5;
        score = 40 + bonus;
    }
    let level: u8;
    if score >= 40 {
        level = 2;
    } else {
        level = 1;
    }
    println!("score = {score}");
    println!("level = {level}");
}

Key points

  • Once filled, an immutable variable cannot be filled again: a second assignment fails with error E0384
  • The name comes first and the value follows: both parts together make one complete variable.

In this example, score is declared with no value. Inside the block, bonus is 5. score = 40 + bonus fills score for the first time. That is initialisation, so no mut is needed. score stays usable after the block ends. Next, level is declared with its type, u8. The if branch fills it with 2. The else branch fills it with 1. So every path fills it before the prints. score is 45, so the if branch runs, and the prints show score = 45 and level = 2.

Note

Prefer let name = value in one line when the value is ready.

Split the two steps only when a block or branches must work the value out first.

A far-away fill is harder to read.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

You declare let x; and fill it only inside an if branch, then print x after the if. What happens?