← Back to Rust Course | Chapter 2: Variables & Types | Lesson 2 of 7

Mutability with mut

Adding the word mut tells Rust that a value is allowed to change later on.

Declaring a Mutable Variable

Adding the mut keyword after let allows the variable's value to be changed later in the program. Without mut, any attempt to reassign the variable is a compile-time error.

Example: Declaring a Mutable Variable

markup
fn main() {
    let mut score = 0;
    println!("Starting score: {}", score);
    score = 10;
    println!("Updated score: {}", score);
}

Mutating in a Loop

Mutable variables are especially useful inside loops, where a value needs to accumulate or change on every iteration, such as a running total.

Example: Mutating in a Loop

markup
fn main() {
    let mut total = 0;
    for n in 1..=5 {
        total += n;
    }
    println!("Total: {}", total);
}

Type Stays Fixed

Even though a mut variable's value can change, its type is fixed for the life of the binding. You cannot store a string in a variable that was first assigned an integer.

Example: Type Stays Fixed

markup
fn main() {
    let mut count: i32 = 1;
    count = count + 1;
    println!("count is now {}", count);
}

Immutable by Default, Opt-in Mutability

Rust chose immutable-by-default so that, when you read code, a plain let binding is a guarantee its value never changes -- making programs easier to reason about, especially when multiple parts of code share data.

Example: Immutable by Default, Opt-in Mutability

markup
fn main() {
    let fixed = 100;
    let mut adjustable = 100;
    adjustable += 1;
    println!("fixed: {}, adjustable: {}", fixed, adjustable);
}
Common Mistakes
  1. Forgetting the mut keyword and then getting a confusing compiler error when trying to reassign a variable.
  2. Assuming mut lets you change a variable's type, when it only allows changing its value, not its type.
  3. Marking everything mut out of habit instead of only the variables that actually need to change.
Chapter Summary
  • Adding mut before a variable name allows its value to be reassigned later.
  • The type of a mutable variable cannot change, only its value.
  • Rust encourages immutability by default to make code easier to reason about and safer to run concurrently.
  • The compiler will warn if a mut variable is never actually mutated.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.