Lifetimes in Rust

August 20243 min read
image

All variables belong to a scope

Let's create a variable a in the main scope and variable b in a local scope.


fn main() {## start of main scope let a = 1; {## start of local scope let b = 2; } }

We'll then assign variable a to b and add a print statement in the main scope.


fn main() { let a = 1; { let b = 2; a = &b; } println!("{}", a); } ## does not compile

This program will not compile. That is because variable a is referencing a variable b that does not live outside its scope.

b's lifetime only lasts within a temporary scope. This is Rust's mechanism for avoiding dangling pointers and the reason it is considered a safe language.

A longer-lasting variable

What if we want a variable to last longer than its existing scope.

Here is where lifetimes come into play. Lifetimes allow a reference to a variable to remain valid as long as needed.

In the code snippet below, the program does not compile.


fn func(n: &i32, _m: &i32) -> &i32 { n } fn main() { let x; let z = 1; { let y = 3; x = func(&z, &y); } println!("{}", x); } ## does not compile

The reason being as before, variable x is making use of a short-lived variable y.

Let's introduce lifetimes to the code to make it compile.


fn func<'a, 'b>(n: &'a i32, _m: &'b i32) -> &'a i32 { n } fn main() { let x; let z = 1; { let y = 3; x = func(&z, &y); } println!("{}", x); }

Here we've declared 2 lifetimes a and b using angle brackets. We've asked the compiler to allow a lifetime a to the returned value of the function func.

Lifetime a is equivalent to the lifetime of variable z found in the main scope. The program now compiles successfully.

If we instead give the return value of func lifetime b, the program will not compile because lifetime b is equivalent to the local scope where y lives.



Summary:
  • Variables created within a scope {} live as long as that scope lasts.
  • A reference to a variable is allowed so long as that variable exists. Rust's way of avoiding dangling pointers.
  • Lifetimes allow a reference to a variable to remain valid for as long as needed.

A newsletter for web3 developers

Subscribe to get the latest posts.