Borrowing
Borrowing lets you use a value without taking ownership. Shared borrows (&T) can be many. A mutable borrow (&mut T) must be the only borrow.
Detailed Explanation
A borrow is a reference with a lifetime the compiler tracks. &session is a shared borrow: you may read, you may not write, and many &session can exist at once. &mut session is a mutable borrow: you may write, and nothing else may borrow session at the same time. That rule — alias XOR mutability — is what makes data races a compile error and what stops a Vec from reallocating while you hold a pointer into it.
The borrow ends when last use of the reference ends (NLL, non-lexical lifetimes), not necessarily at the closing brace. After the last use of r, you can borrow session again. If the compiler still says you are borrowing, something is holding the reference: a struct field, an iterator, a closure that captured it.
Functions encode borrows in the signature. fn peek(s: &str) borrows. fn push(s: &mut String) borrows mutably. The caller does not lose the value. The callee must not store the reference past the call unless the lifetime says it may (fn longest<'a>(a: &'a str, b: &'a str) -> &'a str).
Borrowing is not a runtime lock. There is no counter on a String (unless you use RefCell). The checker is static. RefCell and Mutex move the same rule to runtime when the static checker cannot see the order.
When you borrow: default. When you take ownership: the function must keep the value or destroy it. When you clone: both sides need an owned value at the same time and a borrow cannot work.
Code Examples
fn greet(name: &str) {
println!("hello {name}");
}
fn append_bang(name: &mut String) {
name.push('!');
}
fn main() {
let mut name = String::from("ada");
greet(&name);
append_bang(&mut name);
println!("{name}"); // prints: ada!
}Common Gotchas
You cannot mutably borrow while a shared borrow is live
The error names both borrows. Shorten the shared borrow or copy the data you need.
A method taking `&mut self` borrows the whole value
You cannot pass `self.field` into `self.method(...)` if the method needs `&mut self`. Reorder, or pass the field after the call.
Borrows are not `Rc`
When the function returns, the borrow is over. To keep the value, take ownership or clone.
Iterators borrow the collection
`for x in &v { v.push(...) }` does not compile. Collect the items you need, or iterate indices carefully.