References and Borrowing
Borrowing instead of moving
Instead of moving a value, you can borrow it with a reference (&). The borrower can read (or modify with &mut) but does not own the value.
fn len(s: &String) -> usize {
s.len()
}
let s = String::from("hello");
println!("length: {}", len(&s)); // s is still valid
println!("{}", s); // OKIn C#: Passing by reference is like ref or passing a reference type (you pass the object reference). In Rust, &T is an explicit immutable borrow; the owner keeps ownership.
Immutable reference &T
- Multiple
&Tto the same value are allowed at the same time. - No one can modify the value while borrowed immutably.
let s = String::from("hello");
let r1 = &s;
let r2 = &s;
println!("{} {}", r1, r2);Mutable reference &mut T
- Only one
&mut Tat a time (exclusive borrow). - No immutable references can coexist with a
&mut T.
let mut s = String::from("hello");
let r = &mut s;
r.push_str(" world");
println!("{}", r);In C#: Similar to ref for mutation; Rust enforces exclusivity at compile time.
Shared XOR mutable (the borrow rule, visualized)
At any moment a value may have either any number of shared (&T) borrows or
exactly one mutable (&mut T) borrow — never both at the same time:
any number of readers OR exactly one writer
┌──────┐ ┌──────┐ ┌──────┐ ┌──────────┐
│ &T │ │ &T │ │ &T │ │ &mut T │
└──┬───┘ └──┬───┘ └──┬───┘ └────┬─────┘
└────────┼────────┘ │
▼ ▼
the value (read-only) the value (read + write)This "shared XOR mutable" rule is what lets the compiler rule out data races and iterator invalidation before the program runs.
In C#: nothing stops two pieces of code from holding and mutating the same object at
once (you reach for lock to stay safe). Rust encodes the rule in the type system, so the
conflict is a compile error instead of a runtime bug.
No null
Rust has no null for references. Use Option<&T> if you need “maybe a reference.”
In C#: References can be null; in Rust, use Option instead.
Key takeaway
Use &T to borrow immutably and &mut T to borrow mutably. Rules: many &T or one &mut T, and references must not outlive the owner.