Sub topic 2
Borrowing with shared references
This chapter assumes you know basic Rust syntax, the types String, Vec, and &str, the difference between stack and heap, and how to run a program with cargo. It also assumes you have seen that assigning or passing a String by value moves ownership. This chapter covers shared references. Mutable references come in the next chapter.
The problem a shared reference solves
Passing a String to a function by value moves it. The caller can no longer use it. If a function only needs to read the data, taking ownership forces the caller to give the value up and get it back, or to clone it.
A shared reference lets a function look at a value without owning it. Its type is &T, and you create one with the & operator. Creating a reference is called borrowing. The owner keeps ownership, and the borrower can read through the reference.
fn length(s: &String) -> usize {
s.len()
}
fn main() {
let s = String::from("hello");
let n = length(&s);
println!("{s} has length {n}");
}length receives &String, so main still owns s after the call. The function cannot drop the string, because it does not own it.
What a reference is
A &T is a pointer to a T that the compiler tracks. It holds an address, and the compiler checks that the address stays valid for as long as the reference is used. The check happens at compile time and costs nothing at run time. A &String is one machine word wide. The String it points to is not copied.
The dotted arrow is the borrow. When length returns, its reference goes away. Nothing is freed, because the reference never owned anything.
Many shared references at once
You can create as many shared references to a value as you like, and they can all be alive at the same time. All of them are read-only, so none can change what another sees.
fn main() {
let s = String::from("hello");
let a = &s;
let b = &s;
println!("{a} {b} {s}");
}The owner s can also be read while the references exist. The owner may read the value, but it cannot move it or change it while a borrow is still in use. The rules for what the owner may do are covered in the borrowing-rules chapter.
References are `Copy`
The type &T implements Copy, so copying a reference does not move it. You can pass the same reference to several calls.
fn show(s: &String) {
println!("{s}");
}
fn main() {
let owned = String::from("reused");
let r = &owned;
show(r);
show(r);
show(r);
}This works because each call receives a copy of the pointer. The String itself is never duplicated. Note that &mut T is not Copy, which is part of why mutable references behave differently.
Reading through a reference: dereferencing
To get at the value behind a reference, you dereference it with *. Most of the time you do not need to write it. Method calls and field access dereference automatically, which is why s.len() worked on a &String above.
You need an explicit * when you want the value itself, for example to compare it with a plain value or to copy a small Copy value out.
fn main() {
let x = 5;
let r = &x;
assert_eq!(*r, 5);
let copy: i32 = *r;
println!("{copy} {}", r + 1);
}Arithmetic operators are implemented for &i32, so r + 1 works without *. Comparing r == 5 does not compile, because &i32 and i32 are different types. Write *r == 5 or r == &5.
Prefer `&str` over `&String` in parameters
The first example used &String to keep the idea simple. In real code, a function that only reads text should take &str.
fn word_count(s: &str) -> usize {
s.split_whitespace().count()
}
fn main() {
let owned = String::from("one two three");
println!("{}", word_count(&owned));
println!("{}", word_count("literal text"));
}&str accepts a borrowed String, a string literal, and a slice of either. The compiler converts &String to &str automatically. This conversion is called deref coercion. It works because String implements Deref<Target = str>. The same applies to &Vec<T>, which coerces to &[T]. Slices are covered in their own chapter.
| Parameter type | Accepts `&String` | Accepts `&str` literal | Recommended for read-only text |
|---|---|---|---|
| `&String` | Yes | No | No |
| `&str` | Yes, by coercion | Yes | Yes |
| `String` | No, takes ownership | No | Only if the function needs to own it |
What a shared reference cannot do
A &T grants read access only. Two mistakes come up often at this stage.
Modifying through `&`
fn shout(s: &String) {
s.push_str("!");
}
fn main() {
let s = String::from("hey");
shout(&s);
}This does not compile. The compiler reports E0596: it cannot borrow *s as mutable, because it is behind a & reference. The fix is to change the parameter to &mut String, which is the next chapter's topic.
Moving out of a reference
fn first(v: &Vec<String>) -> String {
v[0]
}
fn main() {
let names = vec![String::from("Ana"), String::from("Bo")];
println!("{}", first(&names));
}This does not compile either. The compiler reports E0507: it cannot move out of index of Vec<String>. Returning v[0] would move the String out of the vector, leaving the vector with a hole, and a borrower may not take ownership of what it only borrows. You have two fixes, depending on what the caller needs.
fn first_ref(v: &Vec<String>) -> &String {
&v[0]
}
fn first_owned(v: &Vec<String>) -> String {
v[0].clone()
}
fn main() {
let names = vec![String::from("Ana"), String::from("Bo")];
println!("{}", first_ref(&names));
println!("{}", first_owned(&names));
}first_ref returns another borrow, so there is no copy. first_owned pays for a clone and gives the caller an independent value. The lifetime of the returned reference is covered in the lifetime chapters.
A reference cannot outlive its owner
A reference is valid only while the value it points to is alive. The compiler enforces this, and the details are in the chapters on dangling references and lifetimes. For now, remember that a borrow ties its user to its owner. If the owner is dropped or moved, any reference still in use after that point is a compile error.
fn main() {
let s = String::from("moved soon");
let r = &s;
let t = s;
println!("{r} {t}");
}This does not compile. The compiler reports E0505: it cannot move out of s because it is borrowed, and r is used afterwards. If you remove r from the println!, the program compiles, because the borrow is no longer in use when the move happens. The exact point where a borrow ends is covered in the non-lexical lifetimes chapter.
Summary of the model
&Tborrows aTfor reading. The owner keeps ownership.- Any number of shared references can coexist, and they are all
Copy. - Method calls and field access dereference automatically. Use
*when you need the value itself. - Prefer
&strand&[T]for read-only parameters, because deref coercion lets callers pass more kinds of values. - Through
&Tyou cannot mutate the value or move it out. Fix these errors with&mut Torclone(), depending on intent.
Exercise
A function fn total_len(a: &String, b: &String) -> usize is called as total_len(&s, &s) where s is a String. Does this compile, and why? Then say what parameter type you would use instead of &String so that total_len("ab", "cde") also works.
Show answer
It compiles. Two shared references to the same value may be alive at once, because neither can change the data. Using &str for both parameters, fn total_len(a: &str, b: &str) -> usize, lets callers pass string literals as well as &String values, which deref coercion converts to &str.
Exercise
The function fn longest_name(v: &Vec<String>) -> String { v[0] } fails with error E0507. Give two different fixes and say when you would choose each.
Show answer
Change the return type to &String and return &v[0], which borrows without copying. Choose this when the caller only needs to read the name. Or keep the return type String and return v[0].clone(). Choose this when the caller needs an independent value that can outlive the vector.