Skip to content

Lifetime

  • Every Reference has a Lifetime
  • Lifetime Annotations - 'x
    • &i32
    • &‘a i32
    • &‘a mut i32

Lifetime in Function

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { todo!() }
  • The function signature tells Rust that for some lifetime ‘a, the function takes two parameters, both of which are string slices that live at least as long as lifetime ‘a.
  • The function signature also tells Rust that the string slice returned from the function will live at least as long as lifetime ‘a.
  • In practice, it means that the lifetime of the reference returned by the longest function is the same as the smaller of the lifetimes of the values referred to by the function arguments.

Lifetimes in Struct Definition

struct StructWithLifetime<'a> {
    str_slice_test: &'a str,
    int_test: &'a i32,
}

Lifetime Elision

  • Lifetimes on function or method parameters are called input lifetimes, and lifetimes on return values are called output lifetimes.

Rules for Lifetime Elision

Three rules to figure out the lifetimes, first applies to input lifetime, second and third is applied to output lifetime

  1. Compiler assigns a lifetime parameter to each parameter that’s a reference.

    • One Parameter
    fn foo<'a>(x: &'a i32)
    • Two Parameter
    fn foo<'a, 'b>(x: &'a i32, y: &'b i32)
  2. If there is exactly one input lifetime parameter, that lifetime is assigned to all output lifetime parameters:

fn foo<'a>(x: &'a i32) -> &'a i32.
  1. If there are multiple input lifetime parameters, but one of them is &self or &mut self because this is a method, the lifetime of self is assigned to all output lifetime parameters.

Lifetimes in Method Definition

impl<'a> StructWithLifetime<'a> {}

Static Lifetime

Generic Type, Trait Bounds and Lifetimes Together