Rust
December 2, 2026 7 min read

Lifetimes in Rust

HS
HEMANT SINGH
Technical Writer & Educator

1. What Are Lifetimes?

A lifetime describes how long a reference is valid.

In Rust, every reference has a lifetime. Rust checks that the referenced data remains valid for as long as the reference is used.

Consider this example:

fn main() {
let name = String::from("Hemant");

let reference = &name;

println!("{}", reference);
}

This code is valid because name remains alive while reference is being used.

Why Are Lifetimes Important?

Lifetimes prevent problems such as:

  1. Dangling references
  2. Accessing data after it has been destroyed
  3. Returning references to local variables that no longer exist

Rust checks these situations at compile time.

2. Understanding a Dangling Reference

A dangling reference is a reference that points to data that is no longer valid.

Consider this example:

fn main() {
let reference;

{
let name = String::from("Hemant");
reference = &name;
}

println!("{}", reference);
}

This code produces a compiler error.

Why?

  1. name is created inside the inner block.
  2. reference borrows name.
  3. The inner block finishes.
  4. name is destroyed.
  5. The program tries to use reference.

Rust prevents this because the reference would outlive the data it points to.

3. Understanding Lifetime Annotations

Sometimes Rust cannot determine the relationship between references automatically.

In such cases, we can use lifetime annotations.

Lifetime annotations describe relationships between references. They do not extend the actual lifetime of data.

Rust lifetime names usually start with an apostrophe.

Example:

'a
'b
'static

The most commonly used annotation is:

'a

Here, 'a is a lifetime parameter.

It does not represent a fixed amount of time. It represents a relationship between lifetimes.

4. Lifetime Annotation in Functions

Consider a function that accepts two string references and returns one of them.

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}

fn main() {
let first = "Rust";
let second = "Programming";

let result = longest(first, second);

println!("Longest: {}", result);
}

Output:

Longest: Programming

Explanation:

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str
  1. <'a> declares a lifetime parameter.
  2. x: &'a str means x is a string reference with lifetime 'a.
  3. y: &'a str means y has the same declared lifetime.
  4. -> &'a str means the returned reference is associated with that lifetime.

This annotation tells Rust that the returned reference cannot be used beyond the lifetime shared by the input references.

It does not mean that both references must have exactly the same actual lifetime. Rust can choose a shorter common lifetime.

5. Why Do We Need Lifetimes in Functions?

Consider this function:

fn longest(x: &str, y: &str) -> &str {
if x.len() > y.len() {
x
} else {
y
}
}

Rust cannot determine the relationship between the input references and the returned reference from this signature alone.

The compiler will report a missing lifetime specification.

We can fix it by adding a lifetime annotation:

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}

Now Rust knows the relationship between the references.

6. Lifetime Annotations with Structs

A struct can also store references.

When a struct contains references, it may need lifetime annotations.

Example:

struct Student<'a> {
name: &'a str,
}

fn main() {
let student_name = "Hemant";

let student = Student {
name: student_name,
};

println!("Student: {}", student.name);
}

Output:

Student: Hemant

Explanation:

struct Student<'a> {
name: &'a str,
}

The lifetime 'a tells Rust that the reference stored in Student must remain valid for the relevant lifetime of the struct.

The struct does not own the name. It borrows it.

7. Multiple Lifetime Parameters

Sometimes a function or struct needs more than one lifetime parameter.

Example:

fn compare<'a, 'b>(
first: &'a str,
second: &'b str
) {
println!("First: {}", first);
println!("Second: {}", second);
}

fn main() {
let name = "Hemant";
let course = "Rust";

compare(name, course);
}

Output:

First: Hemant
Second: Rust

Here:

  1. 'a represents the lifetime of the first reference.
  2. 'b represents the lifetime of the second reference.

The two references do not need to have the same lifetime.

8. Lifetime Annotations with Methods

You can also use lifetime annotations in methods.

Example:

struct Student<'a> {
name: &'a str,
}

impl<'a> Student<'a> {
fn get_name(&self) -> &str {
self.name
}
}

fn main() {
let name = "Hemant";

let student = Student {
name,
};

println!("{}", student.get_name());
}

Output:

Hemant

The returned reference is tied to the borrow of self through lifetime elision rules.

9. The Static Lifetime ('static)

Rust provides a special lifetime called 'static.

A reference with the 'static lifetime can remain valid for the entire duration of the program.

Example:

fn main() {
let message: &'static str = "Hello Rust";

println!("{}", message);
}

Output:

Hello Rust

String literals have the 'static lifetime because they are stored in the program's binary.

Another example:

static COMPANY: &str = "Capscom Technology";

fn main() {
println!("{}", COMPANY);
}

Output:

Capscom Technology

Important: Do not use 'static simply to fix lifetime errors. It means the reference must genuinely be valid for the entire program.

10. Lifetime Elision Rules

Rust can automatically determine lifetimes in many situations.

This is called lifetime elision.

For example:

fn get_name(name: &str) -> &str {
name
}

You do not need to write:

fn get_name<'a>(name: &'a str) -> &'a str {
name
}

Both signatures have the same meaning.

Rust applies lifetime elision rules to determine the relationship.

The Three Lifetime Elision Rules

  1. Each reference parameter gets its own lifetime parameter.
  2. If there is exactly one input lifetime, that lifetime is assigned to all output references.
  3. If one of the input parameters is &self or &mut self, the lifetime of self is assigned to output references.

These rules allow many functions to be written without explicit lifetime annotations.

11. Lifetime Bounds

A lifetime bound can specify that one lifetime must outlive another.

The syntax uses the : symbol.

Example:

fn display<'a, 'b>(name: &'a str, course: &'b str)
where
'a: 'b,
{
println!("Name: {}", name);
println!("Course: {}", course);
}

fn main() {
let name = "Hemant";
let course = "Rust";

display(name, course);
}

Here:

'a: 'b

means that lifetime 'a must last at least as long as lifetime 'b.

12. Static Lifetime Bound with Generics

You can combine lifetimes with generic type parameters and trait bounds.

Example:

use std::fmt::Display;

fn display<T: Display + 'static>(value: T) {
println!("{}", value);
}

fn main() {
display(100);
display(String::from("Rust"));
}

Here, T: 'static means that the type does not contain non-static borrowed references.

It does not mean that the value itself must live forever.

For example, an owned String can be dropped normally even though String satisfies the 'static bound.

13. Difference Between Ownership, Borrowing, and Lifetimes


Concept

Purpose

Ownership

Determines who owns a value

Borrowing

Allows references to access a value

Lifetimes

Ensure references remain valid while used

Example:

fn main() {
let name = String::from("Hemant");

let reference = &name;

println!("{}", reference);
}
  1. name owns the String.
  2. reference borrows the String.
  3. Rust checks that name remains valid while reference is used.

14. Common Mistakes


Mistake

Explanation

Returning a reference to a local variable

The local variable is destroyed when the function ends

Thinking 'a means a fixed duration

It represents a lifetime relationship

Adding 'static everywhere

It does not solve ordinary lifetime problems

Forgetting lifetime parameters in reference-holding structs

The struct may need to specify how long its references remain valid

Confusing borrowing with ownership

A reference does not become the owner of the data