Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ THE FIRST BUILD
BUILD NOTE 02 / 53

Make change explicit.

Separate changing a value from introducing a new binding.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

01 Understand the contract

A let binding is immutable unless you opt into mut. Mutation changes the value in an existing binding, so its type stays fixed. Shadowing creates another binding with the same name and can change the type. This is useful when turning raw input into a validated representation. A const is a named compile-time value that needs an explicit type. Prefer the least changeable representation that fits the work: immutable values are easier to reason about, while a small local mutable accumulator is often exactly right.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/variables/src/main.rs
const MAX_RETRIES: u32 = 3;
fn main() {
    let mut attempts = 1;
    attempts += 1;
    let input = " 42 ";
    let input: u32 = input.trim().parse().expect("valid number");
    println!("attempts={attempts}/{MAX_RETRIES}, input={input}");
}
↳ EXPECTED OUTPUT
attempts=2/3, input=42
  1. 1

    MAX_RETRIES has a type and a constant initializer.

  2. 2

    mut allows attempts to be updated in place.

  3. 3

    The second input shadows a string slice with a parsed u32.

From the extracted rust-workbench folder
cargo run -p lesson_variables

03 Mind the boundary

04 Your next build

A SMALL MISSION

Start a mutable score at 10, add 5, then shadow a string with its character count.

Reveal one possible solution +
solutions/variables/src/main.rs
fn main() {
    let mut score = 10;
    score += 5;
    let label = "rust";
    let label = label.chars().count();
    assert_eq!(score, 15);
    assert_eq!(label, 4);
}

05 Check your reasoning

QUICK SIGNAL CHECK

Can shadowing introduce a different type?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.