ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)
Set your Publisher ID in src/config/ads.ts to display live ads.
Rust Tutorial• 7 min read
References & Borrowing: The Borrow Checker
Immutable borrows (&T), mutable borrows (&mut T), and data race prevention
Instead of taking full ownership, functions can "borrow" access to values using References (&). The Borrow Checker enforces data race prevention at compile-time.
The Two Rules of Borrowing
At any given time, you can have EITHER:
1Any number of immutable references (
&T) to a resource, OR...2Exactly ONE mutable reference (
&mut T) to a resource.You can NEVER have a mutable reference simultaneously with an immutable reference. This rule prevents Data Races at compile-time!
Borrowing with References in Rust
fn calculate_length(s: &String) -> usize {
s.len() // Borrowed reference; does NOT take ownership!
}
fn append_suffix(s: &mut String) {
s.push_str(" Academy"); // Mutating through mutable reference
}
fn main() {
let mut title = String::from("Codexia");
let len = calculate_length(&title); // Immutable borrow
println!("Length: {}", len);
append_suffix(&mut title); // Mutable borrow
println!("Updated: {}", title);
}ADVERTISEMENT
Google AdSense Slot (inContentBanner)
Set your Publisher ID in src/config/ads.ts to display live ads.
Test Yourself With Exercise
Under Rust borrowing rules, can you have an active mutable reference (`&mut T`) while one or more immutable references (`&T`) exist for the same value?