Rust•Borrowing
Rust References and Borrowing (& and &mut)
Borrowing allows referencing data without taking ownership. The borrow checker prevents data races at compile time.
Syntax
fn calculate_len(s: &String) -> usize {}
fn append_data(s: &mut String) {}
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| &T | Immutable Reference | Zero-cost read-only borrow. |
| &mut T | Mutable Reference | Exclusive mutable borrow. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Rust locally:
// Borrowing immutably
fn calculate_length(s: &String) -> usize {
s.len()
}
// Borrowing mutably
fn append_status(s: &mut String) {
s.push_str(" [VERIFIED]");
}
fn main() {
let mut message = String::from("Payload 101");
// Multiple immutable borrows are allowed
let len1 = calculate_length(&message);
let len2 = calculate_length(&message);
println!("Calculated lengths: {} and {}", len1, len2);
// One exclusive mutable borrow
append_status(&mut message);
println!("Updated message: {}", message);
}Expected Output:
Calculated lengths: 11 and 11 Updated message: Payload 101 [VERIFIED]
How It Works: Step-by-Step
- Lines 2-4: calculate_length borrows s immutably without taking ownership.
- Lines 7-9: append_status borrows s mutably with &mut String.
- Line 20: Original message remains valid and modified in place.
Key Concepts
- Borrowing rule 1: You can have any number of immutable references (&T).
- Borrowing rule 2: You can have only ONE mutable reference (&mut T) at a time.
- References must always be valid (no dangling pointers).
Common Mistake: Having both an immutable reference and a mutable reference in the same scope
Rust forbids reading while another reference is mutating (prevents data races).
❌ Incorrect
let mut s = String::from("a"); let r1 = &s; let r2 = &mut s; println!("{}", r1); // Compile Error!✅ Correct
let mut s = String::from("a"); let r1 = &s; println!("{}", r1); let r2 = &mut s; // Non-overlappingRelated Rust Tutorials & Compiler
Rust Functions and Implicit Expression Block Return Optimization
Master Rust expression-oriented functions: implicit tail returns (omitting semicolon), explicit return keyword, and block optimization schemas.
Rust Structs and impl Blocks: Methods and Associated Functions
Define methods on structs with impl blocks and associated functions (constructors).
Rust Concurrency: Threads and Channels (std::sync::mpsc)
Fearless concurrency in Rust with thread::spawn and mpsc message-passing channels.
Rust Online Compiler
Open in Compilra IDE
Run and test Rust on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.