Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

memory
leak
dangling
reference
compiler

What is a lifetime in Rust?

Educative Answers Team

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 ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring