Trusted answers to developer questions

What is a lifetime in Rust?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

One of the most distinguished traits of Rust is that the majority of errors are handled during compile-time. Rust’s compiler has a Borrow Checker that compares scopes (aka lifetimes) of variables and their references to avoid invalid memory access during run-time.

For example, consider the code below; it does not compile because the reference,x, has a larger scope than the subject of the reference, y. This is why we get the error message "y does not live long enough."

fn main() {
let x; //--------+(a)
{ // |
let y = 2; //--+(b) |
x = &y; // | |
} //--+ |
} //--------+
svg viewer

If the subject of the reference has a larger lifetime than the reference variable, the program will compile. As an example, let’s swap variables x and y to get rid of the error:

fn main() {
let x = 2; //--------+(a)
{ // |
let y = &x; //--+(b) |
} //--+ |
} //--------+

Since the subject (x) has a larger lifetime than the reference (y), the program compiles successfully.

RELATED TAGS

memory
leak
dangling
reference
compiler
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?