In this lesson, you will learn how to modify the original value of a variable by using a mutable reference.
The Power of the Pointer
So far, you have learned that a reference allows you to "borrow" a value without taking ownership of it. However, if you have a mutable reference, you gain the ability to reach through that reference and change the underlying data directly.
In Rust, this is done using the dereference operator *. When you place an asterisk before a mutable reference, you are telling the compiler: "I don't want to talk about the reference anymore; I want to talk about the actual value it points to."
Putting it into Practice
Imagine you have a variable representing a player's score. You want a function to update that score without having to return a new value. You can pass a mutable reference to that score and update it in place.
fn main() {
let mut score = 10;
// Create a mutable reference to score
let score_ref = &mut score;
// Use the dereference operator to update the value
*score_ref = 20;
println!("The new score is: {}", score); // Prints: 20
}
In the example above, score_ref is a reference. If we simply wrote score_ref = 20, Rust would throw an error because you are trying to overwrite the address held by the reference rather than the data at that address. By using *score_ref, you gain the power to modify the memory location where score lives.
Why this matters
This pattern is essential for efficiency. Instead of cloning large pieces of data or constantly moving values in and out of functions, you can grant temporary "permission" to a function to modify a value. Because the reference is mutable, the compiler ensures that no one else can read or write to that data while you are updating it, keeping your program memory-safe.
Key Takeaway: Use the dereference operator * on a mutable reference to modify the original value it points to, allowing you to update data without changing ownership.