Lifetimes: How Long Things Live
Imagine you borrow a library book to read. As long as youβre reading it, the book has to still exist β you canβt read a book thatβs already been thrown away! Rust cares about this too. It uses something called lifetimes. β³
A lifetime is just Rustβs way of keeping track of how long something stays around.
Borrowing without taking
Remember borrowing? When you use a & in Rust, youβre borrowing a peek at
something instead of owning it. Thatβs super handy β but Rust has to be careful.
& symbol) is a way to borrow a look at
something without owning it β like peeking at a friend's book instead of keeping it.
A little label called βa
Sometimes Rust wants extra help knowing how long a borrowed thing lives. We give it
a tiny label that looks like 'a (say it βtick-aβ). Itβs just a nickname for a
lifetime, kind of like the <T> placeholder from generics.
Hereβs a function that takes two borrowed words and returns the longer one. The 'a
labels tell Rust, βall of these live for the same amount of time.β
fn longest<'a>(first: &'a str, second: &'a str) -> &'a str {
if first.len() > second.len() {
first
} else {
second
}
}
You donβt need to memorize this yet! The important idea is that 'a is just a promise
that the borrowed word we hand back will still exist when we use it. β
'a. It only asks for help in tricky spots. So don't worry β
you've got this! π¦
Quick quiz
What is a lifetime in Rust for?
That's it! A lifetime makes sure a borrowed reference never points at something that's already gone. β³
'a label is just a nickname for "how long." You've finished World 10 β you can now
write super flexible code! π