Borrowing
Moving a value every time you want to use it is a pain. Borrowing lets code use a value without taking ownership.
Shared references
&x makes a shared reference to x. The reference can read the value, but the owner keeps it. You can have as many shared references as you like.
fn len(s: &String) -> usize { s.len()}let word = String::from("hi");let n = len(&word); // word is borrowedprintln!("{word} {n}"); // still usableMutable references
&mut x makes a mutable reference, which can change the value. The variable itself must be declared with mut, or you get error E0596.
let mut n = 1;let r = &mut n;*r += 1; // n is now 2One &mut at a time
Only one mutable reference to a value can be live at once. Two at the same time is error E0499. This stops two parts of the code from changing the same thing at once.
No & with &mut
You can't hold a shared reference while a mutable one is live, or the other way round. That is error E0502. Changing a value while it is borrowed is also not allowed (E0506).
let mut v = vec![1];let first = &v[0];v.push(2); // E0502: v is borrowedprintln!("{first}");Borrows end at last use
A borrow ends after its last use, not at the end of the block. So this is fine:
let mut s = String::from("hi");let r = &s;println!("{r}"); // last use of rs.push('!'); // ok nowRemember
- Many
&or one&mut, never both at once. &mutneeds amutvariable (E0596).- E0499: two
&mut. E0502:&and&mutmixed. - A borrow ends at its last use.