Bird
Raised Fist0
Rustprogramming~10 mins

Mutable references in Rust - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Mutable references
Create variable x
↓
Create mutable reference &mut x
↓
Use mutable reference to change x
↓
x is updated
↓
End of scope, mutable reference dropped
This flow shows creating a variable, making a mutable reference to it, changing the variable through the reference, and then ending the reference's scope.
Execution Sample
Rust
fn main() {
    let mut x = 5;
    let y = &mut x;
    *y += 1;
    println!("{}", *y);
}
This code creates a mutable variable x, makes a mutable reference y to x, changes x through y, and prints the updated value.
Execution Table
StepActionVariable xReference yOutput
1Declare mutable x = 55None
2Create mutable reference y = &mut x5Points to x (5)
3Modify *y += 1 (change x through y)6Points to x (6)
4Print *y6Points to x (6)6
5End of main, references dropped6None
💡 Program ends after printing updated x value 6
Variable Tracker
VariableStartAfter Step 2After Step 3Final
x5566
yNoneMutable reference to x (5)Mutable reference to x (6)Dropped
Key Moments - 2 Insights
Why does changing *y also change x?
Because y is a mutable reference to x, so modifying *y directly changes the original variable x, as shown in step 3 of the execution_table.
Can we use x directly while y exists as a mutable reference?
No, Rust enforces that while a mutable reference y exists, x cannot be used directly to avoid conflicts. This is why we only modify x through y in step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of x after step 3?
A5
B7
C6
DUndefined
💡 Hint
Check the 'Variable x' column at step 3 in the execution_table.
At which step is the mutable reference y created?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Action' column describing when y is assigned.
If we remove the * before y in '*y += 1', what happens?
ACompilation error because y is a reference
Bx is incremented by 1
Cy becomes 1
DNothing changes
💡 Hint
Dereferencing is needed to modify the value y points to, see step 3.
Concept Snapshot
Mutable references in Rust:
- Use &mut to create a mutable reference.
- Modify the original variable by dereferencing (*ref).
- Only one mutable reference allowed at a time.
- Original variable cannot be used while mutable reference exists.
- Mutable reference scope ends when it goes out of scope.
Full Transcript
This example shows how to create a mutable variable x, then create a mutable reference y to x using &mut. We modify x by changing *y, which updates x's value. The program prints the updated value 6. Rust ensures safe access by allowing only one mutable reference at a time and forbidding direct use of x while y exists. The mutable reference is dropped at the end of the scope.

Practice

(1/5)
1. What does a mutable reference &mut allow you to do in Rust?
easy
A. Prevent any changes to the value it points to
B. Create multiple immutable references at the same time
C. Move ownership of the value to another variable
D. Change the value it points to without taking ownership

Solution

  1. Step 1: Understand what &mut means

    The &mut symbol creates a mutable reference, which means you can change the value it points to without taking ownership.
  2. Step 2: Compare with other options

    Options B and D describe immutable references or no changes allowed, and C talks about ownership transfer, which is different from mutable references.
  3. Final Answer:

    Change the value it points to without taking ownership -> Option D
  4. Quick Check:

    Mutable reference = change value without ownership [OK]
Hint: Mutable references let you change data without moving ownership [OK]
Common Mistakes:
  • Confusing mutable references with ownership transfer
  • Thinking multiple mutable references are allowed simultaneously
  • Believing mutable references prevent changes
2. Which of the following is the correct syntax to create a mutable reference to a variable num in Rust?
easy
A. let ref = #
B. let ref = &mut num;
C. let ref = *num;
D. let ref = mut #

Solution

  1. Step 1: Identify the syntax for mutable references

    In Rust, to create a mutable reference, you use &mut before the variable name.
  2. Step 2: Check each option

    A creates an immutable reference, B dereferences the value, and D has incorrect syntax order.
  3. Final Answer:

    let ref = &mut num; -> Option B
  4. Quick Check:

    Mutable reference syntax = &mut variable [OK]
Hint: Use &mut before variable name for mutable reference [OK]
Common Mistakes:
  • Forgetting the 'mut' keyword after &
  • Placing 'mut' before & incorrectly
  • Using * instead of &mut for references
3. What will be the output of the following Rust code?
fn main() {
    let mut x = 5;
    let r = &mut x;
    *r += 1;
    println!("{}", x);
}
medium
A. 6
B. Runtime panic
C. Compilation error
D. 5

Solution

  1. Step 1: Understand the mutable reference usage

    The variable x is mutable. A mutable reference r is created to x. The value pointed by r is incremented by 1 using *r += 1;.
  2. Step 2: Determine the final value of x

    Since r points to x, incrementing *r changes x from 5 to 6. The print statement outputs 6.
  3. Final Answer:

    6 -> Option A
  4. Quick Check:

    Mutable reference modifies original value = 6 [OK]
Hint: Dereference mutable ref with * to change original value [OK]
Common Mistakes:
  • Expecting original value unchanged
  • Confusing reference with copy
  • Thinking code causes compile error
4. What is wrong with this Rust code?
fn main() {
    let mut val = 10;
    let r1 = &mut val;
    let r2 = &mut val;
    *r1 += 1;
    *r2 += 1;
    println!("{}", val);
}
medium
A. Dereferencing mutable references is not allowed
B. Cannot mutate a variable declared as mutable
C. Cannot have two mutable references to the same variable at the same time
D. Missing semicolon after println!

Solution

  1. Step 1: Identify the mutable references

    The code creates two mutable references r1 and r2 to the same variable val at the same time.
  2. Step 2: Recall Rust's borrowing rules

    Rust allows only one mutable reference at a time to prevent data races. Having two mutable references simultaneously causes a compile-time error.
  3. Final Answer:

    Cannot have two mutable references to the same variable at the same time -> Option C
  4. Quick Check:

    Only one mutable reference allowed at once [OK]
Hint: Only one mutable reference allowed at a time [OK]
Common Mistakes:
  • Trying to create multiple mutable references simultaneously
  • Thinking mutable references can be copied freely
  • Ignoring Rust's borrowing rules
5. Given the following code, what is the correct way to safely modify the value inside data using mutable references without causing a compile error?
fn main() {
    let mut data = 100;
    let r1 = &data;
    let r2 = &mut data;
    *r2 += 50;
    println!("{}", data);
}
hard
A. Remove the immutable reference r1 before creating r2
B. Change r2 to an immutable reference &data
C. Use two mutable references r1 and r2 simultaneously
D. Make data immutable by removing mut

Solution

  1. Step 1: Understand Rust's borrowing rules

    Rust does not allow mutable and immutable references to the same variable at the same time. Here, r1 is immutable and r2 is mutable, causing a conflict.
  2. Step 2: Fix the code by removing the immutable reference

    Removing r1 allows only the mutable reference r2 to exist, so modifying data through r2 is safe and allowed.
  3. Final Answer:

    Remove the immutable reference r1 before creating r2 -> Option A
  4. Quick Check:

    Mutable and immutable refs cannot coexist [OK]
Hint: Remove immutable refs before mutable refs to avoid errors [OK]
Common Mistakes:
  • Trying to use mutable and immutable references simultaneously
  • Changing mutable ref to immutable without reason
  • Making variable immutable but still trying to mutate
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard