Rust Learning Path — Chapter 15. Lifetimes describe relationships between references. They do not make values live longer; they help the compiler verify that references never outlive the data they point to.
Why lifetimes exist
let reference; { let value = String::from("temporary"); reference = &value; } // println!("{reference}"); // rejected: value no longer existsRust prevents this dangling reference at compile time.
When annotations are needed
Many lifetimes are inferred. An annotation becomes necessary when a function returns a reference and the compiler needs to know which input reference the output is related to.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } }The annotation says that the returned reference is valid only for a lifetime compatible with both input references. It does not extend either input's actual lifetime.
Lifetime syntax
&i32 &'a i32 &'a mut i32'a is a named lifetime parameter, similar in placement to a generic type parameter.
Lifetime elision
Rust has rules that allow common signatures to omit explicit lifetime annotations.
fn first_word(text: &str) -> &str { text.split_whitespace().next().unwrap_or("") }The compiler can infer that the returned slice is tied to the input reference.
Lifetimes in structs
#[derive(Debug)] struct Excerpt<'a> { text: &'a str, } fn main() { let article = String::from("Rust lifetimes keep references safe."); let excerpt = Excerpt { text: &article[..14] }; println!("{excerpt:?}"); }The struct cannot outlive the borrowed text it contains.
Lifetimes with methods
impl<'a> Excerpt<'a> { fn text(&self) -> &str { self.text } }What does 'static mean?
'static means a reference can be valid for the entire program. String literals have a 'static lifetime because they are embedded in the program binary.
let message: &'static str = "service started";Do not use 'static merely to silence lifetime errors. Usually the right fix is to model ownership and borrowing correctly.
Owned data can simplify designs
If a structure needs data independently of a caller's scope, owning a String is often clearer than storing &str and introducing a lifetime parameter.
struct OwnedConfig { service_name: String, }Mini lab: choose the longer label
fn choose_longer<'a>(left: &'a str, right: &'a str) -> &'a str { if left.len() >= right.len() { left } else { right } } fn main() { let api = String::from("payments-api"); let db = String::from("db"); println!("{}", choose_longer(&api, &db)); }Mental model
owned value exists │ ├── reference borrows it │ │ │ └── reference must not outlive owner │ └── owner drops → old references may no longer be usedCommon mistakes
- Thinking lifetime annotations extend how long data lives.
- Returning a reference to a local value created inside a function.
- Adding 'static as a universal fix.
- Borrowing data in a struct when owning it would make the API simpler.
Stage 3 checkpoint
You now have the core tools for collections, explicit errors, generic reusable code, trait-based behavior, and safe reference relationships. These concepts are the bridge from small Rust examples to maintainable application architecture.
Next: Stage 4 — Modules, packages and crates.
Join the discussion
0 CommentsAsk questions, add context, or share what worked.
More from Melochip Editorial
Learn what Playwright testing is, why modern QA teams use it, how testers can get started, and the major types...
7 min read · Sep 19, 2026
Learn how Kubernetes Deployments and ReplicaSets work with practical YAML, scaling, self-healing, rolling upda...
7 min read · Sep 17, 2026
Learn Kubernetes security best practices with RBAC, Secrets, ServiceAccounts, Pod securityContext, NetworkPoli...
6 min read · Sep 17, 2026Related articles
Learn Kubernetes Ingress with controllers, IngressClass, host and path routing, TLS, DNS, annotations, redirec...
8 min read · Sep 17, 2026
Learn how Kubernetes Deployments and ReplicaSets work with practical YAML, scaling, self-healing, rolling upda...
7 min read · Sep 17, 2026
Learn Kubernetes monitoring and logs with kubectl logs, events, metrics-server, top commands, Prometheus, Graf...
5 min read · Sep 17, 2026
Learn Kubernetes ConfigMaps and Secrets with YAML, environment variables, file mounts, update behavior, immuta...
8 min read · Sep 17, 2026Stay in the loop. Get new Melochip articles
Receive Melochip article updates when new articles are available. Explicit opt-in only.
No comments yet. Start the discussion.