Dangling references
The book deal has one more clause: while the book is in someone's hands, the owner may not throw it away. Otherwise the reader is left empty-handed in the middle of a chapter.
A reference to a value that has already been destroyed is called a dangling reference. In C and C++ such code builds, and reading through a dangling reference is undefined behavior: the program may print garbage, crash, or seem to work for a while. In Rust a dangling reference does not get past the compiler.
While the book is lent
Remember the drop function: it takes a value and destroys it. Let's try to destroy a string that a reference is still looking at:
fn main() {
let s = String::from("Dune");
let r = &s;
drop(s); // ✗
println!("{r}");
}error[E0505]: cannot move out of `s` because it is borrowedLet's go through it line by line:
sowns the stringDune.let r = &s;borrows the string for reading.drop(s)wants to move the string into the function and destroy it.- But
ris still needed: the next line prints it. Ifdropwent through,rwould point to a destroyed string.
The compiler answers that s cannot be moved while it is borrowed. The fix is to move drop(s) below the println!. Then the borrow of r ends at the print, before the string is destroyed.
A reference does not extend a life
A reference does not hold on to a value. When the owner goes away, the value is destroyed along with it, however many references to it there are. So the borrow checker watches the other direction: every borrow must end before the owner destroys the value.
Here the book analogy falls short. In real life the owner can throw the book away, and the reader finds out only when reaching for it. In Rust the compiler will not build such a program, and the check costs nothing while the program runs.
Interviewers like to ask this: "What is a dangling reference, and how does Rust protect against it?" The answer:
- a dangling reference points to a value that has already been destroyed;
- in C and C++ such code builds, and reading through it is undefined behavior;
- in Rust the borrow checker does not let a value go away before a reference to it;
- the whole check happens at build time, so a running program never has dangling references.
Common mistake
A function creates a string and tries to return a reference to it:
fn make() -> &String { // ✗
let s = String::from("Dune");
&s
}
fn main() {
let r = make();
println!("{r}");
}error[E0106]: missing lifetime specifierThe words missing lifetime specifier mean that the compiler does not know which value the returned reference is borrowed from and how long it will live. The string s belongs to the function make and is destroyed at its }. The reference &s would outlive its string and become dangling.
The compiler stops already at the signature, before the function body. The result type &String promises to return a borrowed value, but make has no parameters, so there is nothing to borrow it from. That is what the first help: hint under the error says. The last hint suggests what you almost always need: return the String itself.
fn make() -> String {
let s = String::from("Dune");
s
}
fn main() {
let t = make();
println!("{t}"); // Dune
}Now the function hands over the string itself rather than a reference, and ownership passes to t. String::from works the same way: it creates a string and gives it to you. Nothing is copied: only the card with the key to the unit moves.
Key points
- A dangling reference points to a destroyed value; in Rust such code does not compile.
- While a value is borrowed, it cannot be moved or destroyed:
drop(s)with a live reference gives E0505. - A reference does not extend a value's life: the borrow must end before the owner does.
- You cannot return a reference to a local variable (E0106 at the signature); the function returns the
Stringitself.