Rust – Lifetime
Last Updated :
15 Sep, 2022
Lifetimes in Rust refer to the lifetime of how long a variable would live. Lifetimes are associated with references as references cannot live longer than the object from which it is derived. Lifetimes basically describe the scope that a reference is valid for. Lifetimes come into play when we are deallocating an invalid resource
Example 1:
Rust
struct GFG
{
name: String,
id : i32,
}
fn main() {
let x:&GFG;
{
let y: GFG = GFG
{
name : String::from( "GeeksforGeeks" ),
id:2022,
};
}
x = &y;
}
|
Output:
Here, we can see that since x references y that is deallocated when the scope of Y is finished.
Example 2:
Rust
#![allow(dead_code)]
struct GFG
{
name: String,
id : i32,
}
fn function_name(x: &GFG, y: &GFG)->&GFG
{
if x.name == "GeeksforGeeks"
{
x
}
else
{
y
}
}
fn main()
{
let x: GFG = GFG
{
name : String::from( "GeeksForGeeks" ),
id:2022,
};
let y: GFG = GFG
{
name : String::from( "GeeksForGeeks" ),
id:2022,
};
function_name(x,y);
}
|
Output:
Here, we can see that x and y both are referring to the GFG struct. For this, we have a concept of Lifetime annotation in Rust.
Lifetime Annotation:
Lifetime Annotation describes the lifetime of a reference variable.
Syntax:
fn <‘x> function_name( param1: &‘x type) -> &’x return_value
{
statement 1;
statement 2;
…………………….
returnValue;
}
- fn: this is the keyword for defining the lifetime of a function notation
- function_name: name of the function
- ‘x: lifetime notation
- &’x: reference variable containing lifetime ‘x
- returnValue: returns the value of the function
Example 3:
Rust
#![allow(dead_code)]
struct GFG{
name: String,
id : i32,
}
fn function_name< 'g> (x: &' g GFG, y: & 'g GFG) -> &' g GFG{
if x.name == "GeeksforGeeks" {
x
}
else {
y
}
}
fn main(){
let x: GFG = GFG {
name : String::from( "GeeksForGeeks" ),
id:2022,
};
let y: GFG = GFG {
name : String::from( "GeeksForGeeks" ),
id:2022,
};
function_name(&x,&y);
}
|
Output:
Here, we see that the x and y parameters have lifetimes that are the same as that of the function. Hence, the lifetime for both the references is valid too. Hence, the Rust compiler can use the concept borrow checker to check the validity of the reference, and therefore compiler error issues are resolved.
Share your thoughts in the comments
Please Login to comment...