Lifetime Elision

This lesson discusses lifetime elision in Rust.

What Is Lifetime Elision?

Some common coding patterns were identified and annotating them was an extra effort. In order to avoid that overhead, Rust allows lifetimes to be elided or omitted. This is known as lifetime elision. Rust does so by designing rules for omitting lifetime annotation. They are tested at compile time and are used to determine a lifetime.

Lifetime Ellison can appear in two ways:

  • An input lifetime is a lifetime associated with a parameter of a function.

     fn fun_name<'a>( x : & 'a i32);  

    Here, the input lifetime of x is 'a.

  • An output lifetime is a lifetime associated with the return value of a function.

     fn fun_name<'a>() -> & 'a i32;  

    Here, the output lifetime of return value is 'a.

    Note: A function can have both input and output lifetimes.

     fn fun_name<'a>(x : & 'a i32)-> & 'a i32;

    Here, the x has the input lifetime and the return value has the output lifetime.

Rules for Elision

Elision rules are as follows:

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy