Following on in my dive into the concept of ownership in Rust, will assess the idea of lifetimes. I will follow the documentation at rust-lang.org. The tutorial breaks down the concept in three chunks:
-
Ownership (Covered in a previous post)
-
References and Borrowing (Covered in a previous post)
-
Lifetimes
In this post will summarize my general understanding of lifetimes.
tl;dr: the concept of lifetimes seems quiet complex, but makes “lifetimes” of values transparent and promotes safer programming.
Point #1: “use after free” prevention
The documentation provides a rather intuitive break down of an example of what the concept of lifetimes is attempting to prevent.
-
I acquires a handle to some kind of resource.
-
I lend a reference to the resource to you.
-
I free the resource, as I am done with the resource, and decide to deallocate.
-
You decide to use the resource.
This would cause an error. The reference you have been lent is now pointing at an invalid resource. The ‘use after free’ concept should be familiar and applies to this scenario.
The above would fail, as a you is referecing a resource that has gone out of scope. The rust compiler is able to catch this as a result of having visibility on the “lifetimes” of different values.
Point #2: syntax
Some syntax to keep in mind. Rust allows functions to have generic parameters placed between <>:
Point #3: ‘static lifetime
Static lifetime is a special type of lifetime that has a lifetime over the entire program.