Sub topic 7
Borrowing with Shared References
This chapter assumes you know the ownership rules and move semantics from the earlier chapters. You should also be comfortable with String, Vec, and &str, and with running programs using cargo run. Here you learn how to let a function read a value without taking ownership of it.
The problem: moves are too expensive for reading
When you pass a String to a function by value, ownership moves into the function. The caller loses the value. If the function only wants to read it, the caller would have to get the value back through the return value:
fn length_owned(s: String) -> (String, usize) {
let n = s.len();
(s, n)
}
fn main() {
let s = String::from("hello");
let (s, n) = length_owned(s);
println!("{s} has {n} bytes");
}This works, but it is clumsy. Every read-only helper would need to hand the value back. Borrowing solves this.
Creating a shared reference
A shared reference has the type &T and is created with the & operator. It points at a value that someone else owns. Creating one is called borrowing.
fn length(s: &str) -> usize {
s.len()
}
fn main() {
let s = String::from("hello");
let n = length(&s);
println!("{s} has {n} bytes");
}Here &s lends s to length for the duration of the call. Afterwards s is still valid in main, and it is still the owner.
A reference has these properties:
- It is a pointer to the borrowed value. It does not own the value.
- It is not dropped as a value. When the reference goes out of scope, the value it pointed to stays alive, because the owner still holds it.
- It is read-only. Through a
&Tyou can read the value, but you cannot modify it. - The compiler guarantees it never points at freed memory. Later chapters cover how that guarantee works.
Many readers at once
You can create any number of shared references to the same value at the same time. This is safe because nobody can change the value while they exist. All of them only read.
fn main() {
let v = vec![1, 2, 3];
let a = &v;
let b = &v;
println!("{} {}", a.len(), b.len());
println!("{}", a == b);
println!("{}", v.len());
}The owner v can also be read while the borrows are alive. Reading through the owner is just another shared access.
A shared reference is itself Copy. Copying a &T copies only the pointer, not the data behind it:
fn main() {
let s = String::from("hi");
let r = &s;
let r2 = r;
println!("{r} {r2}");
}Both r and r2 remain usable. This differs from String, where let r2 = r; would move. Because &T is Copy, you never need to clone a reference to hand it to several functions.
Using references without special syntax
You rarely write * to follow a reference when reading. Rust applies automatic dereferencing in two places:
- Method calls:
s.len()works whethersis aString, a&String, or a&&String. - Formatting macros such as
println!, which print the value behind the reference.
You need an explicit * when you want the value itself, for example when comparing a number to a reference:
fn main() {
let n = 10;
let r = &n;
println!("{}", *r + 1);
println!("{}", *r == 10);
}Writing r == 10 would fail to compile, because &i32 and i32 are different types. Write *r == 10.
Choosing parameter types: `&String` or `&str`
A function that reads text should usually accept &str, not &String. Rust converts &String to &str automatically at the call site. This is called deref coercion. A &str parameter then accepts owned strings, slices, and string literals.
fn shout(s: &str) -> String {
s.to_uppercase()
}
fn main() {
let owned = String::from("hi");
println!("{}", shout(&owned));
println!("{}", shout("literal"));
}The same reasoning applies to &[T] instead of &Vec<T>.
| Parameter type | Caller keeps the value? | Can modify? | Accepts string literals? |
|---|---|---|---|
| `String` | No, it is moved | Yes | No |
| `&String` | Yes | No | No |
| `&str` | Yes | No | Yes |
What shared references cannot do
A shared reference cannot change the value it points to. This is the most common error when you first start borrowing:
fn add_suffix(s: &String) {
// s.push_str(", world");
// error[E0596]: cannot borrow `*s` as mutable, as it is behind a `&` reference
println!("{s}");
}
fn main() {
let s = String::from("hello");
add_suffix(&s);
}Uncommenting the push_str line makes the program fail to compile. The compiler's message also suggests changing the parameter to &mut String. That is the correct fix when mutation is intended, and the next chapter covers it.
Two other errors appear often:
- Returning a reference to a local variable. The local is dropped at the end of the function, so the reference would dangle. Rust rejects this, and a later chapter covers it.
- Using a value after moving it, when you meant to borrow. For example,
length_owned(s)followed byprintln!("{s}")givesE0382: borrow of moved value. Change the call to pass&sand the parameter to&str.
How long a borrow lasts
A borrow lasts from where the reference is created until its last use, not until the end of its scope. This rule is part of what the compiler calls non-lexical lifetimes. It matters when the owner is later mutated, as in the following program.
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 in the first println!, before push needs mutable access. If you moved the print of first after push, the compiler would reject the program. The borrowing rules chapter explains why.
Summary of the working model
&xborrowsxwithout taking ownership.- Any number of
&Treferences can exist at once, because all of them only read. - A
&TisCopy, and dropping it does not free the value. - You cannot modify a value through
&T. - Prefer
&strand&[T]in parameters for flexibility.
Exercise
The function below fails to compile with "borrow of moved value: name". Change only the function signature and the call so that name stays usable, and explain why that works.
fn greet(name: String) -> usize {
println!("Hello, {name}");
name.len()
}
fn main() {
let name = String::from("Ferris");
let n = greet(name);
println!("{name} {n}");
}
Show answer
Change the signature to fn greet(name: &str) -> usize and the call to greet(&name). The original passes name by value, so ownership moves into greet and main can no longer use it. With &name, the function receives a shared reference, which borrows the value instead of taking it. main stays the owner, and the later println!("{name} {n}") compiles. The &String argument is converted to &str by deref coercion.
Exercise
Will this program compile? If not, name the error and the fix. fn main() { let s = String::from("abc"); let r = &s; r.push('d'); println!("{r}"); }
Show answer
It does not compile. r is a shared reference, so push is rejected with E0596, "cannot borrow *r as mutable, as it is behind a & reference". To fix it, declare let mut s, create the reference with &mut s (so r has type &mut String), and the push is then allowed.