In this lesson, you will learn how to architecture your code to safely update shared state without breaking Rust’s strict rules against multiple mutable references.
The Problem: Concurrent Conflict
As you’ve learned, Rust strictly forbids having two mutable references to the same data at the same time. This is a safety feature: if one part of your program is changing a value while another part is reading it, you risk "data races" (crashes or unpredictable behavior).
When you need to update data from multiple "places" (like different functions or logic paths), you cannot simply pass around multiple &mut references. If you try to hold two mutable references simultaneously, the compiler will stop you.
The Solution: Architecture via Ownership
Instead of fighting the borrow checker to share a mutable reference, you can change your architecture. The safest way to handle concurrent-like updates is to centralize the mutation.
Think of your data as a resource that lives in one place. Instead of passing &mut references everywhere, you create a "controller" function or a specific scope that takes ownership of the data, performs the necessary changes, and returns the result.
Consider this pattern:
fn update_score(mut score: i32) -> i32 {
score += 10;
score
}
fn main() {
let mut my_score = 100;
// Instead of trying to mutate my_score from two places,
// we pass ownership to the controller.
my_score = update_score(my_score);
my_score = update_score(my_score);
println!("Final score: {}", my_score);
}
Why this is safer
By moving the value into a function, you ensure that only one part of your program has the right to modify the data at any given moment. Once the function is finished, it hands ownership back to you.
This approach avoids "aliasing"—the act of having two pathways to the same memory—entirely. By forcing the data to "flow" through specific functions rather than being held open by multiple mutable references, you keep your memory layout clean, predictable, and free from concurrent conflicts.
Key Takeaway: Avoid concurrent mutation by centralizing updates through ownership transfer rather than sharing mutable references.