Advanced 18 min readModule: Module 4: Borrowing & References (&T and &mut T)
References, Borrowing & The Borrow Checker
Pass data without transferring ownership using references (&), and learn the golden rule of the borrow checker.
What You Will Learn in This Lesson
- Borrowing data with immutable references (&String)
- Exclusive mutable borrowing (&mut String)
- The Golden Borrow Rule: Either 1 mutable reference OR any number of immutable references
Introduction & Core Concept
Instead of transferring ownership, Rust allows functions to 'borrow' access to data via references without taking ownership.
WHY DOES THIS MATTER IN THE REAL WORLD?
The borrow checker rules mathematically prevent data races: two threads cannot mutate the same memory location simultaneously.
Immutable & Mutable Borrowing
rustrust
1234567891011121314fn calculate_length(s: &String) -> usize {s.len() // Borrowed reference}fn append_badge(s: &mut String) {s.push_str(" [PRO]");}fn main() {let mut name = String::from("Alex Developer");println!("Length: {}", calculate_length(&name));append_badge(&mut name);println!("Updated: {}", name);}
Line-by-Line Technical Breakdown
1You cannot have a mutable reference while immutable references are still in active use.
Try It Yourself (Interactive Editor)
Modify the code in real-time and click Run to test live browser output and console logs.
Intelligent Code Runner & Live Sandbox[RUST]
RUST SOURCE EDITOR
Interactive Live CodeIndustry Best Practices & Professional Standards
- Keep mutable borrow scopes as narrow as possible.
Lesson Summary & Core Takeaways
- Borrowing enables high-performance zero-copy memory access with compile-time safety.