Lifetimes

Explore lifetimes and understand how they impact the validity and scope of references in Rust.

A lifetime in Rust is a concept that the compiler uses to check if all the borrows in the language are valid. In simple words, a variable’s lifetime starts when it is created and ends when it goes out of scope and is removed from memory. However, it is important to note that a variable’s lifetime is not the same as its scope.

How do lifetimes work?

The code below demonstrates a very simple example of how lifetimes work. It will throw an error when it is run, and we’ll explain why that happens.

Get hands-on with 1400+ tech skills courses.