Borrowing
| Shared & borrows | |
| One &mut | |
| The two rules | |
| No dangling (compiler stops you) |
Shared & borrows
A shared borrow reads data without taking ownership. Many shared borrows may exist at once because none can change the value:
let s = String::from("hi");
let r = &s;
println!("{} {}", s, r);
One &mut
A mutable borrow allows change but only one may exist at a time. It must not overlap with any shared borrow:
let mut s = String::from("hi");
let r = &mut s;
r.push_str("!");
The two rules
Rule one is many shared borrows or exactly one mutable borrow, never both together. Rule two is that every borrow must stay valid while in use:
let mut s = String::from("hi");
let a = &s;
println!("{}", a);
let b = &mut s;
b.push_str("!");
No dangling (compiler stops you)
A borrow can never outlive its owner. Return owned data from a function instead of a reference to a local value:
fn make() -> String {
String::from("hi")
}
Next: Lifetimes
Article author: Arthur Isaev