Lifetimes
When we are dealing with references, we have to make sure that the referencing data stay alive until we are stop using the references.
Think,
We have a variable binding, “a”.
We are referencing the value of “a”, from another variable binding “x”.
We have to make sure that “a” lives until we stop using “x”
🔎 Memory management is a form of resource management applied to computer memory. Up until the mid-1990s, the majority of programming languages used Manual Memory Management which requires the programmer to give manual instructions to identify and deallocate unused objects/ garbage. Around 1959 John McCarthy invented Garbage collection(GC), a form of Automatic Memory Management(AMM). It determines what memory is no longer used and frees it automatically instead of relying on the programmer. However Objective-C and Swift provide similar functionality through Automatic Reference Counting(ARC).
What is Lifetimes?
In Rust,
A resource can only have one owner at a time. When it goes out of the scope, Rust removes it from the Memory.
When we want to reuse the same resource, we are referencing it/ borrowing its content.
When dealing with references, we have to specify lifetime annotations to provide instructions for the compiler to set how long those referenced resources should be alive.
⭐ ️But because of lifetime annotations make code more verbose, in order to make common patterns more ergonomic, Rust allows lifetimes to be elided/omitted in
fn
definitions. In this case, the compiler assigns lifetime annotations implicitly.
Lifetime annotations are checked at compile-time. Compiler checks when a data is used for the first and the last times. According to that, Rust manages memory in run time. This is the major reason of having slower compilation times in Rust.
Unlike C and C++, usually Rust doesn’t explicitly drop values at all.
Unlike GC, Rust doesn’t place deallocation calls where the data is no longer referenced.
Rust places deallocation calls where the data is about to go out of the scope and then enforces that no references to that resource exist after that point.
Usage
Lifetimes are denoted with an apostrophe. By convention, a lowercase letter is used for naming. Usually starts with 'a
and follows alphabetic order when we need to add multiple lifetime annotations.
When using references,
01. On Function Declaration
Input and output parameters with references should attach lifetimes after
&
sign. ex..(x: &'a str)
,..(x: &'a mut str)
After the function name, we should mention that the given lifetimes are generic types. ex
fn foo<'a>(..)
,fn foo<'a, 'b>(..)
02. On Struct or Enum Declaration
Elements with references should attach lifetimes after
&
sign.After the name of the struct or enum, we should mention that the given lifetimes are generic types.
03. With Impls and Traits
04. With Generic Types
Lifetime Elision
As I mentioned earlier, in order to make common patterns more ergonomic, Rust allows lifetimes to be elided/omitted. This process is called Lifetime Elision.
💡 For the moment Rust supports Lifetime Elisions only on fn
definitions. But in the future it will support for impl
headers as well.
Lifetime annotations of fn
definitions can be elided
if its parameter list has either,
only one input parameter passes by reference.
a parameter with either
&self
or &mut self reference.
💡 In the Lifetime Elision process of fn definitions,
Each parameter passes by reference is got a distinct lifetime annotation.
ex.
..(x: &str, y: &str)
→..<'a, 'b>(x: &'a str, y: &'b str)
If the parameter list has only one parameter passes by reference, that lifetime is assigned to all elided lifetimes in the return values of that function.
ex.
..(x: i32, y: &str) -> &str
→..<'a>(x: i32, y: &'a str) -> &'a str
Even it has multiple parameters pass by reference, if one of them has &self or &mut self, the lifetime of self is assigned to all elided output lifetimes.
ex.
impl Impl{ fn function(&self, x: &str) -> &str {} }
→
impl<'a> Impl<'a>{ fn function(&'a self, x: &'b str) -> &'a str {} }
For all other cases, we have to write lifetime annotations manually.
'static
Annotations
'static
Annotations'static
lifetime annotation is a reserved lifetime annotation. These references are valid for the entire program. They are saved in the data segment of the binary and the data referred to will never go out of scope.
Few more examples about usage of Rust lifetimes.
Last updated