Borrowing & References
Lend a value without giving it away, and let the compiler referee.
builds on
Instead of moving a value, you can borrow a reference to it with &. The function reads the data without taking ownership, so the caller keeps using it afterward.
One mutable borrow XOR many shared borrows. That single rule is what makes data races a compile error instead of a 3am incident.
main.rs
Here is the rule being enforced. Two mutable borrows of the same value, alive at the same time, and the compiler names the exact conflict. This error text is captured from real rustc and re-verified against every new stable release.
what the compiler says
fn main() {
let mut s = String::from("borrow");
let a = &mut s;
let b = &mut s; // a second mutable borrow while `a` is still live
println!("{a} {b}");
}
error[E0499]: cannot borrow `s` as mutable more than once at a time
--> main.rs:5:13
|
4 | let a = &mut s;
| ------ first mutable borrow occurs here
5 | let b = &mut s; // a second mutable borrow while `a` is still live
| ^^^^^^ second mutable borrow occurs here
6 | println!("{a} {b}");
| - first borrow later used here
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0499`.
Why might a function take `bars: &[f64]` instead of `bars: Vec<f64>`?
Which combination of borrows does the compiler allow to exist at the same time?