Sitemap
Rustaceans

Exploring Rust: Insights and Expertise from Rustaceans

Lifetimes

6 min readJul 19, 2025

--

Press enter or click to view image in full size
Image made by Excalidraw

Yesterday we looked at Slices and their nitty-gritties, I’d suggest you check it out below.

Rust’s ownership model is all about ensuring memory safety at compile time. Lifetimes are a key part of this, specifying how long references are valid. Think of them as the compiler’s way of tracking the “lifespan” of a borrowed value to prevent accessing data that’s gone out of scope.

Imagine you’re building a web server that processes user requests. You might have a function that takes a user’s input string and returns a response. If that function borrows the input string, the compiler needs to know how long that borrow is valid to avoid referencing freed memory. Lifetimes make this explicit.

Below is a simple example:

fn get_first_word(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}

The function above takes a string slice and returns the first word as another slice. The compiler needs to ensure the returned slice doesn’t outlive the input string. Rust’s lifetimes handle this implicitly here, but as we’ll see, explicit lifetime annotations are often…

--

--

Rustaceans
Rustaceans

Published in Rustaceans

Exploring Rust: Insights and Expertise from Rustaceans

John Philip
John Philip

Written by John Philip

Dev | Life Café | Twitter at @amjohnphilip | Email: dxphilo@gmail.com

No responses yet