Sub topic 2
Borrowing with Shared References
This chapter assumes you know basic Rust syntax, how String and &str differ, and how moves work: assigning or passing a String transfers ownership and invalidates the old variable.
The problem borrowing solves
Passing a String to a function by value moves it. The caller can no longer use it. Often a function only needs to read the data. A shared reference, written &T, lets the function look at a value without owning it. Creating a reference is called borrowing.
Borrowing with `&`
fn length(s: &String) -> usize {
s.len()
}
fn main() {
let s = String::from("hello");
let n = length(&s);
println!("{s} has length {n}");
}Two places change compared with a move:
- The parameter type is
&String, which means "a reference to aString". - The caller writes
&sto create the reference.
When length returns, the reference goes out of scope. The function never owned the String, so it does not free it. main still owns s and can print it.
What a shared reference lets you do
A &T gives read-only access. It is also Copy, so you can hand out as many as you like. All of them can exist at the same time, and all of them can read.
fn main() {
let s = String::from("hello");
let a = &s;
let b = &s;
println!("{a} {b} {s}");
}Even the owner s can still be read while a and b exist. The next chapters cover what happens when someone wants to write.
Auto-dereferencing
Calling s.len() on a &String works without any special syntax. Method calls and field access automatically dereference. You only write *r when you need the value itself, for example in *r == 5 where r is &i32.
Common errors
| What you wrote | What the compiler says | Fix |
|---|---|---|
| `length(s)` where the parameter is `&String` | E0308, mismatched types: expected `&String`, found `String` | Pass `&s` |
| `s.push_str("x")` inside a function that took `s: &String` | E0596, cannot borrow `*s` as mutable, as it is behind a `&` reference | Change the parameter to `&mut String` (next chapter) |
| `let owned: String = *s;` where `s` is `&String` | E0507, cannot move out of `*s` which is behind a shared reference | Use `s.clone()`, or keep working with the reference |
The third error is the one that surprises people most. A reference does not own the value. If you could move the String out of it, the real owner would be left pointing at data that is gone.
Reading a borrowing signature
Reading the type tells you what a function may do to your data:
fn f(s: String)takes ownership. You losesunless you clone it first.fn f(s: &String)borrowssread-only. You keeps.
If a function only inspects its input, choose the shared reference. The caller keeps the value and nothing is copied.
Exercise
In the code below, why does the compiler reject the last line? Which one-character change to the call fixes it, and what happens to name afterwards?
fn shout(s: &String) -> String {
s.to_uppercase()
}
fn main() {
let name = String::from("ada");
let loud = shout(name);
println!("{name} {loud}");
}
Show answer
shout expects a &String, but name is a String, so the call fails with E0308 (mismatched types). Writing shout(&name) borrows name instead of moving it. name stays valid, so the println! prints ada ADA.