Member-only story

Lifetimes in Rust are not that hard to understand.

applied.math.coding
4 min readFeb 8, 2023

When learning Rust, the first time one encounters a compilation error that states about lifetimes, can be a confusing experience. The first thing to understand about lifetimes is that it provides yet another level of security to our program.

As we all know and probably do, sharing references is a lot better than passing data by copying their values. Though, references are easily out of scope when not considered carefully.

So for instance

let mut r: &Vec<u32>;
{
let x = vec![1,2,3];
r = &x;
} // <-- the value owned by x is dropped
r // <-- r points to a dropped value: ERROR!

The “life” of x‘s value is bound to the code block wrapped by { ... }. Therefore, the “life” of a reference like r pointing to this value, exactly has the same “time of life”.

All good — and the Rust compiler would complain when detected an situation like the one above.

Another (C++ -traditional) example is the following:

fn f() -> &Vec<u32> {
let x =…

applied.math.coding
applied.math.coding

Written by applied.math.coding

I am a Software Developer - Java, Rust, SQL, TypeScript - with strong interest doing research in pure and applied Mathematics.

No responses yet

Write a response