References let you use data without taking ownership. This helps share data safely and avoid copying.
Reference usage patterns in Rust
let ref_variable = &value; // immutable reference let mut_ref_variable = &mut value; // mutable reference
Use & to create an immutable reference (read-only).
Use &mut to create a mutable reference (allows changes).
x and prints its value.let x = 5; let r = &x; // r is a reference to x println!("{}", r);
x, changes the value through the reference, and prints the updated value.let mut x = 10; let r = &mut x; // mutable reference *r += 5; println!("{}", x);
fn print_value(val: &i32) {
println!("Value is {}", val);
}
let num = 7;
print_value(&num);fn add_one(val: &mut i32) {
*val += 1;
}
let mut num = 3;
add_one(&mut num);
println!("{}", num);This program shows how to create immutable and mutable references. It first prints the original value, then updates it through a mutable reference and prints the new value.
fn main() {
let mut score = 42;
{
let score_ref = &score; // immutable reference
println!("Score is {}", score_ref);
}
let score_mut_ref = &mut score; // mutable reference
*score_mut_ref += 8;
println!("Updated score is {}", score);
}You cannot have mutable and immutable references to the same data at the same time.
References help avoid copying large data and keep your program efficient.
Use * to access or change the value a reference points to.
References let you use data without taking ownership.
Use & for read-only access and &mut for changing data.
References help write safe and efficient Rust code.
Practice
& symbol represent in Rust when used before a variable?Solution
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.Step 2: Differentiate from mutable references and pointers
&mutis used for mutable references, and Rust references are never null pointers, so&is not a pointer that can be null.Final Answer:
A reference to the variable, allowing read-only access without ownership -> Option CQuick Check:
&means read-only reference [OK]
- Confusing & with &mut for mutability
- Thinking & creates a copy of the value
- Assuming & can be null pointer
num in Rust?Solution
Step 1: Recall syntax for mutable references
In Rust, to create a mutable reference, you use&mutbefore the variable name.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.Final Answer:
let ref = &mut num; -> Option BQuick Check:
Mutable reference syntax = &mut [OK]
- Using & instead of &mut for mutable references
- Placing mut after & incorrectly
- Using * instead of & for references
fn main() {
let x = 10;
let y = &x;
println!("{}", y);
}Solution
Step 1: Understand the reference
Variabley = &xyis a reference tox, so it points to the value 10.Step 2: Printing a reference with
Rust automatically dereferencesprintln!("{}", y)ywhen printing, so it prints the value 10, not the address or &10.Final Answer:
10 -> Option AQuick Check:
Printing reference prints value [OK]
- Expecting &10 to print literally
- Thinking it prints memory address
- Assuming compilation error due to reference
fn main() {
let mut num = 5;
let r = #
*r = 10;
println!("{}", num);
}Solution
Step 1: Check reference mutability
Variableris an immutable reference tonumbecause it is declared as&num, not&mut num.Step 2: Understand assignment through reference
You cannot assign a new value through an immutable reference. The line*r = 10;causes a compilation error.Final Answer:
Cannot assign to *r because r is an immutable reference -> Option AQuick Check:
Immutable reference cannot be used to modify value [OK]
- Forgetting to use &mut for mutable references
- Thinking mut on variable alone allows mutation through immutable ref
- Ignoring compiler error messages
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?
}Solution
Step 1: Understand function parameter type
The functionadd_valueexpects a mutable reference&mut Vec<i32>.Step 2: Check how to pass mutable reference
To pass a mutable reference, the variable must be mutable and passed as&mut vec. Passing&vecis immutable reference, and passingvecmoves ownership.Final Answer:
add_value(&mut vec); -> Option DQuick Check:
Mutable reference call uses &mut [OK]
- Passing immutable reference when mutable is needed
- Passing ownership instead of reference
- Incorrect syntax like mut &var
Ready to prove it?
Pass the test and this pattern moves unknown
