Sub topic 7
Borrowing with shared references
This chapter assumes you know basic Rust syntax, can run programs with cargo, and have read the earlier chapters on the ownership rules, moves, and passing ownership to functions.
The problem borrowing solves
Passing a String to a function moves it. The caller loses the value unless the function returns it. That is awkward when a function only needs to read the data.
A shared reference, written &T, lets code look at a value without owning it. Creating a reference is called borrowing. The owner keeps ownership, and the value is not dropped when the reference goes away.
Borrowing in a function call
fn length(s: &str) -> usize {
s.len()
}
fn main() {
let s = String::from("hello");
let n = length(&s);
println!("{s} has {n} bytes");
}&s creates a reference to s. The function takes &str, and Rust converts &String to &str automatically. After the call, s is still valid, so main can print it.
What a shared reference allows
- You can read through it, call
&selfmethods, and copy outCopyvalues. - You cannot change the value through it.
- You can create as many shared references to one value as you like, at the same time.
- Every
&Tis itselfCopy, so passing one around never moves anything.
fn main() {
let s = String::from("hi");
let r1 = &s;
let r2 = &s;
println!("{r1} {r2} {s}");
}Many readers at once are safe because nobody can change the data underneath them.
Borrows end at their last use
A borrow lasts from where it is created to where it is last used, not to the end of the block. The compiler tracks this precisely.
fn main() {
let mut v = vec![1, 2, 3];
let first = &v[0];
println!("{first}");
v.push(4);
println!("{:?}", v);
}This compiles because first is last used before push runs. If you moved the println!("{first}") line after v.push(4), it would fail. push may reallocate the vector, which would leave first pointing at freed memory.
Common errors
The most frequent mistake is trying to modify data through a shared reference:
fn add_suffix(s: &String) {
s.push_str(", world");
}The compiler reports error E0596: cannot borrow *s as mutable, as it is behind a & reference. The fix is to take &mut String, which the next chapter covers.
The other common mistake is changing the owner while a reference is still in use. The error is E0502: cannot borrow v as mutable because it is also borrowed as immutable. To fix it, finish using the reference first, or restructure the code so the borrow ends earlier.
Exercise
Exercise
Why does this code fail to compile, and how would you fix it? let mut s = String::from("a"); let r = &s; s.push('b'); println!("{r}");
Show answer
The shared reference r is still used by println! after s.push('b') needs mutable access to s. A shared borrow and a mutation cannot overlap. Fix it by printing r before the push, or by removing r and printing s after the push.