Open In App

Rust – Lifetime

Last Updated : 15 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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




// Rust program for when we can 
// determine the variable lifetime 
// by looking at the code.
  
struct GFG
{
   name: String,
   id : i32,
}
  
fn main() {
  let x:&GFG;
    {
    let y: GFG = GFG 
      {
      name : String::from("GeeksforGeeks"),
      id:2022,
      };
    }
    x = &y; 
    
  // allocated reference to a 
  // memory location that is dropped
}


Output:

 

Here, we can see that since x references y that is deallocated when the scope of Y is finished. 

Example 2:

Rust




// Rust-Lifetime program when nothing can
// be determined by the lifetime of a variable
  
#![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,
}
//'g -> lifetime annotation
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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads