⏳
World 10 Β· Super Flexible Code

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.

The Big Idea A lifetime helps Rust make sure that a borrowed thing never points at something that is already gone. No reading a book that's been returned!

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.

Think of it like this… A borrowed book must still be on the shelf while you're reading it. If someone takes it away mid-sentence, you're stuck! Rust refuses to let that happen to your code. πŸ“š
New word A reference (the & 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. βœ…

Ferris says: Most of the time Rust figures out lifetimes all by itself, and you never have to write 'a. It only asks for help in tricky spots. So don't worry β€” you've got this! πŸ¦€
Watch out! Never hand back a borrowed peek at something that's about to disappear. That's like promising a friend a book you already returned to the library. Rust will gently stop you before it breaks!

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. ⏳

You learned… A lifetime is how Rust makes sure a borrowed thing stays alive while you're using it β€” like a library book that must still exist while you read it. The little 'a label is just a nickname for "how long." You've finished World 10 β€” you can now write super flexible code! πŸŽ‰