DEV Community

Cover image for What Is Rust Life Time?
Mansoor Ahmed
Mansoor Ahmed

Posted on

What Is Rust Life Time?

Rust Lifetime
The Lifetime explains the scope for which reference is valid.
Lifetimes are implicit and inferred.
Generic lifetime parameters are being used by the Rust to ensure that actual references are used which are valid.
Preventing Dangling references with Lifetimes
When a program tries to access the invalid reference, it is known as a Dangling reference.
The pointer which is pointing to the invalid resource is known as a Dangling pointer.
Example
fn main() {
let a;
{
let b = 10;
a = &b;
}
println!(“a : {}”,a);
}

Output
Output

The outer scope in the above example contains the variable whose named as ‘a’ and it does not contain any value. One inner scope contains the variable ‘b’ and it stores the value 10. The reference of ‘b’ variable is stored in the variable
‘a’. When the inner scope ends, and we try to access the value of ‘a’.

Compile Error
The Rust compiler will throw a compilation error as ‘a’ variable is referring to the location of the variable which is gone out of the scope.The Rust would determine that the code is invalid by using the borrow checker.

Borrow checker
The borrow checker is used to resolve the problem of dangling references. The borrow checker is used to compare the scopes to determine whether they are valid or not.

Lifetime annotation syntax
Lifetime annotation does not replace how long any of the references live.
Functions may also accept the references of any lifetime by using the generic lifetime parameter. Lifetime annotation describes the relationship
among the lifetimes of multiple parameters.

Steps to be followed for the lifetime annotation syntax:
The names of the lifetime parameters should start with (‘) apostrophe.
They are mainly lowercase and short. For example: ‘a. The Lifetime parameter annotation is kept after the ‘&’ of a reference and then space to separate annotation from the reference type.

Lifetime Annotations in Function Signatures
The ‘a represents the lifetime of a reference. Every reference has a lifetime associated with it. We can use the lifetime annotations in function signatures as well.
The generic lifetime parameters are used between angular brackets <> , and the angular brackets are placed between the function name and the parameter list. Let’s have a look:
fn fun<‘a>(…);
In the above case, fun is the function name which has one lifetime, i.e., ‘a. If a function contains two reference parameters with two different lifetimes, then it can be represented as:
fn fun<‘a,’b>(…);
Both & ‘a i32 and & ‘a mut i32 are similar. The only difference is that ‘a is placed between the & and mut. & mut i32 means “mutable reference to an i32” .
& ‘a mut i32 means “mutable reference to an i32 with a lifetime ‘a”.
Lifetime Annotations in struct
We can also use the explicit lifetimes in the struct as we have used in functions.
Let’s look:
struct Example
x : & ‘a i32, // x is a variable of type i32 that has the lifetime ‘a.

Example
fn main() {
let y = &9;
let b = Example{ x: y };
println!(“{}”, b.x);
}
Output
9

impl blocks
We can implement the struct type having a lifetime ‘a using impl block. Let’s see a simple example:
struct Example<‘a> {
x: &’a i32,
}

impl<‘a> Example<‘a>
{
fn display(&self)
{
print!(“Value of x is : {}”,self.x);
}
}

fn main() {
let y = &90;
let b = Example{ x: y };
b.display();
}
Output:
Value of x is : 90

Multiple Lifetimes
There are two possibilities that we can have:
Multiple references have the same lifetime.
Multiple references have different lifetimes.
When references have the same lifetime.
fn fun <‘a>(x: & ‘a i32 , y: & ‘a i32) -> & ‘a i32
//block of code.
In the above case, both the references x and y have the same lifetime, i.e., ‘a.

‘static
The lifetime named as ‘static is a special lifetime. It signifies that something has the lifetime ‘static will have the lifetime over the entire program. Mainly ‘static lifetime is used with the strings. The references which have the ‘static lifetime are valid for the entire program. Let’s look:
let s : & ‘static str = “javaTpoint tutorial” ;

In the above example, the lifetime of ‘a’ variable is shorter than the lifetime of ‘b’ variable. Therefore, the above code runs without any compilation error.

Lifetime annotation syntax
Lifetime annotation does not change how long any of the references live.
Functions may also accept the references of any lifetime by using the generic lifetime parameter. Lifetime annotation describes the relationship among the lifetimes of multiple parameters.

Steps to be followed for the lifetime annotation syntax:
The names of the lifetime parameters should start with (‘) apostrophe.
They are mainly lowercase and short. For example: ‘a. Lifetime parameter annotation is placed after the ‘&’ of a reference and then space to separate annotation from the reference type.

Lifetime Annotations in Function Signatures
The ‘a represents the lifetime of a reference. Every reference has a lifetime associated with it. We can use the lifetime annotations in function signatures as well.
The generic lifetime parameters are used between angular brackets <> , and the angular brackets are placed between the function name and the parameter list. Let’s have a look:
fn fun<‘a>(…);
In the above case, fun is the function name which has one lifetime, i.e., ‘a. If a function contains two reference parameters with two different lifetimes, then it can be represented as:
fn fun<‘a,’b>(…);
Both & ‘a i32 and & ‘a mut i32 are similar. The only difference is that ‘a is placed between the & and mut. & mut i32 means “mutable reference to an i32” . & ‘a mut i32 means “mutable reference to an i32 with a lifetime ‘a”.
Lifetime Annotations in struct
We can also use the explicit lifetimes in the struct as we have used in functions.
Let’s look:
struct Example
x : & ‘a i32, // x is a variable of type i32 that has the lifetime ‘a.

Example
fn main() {
let y = &9;
let b = Example{ x: y };
println!(“{}”, b.x);
}
Output
9

Multiple Lifetimes
There are two possibilities that we can have:
Multiple references have the same lifetime.
Multiple references have different lifetimes.
When references have the same lifetime.
fn fun <‘a>(x: & ‘a i32 , y: & ‘a i32) -> & ‘a i32 //block of code.
In the above case, both the references x and y have the same lifetime, i.e., ‘a.

STATIC
The lifetime named as ‘static is a special lifetime. It signifies that something has the lifetime ‘static will have the lifetime over the entire program. Mainly ‘static lifetime is used with the strings. The references which have the ‘static lifetime are valid for the entire program. Let’s look:
let s : & ‘static str = “javaTpoint tutorial” ;

Lifetime Elision
Lifetime Elision is an inference algorithm which makes the common patterns more ergonomic. Lifetime Elision makes a program to be ellided.

Lifetime Elision can be used anywhere:
& ‘a T
& ‘a mut T
T<‘a>

Lifetime Elision can appear in two ways: Input lifetime: An input lifetime is a lifetime associated with the parameter of a function. Output lifetime: An output lifetime is a lifetime associated with the return type of the function.
For more details visit:https://www.technologiesinindustry4.com/2020/12/what-is-rust-life-time.html

Discussion (0)