Skip to Content
Course content

6: Variables and Mutability

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're handling a legal contract. Once that contract is signed and notarized, you can't just take an eraser to the "Payment Amount" line and scribble in a new number. If you want a different amount, you have to draft an entirely new contract. Now, compare that to a whiteboard in a conference room. You write a number up there, and five minutes later, you can wipe it away and write something else in the exact same spot.

In Rust, variables work exactly like this. By default, every variable you create is like that signed contract: immutable. If you want the whiteboard experience, you have to explicitly ask for it.

The Default: Ink on Paper

When you use let, you're telling Rust, "This value is set, and it isn't going to change." I'll be honest—when I first started with Rust, this drove me crazy. I kept trying to update variables and the compiler kept yelling at me. But there's a method to the madness. By making things immutable by default, Rust eliminates a whole category of bugs where a value changes unexpectedly in a complex program.

fn main() {
    let player_name = "Aris"; 
    println!("Welcome, {}!", player_name);

    // This line would cause a compiler error:
    // player_name = "Zelda"; 
}

If you tried to run that last line, Rust would stop you immediately. It's not being stubborn; it's protecting you. It ensures that once player_name is set, it stays that way for the rest of its life.

The Escape Hatch: Using mut

Obviously, you can't build a real app if nothing ever changes. You need a way to track things like a player's health, a shopping cart total, or a countdown timer. This is where the mut keyword comes in. Adding mut transforms your "signed contract" into a "whiteboard."

fn main() {
    let mut health = 100;
    println!("Starting health: {}", health);

    health = 80; // This is perfectly legal now
    println!("After taking damage: {}", health);
    
    health = 60;
    println!("Ouch, again: {}", health);
}

I usually recommend staying immutable as long as possible. Only add mut when you absolutely have to. It makes your code much easier to reason about because you can look at a variable and know for a fact it isn't changing behind your back.

Starting Fresh with Shadowing

There is a third option that often confuses people: shadowing. This happens when you use the let keyword again with the same variable name. This isn't the same as mutability. You aren't changing the value inside the "bucket"; you're throwing the old bucket away and putting a brand new one in its place with the same name.

Shadowing is incredibly useful when you want to change the type of a variable but keep the name. For example, imagine taking a string of numbers from a user and needing to turn it into an actual integer.

fn main() {
    let space_fuel = "42"; // This is a string (&str)
    println!("Fuel string: {}", space_fuel);

    // We "shadow" the previous variable. 
    // It's now an integer (i32), but keeps the same name.
    let space_fuel: i32 = space_fuel.parse().expect("Not a number!");
    println!("Fuel integer: {}", space_fuel);
}

If we had used mut for this, it would have failed because a mut variable cannot change its data type. Shadowing lets us transform the data while keeping our naming clean.




📋 Practical Task

Build a Spaceship Fuel Monitor

Write a small Rust program that simulates a spaceship's fuel system. Your code should demonstrate all three concepts we covered: immutability, mutability, and shadowing.

  • Part 1: Create an immutable variable called ship_name and assign it a value.
  • Part 2: Create a mutable variable called fuel_level starting at 100. Simulate the ship taking off by decreasing this value twice (e.g., subtracting 20, then subtracting 10).
  • Part 3: Create a variable called fuel_report as a string (e.g., "50"). Then, use shadowing to convert that fuel_report string into an actual integer so it can be used for calculations.
  • Part 4: Print all three variables to the console to verify they updated correctly.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.