Bird
Raised Fist0
Rustprogramming~10 mins

Reference usage patterns in Rust - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Reference usage patterns
Create variable
↓
Create reference & borrow
↓
Use reference to read or modify
↓
Reference goes out of scope
↓
Variable can be used again or dropped
This flow shows how a variable is created, then a reference borrows it temporarily, used safely, and then the reference ends allowing normal use again.
Execution Sample
Rust
fn main() {
    let x = 10;
    let r = &x;
    println!("Reference value: {}", r);
}
This code creates a variable x, then a reference r to x, and prints the value through the reference.
Execution Table
StepActionVariable StatesReference StatesOutput
1Create variable x with value 10x=10r=none
2Create reference r to xx=10r=&x (points to 10)
3Print value via reference rx=10r=&x (points to 10)Reference value: 10
4End of main, variables go out of scopex=droppedr=dropped
💡 Program ends after printing value through reference
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
xuninitialized101010dropped
rnonenone&x (points to 10)&x (points to 10)dropped
Key Moments - 3 Insights
Why can we use r to read x but not change it?
Because r is an immutable reference to x, it only allows reading. Mutable references are needed to change values. See Step 2 and 3 in execution_table.
What happens if we try to use x while r exists?
In Rust, you can read x while immutable references exist, but you cannot mutate x. The reference ensures safe access. This is shown by r borrowing x at Step 2.
Why does the reference r stop existing at the end?
References have a limited scope. When main ends, all variables and references are dropped to free memory, as shown in Step 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 2, what does r point to?
AA new variable
BThe value 10 stored in x
CNothing, r is uninitialized
DA copy of x
💡 Hint
Check the 'Reference States' column at Step 2 in execution_table
At which step does the program print the value through the reference?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Output' column in execution_table
If we changed r to a mutable reference, what would change in the execution?
AWe could modify x through r
Br would no longer point to x
Cx would become immutable
DNothing would change
💡 Hint
Recall that mutable references allow modifying the borrowed value
Concept Snapshot
Reference usage in Rust:
- Use & to create an immutable reference
- References borrow data without taking ownership
- Immutable references allow reading only
- Mutable references (&mut) allow modifying
- References have limited scope and lifetime
Full Transcript
This example shows how Rust uses references to borrow variables safely. First, a variable x is created with value 10. Then, a reference r is made to borrow x immutably. Using r, the program prints the value of x without taking ownership. After printing, the program ends and all variables and references go out of scope and are dropped. This pattern ensures safe access to data without copying or ownership transfer. Immutable references allow reading but not changing the data. Mutable references are needed to modify. The execution table tracks each step, showing variable and reference states and output. Key moments clarify common confusions about mutability and scope. The quiz tests understanding of reference pointing, output timing, and mutable references. The snapshot summarizes the main rules for using references in Rust.

Practice

(1/5)
1. What does the & symbol represent in Rust when used before a variable?
easy
A. A pointer that can be null
B. A mutable reference to the variable, allowing modification
C. A reference to the variable, allowing read-only access without ownership
D. A way to clone the variable's value

Solution

  1. Step 1: Understand the meaning of & in Rust

    In Rust, & creates a reference to a value, which means you can read the value without taking ownership.
  2. Step 2: Differentiate from mutable references and pointers

    &mut is used for mutable references, and Rust references are never null pointers, so & is not a pointer that can be null.
  3. Final Answer:

    A reference to the variable, allowing read-only access without ownership -> Option C
  4. Quick Check:

    & means read-only reference [OK]
Hint: Remember: & means read-only reference, &mut means change allowed [OK]
Common Mistakes:
  • Confusing & with &mut for mutability
  • Thinking & creates a copy of the value
  • Assuming & can be null pointer
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: Recall syntax for mutable references

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

    let ref = # uses & which is an immutable reference. let ref = *num; uses dereference operator * incorrectly here. let ref = mut # has incorrect syntax order.
  3. Final Answer:

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

    Mutable reference syntax = &mut [OK]
Hint: Use &mut before variable for mutable reference [OK]
Common Mistakes:
  • Using & instead of &mut for mutable references
  • Placing mut after & incorrectly
  • Using * instead of & for references
3. What will be the output of the following Rust code?
fn main() {
    let x = 10;
    let y = &x;
    println!("{}", y);
}
medium
A. 10
B. &10
C. Compilation error
D. Memory address of x

Solution

  1. Step 1: Understand the reference y = &x

    Variable y is a reference to x, so it points to the value 10.
  2. Step 2: Printing a reference with println!("{}", y)

    Rust automatically dereferences y when printing, so it prints the value 10, not the address or &10.
  3. Final Answer:

    10 -> Option A
  4. Quick Check:

    Printing reference prints value [OK]
Hint: Printing &var shows value, not address [OK]
Common Mistakes:
  • Expecting &10 to print literally
  • Thinking it prints memory address
  • Assuming compilation error due to reference
4. Identify the error in this Rust code snippet:
fn main() {
    let mut num = 5;
    let r = #
    *r = 10;
    println!("{}", num);
}
medium
A. Cannot assign to *r because r is an immutable reference
B. num should not be mutable
C. Missing semicolon after *r = 10
D. Cannot print num after referencing

Solution

  1. Step 1: Check reference mutability

    Variable r is an immutable reference to num because it is declared as &num, not &mut num.
  2. Step 2: Understand assignment through reference

    You cannot assign a new value through an immutable reference. The line *r = 10; causes a compilation error.
  3. Final Answer:

    Cannot assign to *r because r is an immutable reference -> Option A
  4. Quick Check:

    Immutable reference cannot be used to modify value [OK]
Hint: Use &mut for references if you want to change data [OK]
Common Mistakes:
  • Forgetting to use &mut for mutable references
  • Thinking mut on variable alone allows mutation through immutable ref
  • Ignoring compiler error messages
5. Given a function that takes a mutable reference to a vector and appends a value, which of the following correctly calls the function to add 42 to vec?
fn add_value(v: &mut Vec<i32>) {
    v.push(42);
}

fn main() {
    let mut vec = vec![1, 2, 3];
    // Which call is correct here?
}
hard
A. add_value(&vec);
B. add_value(mut &vec);
C. add_value(vec);
D. add_value(&mut vec);

Solution

  1. Step 1: Understand function parameter type

    The function add_value expects a mutable reference &mut Vec<i32>.
  2. Step 2: Check how to pass mutable reference

    To pass a mutable reference, the variable must be mutable and passed as &mut vec. Passing &vec is immutable reference, and passing vec moves ownership.
  3. Final Answer:

    add_value(&mut vec); -> Option D
  4. Quick Check:

    Mutable reference call uses &mut [OK]
Hint: Pass &mut variable to functions needing mutable reference [OK]
Common Mistakes:
  • Passing immutable reference when mutable is needed
  • Passing ownership instead of reference
  • Incorrect syntax like mut &var
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