What is 'a in Rust Language

I understand basic Borrow check , but this I can not assimilating when i go need this this and why?

fn bar<'a>(...)

1 Like

Part of Rust by Example covers this in depth. To summarize, these are called lifetimes.

fn foo<'a>(/**/);
//      ^-- Lifetime.

We use these to express constraints on the lifetimes of objects.

For example, if we take an structure reference as an input, and return a reference to part of it, we must say that what we return will only live as long as the structure we got the reference from:

struct Bar {
    value: i32,
}

fn get_value<'a>(my_bar: &'a Bar) -> &'a i32 {
    &my_bar.value
}

Lifetimes can also be used to make constraints occur on the lifetimes of objects:

fn foo<'outer, 'inner: 'outer>(value: &'outer &'inner i32);

In the above example we must make sure that the inner value lives as long as the outer. Here's an explanation:

let x = 20; // This is the actual i32    <-------+
let y = &x; // This is the inner reference <---+ |
let z = &y; // This is the outer reference <-+ | |
foo(z);    // <-The outer reference is moved-+ | |
// <---The first reference gets dropped--------+ |
// <--------The original x gets dropped----------+
2 Likes