Dangling reference
- Rust course
- Beginner
- Lesson 51/115
- 4 min
See how Rust prevents dangling references.
Dangling references
A dangling reference is a reference pointing at a value that no longer exists. This bug, common in C and C++, is prevented at compile time in Rust:
fn sarkan() -> &String { // error: missing lifetime
let s = String::from("geçici");
&s // s is dropped here!
}The fix is to return the value itself instead of a reference: fn yeni() -> String { String::from("geçici") }. Ownership then passes to the caller.
References across scopes
The same bug is caught in inner blocks too:
let r;
{
let x = 5;
r = &x; // error E0597: x doesn't live long enough
}
// println!("{r}");The error message says "borrowed value does not live long enough" and shows where x is dropped. Moving the value to the outer scope fixes it.
Practice Safe return
Write fn mesaj_uret(ad: &str) -> String; it returns format!("Hoş geldin, {ad}") (not a reference). Print the result of mesaj_uret("Ece").
Starter code
fn main() {
// buraya yaz
}Sample solution
fn mesaj_uret(ad: &str) -> String {
format!("Hoş geldin, {ad}")
}
fn main() {
println!("{}", mesaj_uret("Ece"));
}Expected output
Hoş geldin, Ece
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the borrow checker guarantee?
- That the program runs fast
- That there are never memory leaks in any case
- That the code compiles
- No reference outlives the value it points to Correct answer
Explanation: The compiler compares every reference's lifetime with the value's lifetime; a reference that outlives it is a compile error.
2 Return the value
fn yeni_mesaj() -> ____ {
String::from("merhaba")
}
fn yeni_mesaj() -> String {
String::from("merhaba")
}
Explanation: Returning the value itself transfers ownership; no dangling reference is created.
3 Error code and meaning
| Term | Meaning |
|---|---|
E0382 |
Use of a moved value |
E0499 |
Two &mut |
E0502 |
Writing while reading |
E0597 |
Value doesn't live long enough |