Rust borrowingEnumsFunctionsGenericsLifetimesReferencesRustStructs

Article & Tutorial

Rust Lifetimes Explained: Lifetime Annotations, Elision, Structs and 'static

Learn Rust lifetimes, lifetime annotations, elision rules, lifetime parameters in functions and structs, 'static and how lifetimes prevent dangling references.

Rust Lifetimes Explained: Lifetime Annotations, Elision, Structs and 'static abstract technical illustration
Rust Lifetimes Explained: Lifetime Annotations, Elision, Structs and 'static abstract technical illustration
Contents

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

bash
let reference; { let value = String::from("temporary"); reference = &value; } // println!("{reference}"); // rejected: value no longer exists

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

bash
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

bash
&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.

bash
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

bash
#[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

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

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

bash
struct OwnedConfig { service_name: String, }

Mini lab: choose the longer label

bash
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

bash
owned value exists │ ├── reference borrows it │ │ │ └── reference must not outlive owner │ └── owner drops → old references may no longer be used

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

Did this help?

Yes No

Join the discussion

0 Comments

Ask questions, add context, or share what worked.

Sign in to join the discussion

No comments yet. Start the discussion.

More from Melochip Editorial

Related articles

Stay in the loop. Get new Melochip articles

Receive Melochip article updates when new articles are available. Explicit opt-in only.

No pre-checked boxes. Unsubscribe support is part of the subscriber foundation.