Bird
Raised Fist0
Rustprogramming~10 mins

Immutable references in Rust - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Immutable references
Create variable x
↓
Create immutable reference &x
↓
Use &x to read value
↓
Try to modify x through &x?
No→Compile error
↓
End
This flow shows creating a variable, making an immutable reference to it, using that reference to read the value, and that modification through the reference is not allowed.
Execution Sample
Rust
fn main() {
    let x = 10;
    let r = &x;
    println!("{}", r);
}
This code creates an integer variable, makes an immutable reference to it, and prints the value through the reference.
Execution Table
StepActionVariable/ReferenceValueNotes
1Declare xx10x holds value 10
2Create immutable reference r to xr&10r points to x, cannot modify x through r
3Print value via rOutput10Prints the value x points to
4Try to modify x through rErrorCompile-time errorImmutable reference forbids modification
💡 Execution stops after printing because modification through immutable reference is not allowed
Variable Tracker
VariableStartAfter Step 2After Step 3Final
xuninitialized101010
runinitialized&10&10&10
Key Moments - 2 Insights
Why can't we change the value of x through the immutable reference r?
Because r is an immutable reference, Rust enforces that you cannot modify the value it points to. See execution_table row 4 where trying to modify causes a compile-time error.
Does creating an immutable reference copy the value of x?
No, the reference r points to the original x without copying. It just allows read-only access. See execution_table row 2 where r is &10, not a new 10.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of r after step 2?
A&10
B10
Cuninitialized
DCompile-time error
💡 Hint
Check the 'Variable/Reference' and 'Value' columns at step 2 in the execution_table.
At which step does the program print the value 10?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Action' and 'Output' columns in the execution_table.
If r was a mutable reference, what would change in the execution table?
AStep 3 would print a different value
BStep 4 would succeed without error
CStep 2 would not create r
DStep 1 would fail
💡 Hint
Consider the note in step 4 about compile-time error due to immutability.
Concept Snapshot
Immutable references in Rust:
- Created with &variable
- Allow read-only access to the value
- Prevent modification through the reference
- Multiple immutable references allowed
- Compiler enforces safety at compile time
Full Transcript
This example shows how Rust handles immutable references. First, a variable x is created with value 10. Then, an immutable reference r is made to x using &x. This reference allows reading the value but forbids any changes. When printing r, the program outputs 10. If we try to modify x through r, the compiler stops us with an error. This ensures safety by preventing unexpected changes through references.

Practice

(1/5)
1. What does an immutable reference in Rust allow you to do?
easy
A. Prevent any access to the data
B. Read data without changing it
C. Create multiple mutable references
D. Change data while reading it

Solution

  1. Step 1: Understand the purpose of immutable references

    Immutable references allow you to look at data without changing it.
  2. Step 2: Compare options with this understanding

    Only Read data without changing it correctly states that immutable references let you read data without changing it.
  3. Final Answer:

    Read data without changing it -> Option B
  4. Quick Check:

    Immutable reference = read-only access [OK]
Hint: Immutable references only allow reading data [OK]
Common Mistakes:
  • Thinking immutable references allow data modification
  • Confusing mutable and immutable references
  • Believing immutable references block all access
2. Which of the following is the correct syntax to create an immutable reference to a variable x in Rust?
easy
A. let ref = x&;
B. let ref = *x;
C. let ref = &mut x;
D. let ref = &x;

Solution

  1. Step 1: Recall syntax for immutable references

    In Rust, an immutable reference is created using the ampersand before the variable: &x.
  2. Step 2: Check each option

    let ref = &x; uses &x correctly. let ref = *x; uses dereference operator incorrectly. let ref = &mut x; creates a mutable reference, not immutable. let ref = x&; is invalid syntax.
  3. Final Answer:

    let ref = &x; -> Option D
  4. Quick Check:

    Immutable reference syntax = &variable [OK]
Hint: Use & before variable name for immutable reference [OK]
Common Mistakes:
  • Using *x instead of &x
  • Confusing mutable (&mut) with immutable (&)
  • Writing invalid syntax like x&
3. What will be the output of this Rust code?
let x = 10;
let r1 = &x;
let r2 = &x;
println!("{} and {}", r1, r2);
medium
A. Compilation error due to multiple references
B. Runtime error
C. 10 and 10
D. 10 and 0

Solution

  1. Step 1: Understand multiple immutable references

    Rust allows multiple immutable references to the same data at the same time without error.
  2. Step 2: Check the print statement

    Both r1 and r2 point to x which is 10, so printing them shows "10 and 10".
  3. Final Answer:

    10 and 10 -> Option C
  4. Quick Check:

    Multiple immutable refs print same value [OK]
Hint: Multiple immutable references can coexist safely [OK]
Common Mistakes:
  • Thinking multiple immutable references cause errors
  • Expecting runtime errors from references
  • Confusing mutable and immutable references rules
4. Identify the error in this Rust code snippet:
let mut x = 5;
let r1 = &x;
let r2 = &mut x;
println!("{} and {}", r1, r2);
medium
A. Cannot have mutable and immutable references at the same time
B. Missing semicolon after let r1
C. Cannot print references directly
D. Variable x should not be mutable

Solution

  1. Step 1: Check reference rules in Rust

    Rust forbids having a mutable reference while immutable references exist to the same variable.
  2. Step 2: Analyze the code

    Here, r1 is an immutable reference and r2 is a mutable reference to x at the same time, causing a compile error.
  3. Final Answer:

    Cannot have mutable and immutable references at the same time -> Option A
  4. Quick Check:

    Mutable + immutable refs together = error [OK]
Hint: Mutable and immutable refs can't coexist simultaneously [OK]
Common Mistakes:
  • Ignoring Rust's borrowing rules
  • Thinking printing references causes error
  • Assuming mutability of variable is the problem
5. Given this Rust function:
fn print_value(val: &i32) {
    println!("Value is {}", val);
}

fn main() {
    let mut num = 20;
    let r1 = #
    print_value(r1);
    let r2 = &mut num;
    *r2 += 5;
    print_value(&num);
}

What is the output when this program runs?
hard
A. Value is 20\nValue is 25
B. Compilation error due to mutable and immutable references
C. Value is 25\nValue is 25
D. Runtime error

Solution

  1. Step 1: Analyze references in main function

    First, an immutable reference r1 to num is created and passed to print_value. Then a mutable reference r2 is created after r1 is no longer used.
  2. Step 2: Check Rust borrowing rules

    Rust allows mutable references after immutable references are no longer used. Here, r1 is used only in print_value, so r2 creation is valid.
  3. Step 3: Determine output

    First print_value prints 20, then after incrementing via r2, second print_value prints 25.
  4. Final Answer:

    Value is 20 Value is 25 -> Option A
  5. Quick Check:

    Immutable ref used before mutable ref creation [OK]
Hint: Mutable ref can be created after immutable ref is no longer used [OK]
Common Mistakes:
  • Assuming code runs into compile error
  • Ignoring Rust's borrowing rules about scopes
  • Thinking mutable ref can coexist with immutable ref simultaneously
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