Why Lifetimes
Preventing dangling references.
Why Lifetimes is a free Learn Rust Coding lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
References Must Stay Valid
A reference borrows data it does not own. Rust must guarantee the data lives at least as long as the reference. Lifetimes are how the compiler tracks this.
Their job: prevent dangling references.
What Is a Dangling Reference?
A dangling reference points to memory that has been freed. In languages without checks, using one causes crashes or security bugs. Rust refuses to compile such code.
The Borrow Checker in Action
This code would create a reference to a value that goes out of scope. Rust rejects it at compile time. Lifetimes are the rule it uses to decide.
fn main() {
let r;
{
let x = 5;
r = &x;
println!("inside: {}", r);
}
// using r here would be a dangling reference
println!("done");
}Scopes Define Lifetimes
A value's lifetime is the span where it is valid, usually its scope. A reference must not outlive the value it points to.
Here both x and the reference live in the same scope, so it is fine.
fn main() {
let x = 5;
let r = &x;
println!("x is {}, r is {}", x, r);
}Returning References
A function returning a reference must return one that stays valid for the caller. You cannot return a reference to a local variable, because it dies when the function ends.
Returning a Borrow of an Input
What you can do is return a reference that borrows from an input. The result is valid as long as that input is. This is exactly what lifetime annotations describe.
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &b) in bytes.iter().enumerate() {
if b == b' ' {
return &s[..i];
}
}
s
}
fn main() {
let sentence = String::from("hello world");
println!("{}", first_word(&sentence));
}Lifetimes Are Compile-Time Only
Lifetimes are purely a compile-time concept. They add no runtime cost and exist only to let the borrow checker verify memory safety.
Ownership and Lifetimes Together
Ownership decides who frees a value; lifetimes decide how long borrows of it may live. Together they let Rust guarantee safety without a garbage collector.
fn main() {
let data = vec![1, 2, 3];
let view = &data[0..2];
println!("{:?}", view);
// data still owns the vector; view just borrows part of it
println!("{:?}", data);
}Why Names Appear in Signatures
When a function takes multiple references, the compiler sometimes cannot tell how their lifetimes relate. You then add lifetime annotations to clarify the relationships.
The next lesson covers that syntax.
The Payoff
Because of lifetimes, an entire category of bugs — use-after-free, dangling pointers, iterator invalidation — simply cannot compile. You get C-like speed with memory safety.
Mental Model
Think of a lifetime as a label on the duration data is alive. A reference carries the constraint: I am valid only while my source is alive. The borrow checker enforces it.
Quick Check
Test your understanding of why lifetimes exist.
Recap
You learned why lifetimes exist:
- References must not outlive the data they borrow
- Lifetimes prevent dangling references at compile time
- They are compile-time only, with no runtime cost
- They work alongside ownership for memory safety without a GC
Frequently asked questions
Is the “Why Lifetimes” lesson free?
Yes — the full text of “Why Lifetimes” is free to read here on the web, and the Learn Rust Coding course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.
What will I learn in “Why Lifetimes”?
Preventing dangling references. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Learn Rust Coding?
No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Why Lifetimes” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Learn Rust Coding lesson?
Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.