← Back to list

Why do we need lifetimes in Rust?

I’m currently learning about lifetimes in Rust. I am writing this blog to have a better understanding of lifetimes. Correct me if I am…

Nishant · 2025-08-29 15:06 · 2 claps · 1.6 min read
#rust #learning-rust #lifetime
Open on Medium ↗
Wiki topics: EDU · Education & Learning

Why do we need lifetimes in Rust?

I’m currently learning about lifetimes in Rust. I am writing this blog to have a better understanding of lifetimes. Correct me if I am wrong.

References don’t own data

In Rust, reference ( &T) do not own the data they point towards. So, the compiler must confirm that no reference should outlive the data it points.

Otherwise, we would end up with a dangling pointer.

Example: A Struct With a Reference

struct User {
  name: &str
}

fn main(){
  let user;
  {
    first_name = String::from("Nishant");
    user = User{
      name: &first_name
    }
  }
  println!("{}", user.name);
}

Like in the above diagram, after the completion of the inner block, the reference first_name will be a dangling pointer after the end of the block, as the original data will be deleted from the heap memory after the end of the block. So, we cannot access user.name after the inner block, as the data towards it no longer exists.

Borrow Checker To The Rescue

Rust borrow checker of the Rust compiler does not compile the code without a lifetime when using functions or the structs with references.

The compiler says, “I don’t know how long name will live compared touser, so I can’t allow this reference.”

Fix: Add a Lifetime

In the above diagram, we have defined the lifetime for the User struct

struct User<'r> {
  name: &'r str
}

Now, the struct is tied to the lifetime 'r of the string it borrows. In simple words, this means the reference to the name and user struct will live for the same time(or can be said to have the same lifetime).

This way, the Rust compiler forces user cannot outlive first_name . If, first_name is dropped, it user must also go out of scope.

Rust knows “user is only valid as long as the borrowed string is valid."


메타데이터
post_id
16f12173c30a
slug
why-do-we-need-lifetimes-in-rust-16f12173c30a
url
https://medium.com/@nishujangra27/why-do-we-need-lifetimes-in-rust-16f12173c30a
canonical_url
https://medium.com/@nishujangra27/why-do-we-need-lifetimes-in-rust-16f12173c30a
author_url
https://medium.com/@nishujangra27
status
ok
fetched_at
2026-08-23 05:29:04