1

I am new to Rust and currently learning the lifetime annotation topic. I am still not getting the purpose of lifetime annotation. Consider the below example from Rust book:

fn longest<'a> (x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}

/*
fn longest(x: &str, y: &str) -> &str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}
*/

fn main() {
    let x = String::from("abcd");
    let y = String::from("xyz");

    let z = longest(&x, &y);
    println!("{}", z);
}

If I can call the function longest with valid reference arguments then isn't it obvious that the returned reference will also be valid, which in this case is either &x or &y?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Harry
  • 2,177
  • 1
  • 19
  • 33

1 Answers1

2

Imagine you did this

fn main() {
    let x = String::from("abcd");
    let y = String::from("xyz");

    let z = longest(&x, &y);

    // drop `x`, invalidating any references to it
    std::mem::drop(x);

    println!("{}", z);
}

The reference &x was valid when you called longest with it, but it isn't anymore when you refer to z. But z is just &x.

Because you can pass arbitrary arguments to longest at runtime, Rust couldn't possibly know whether z will refer to x or to y which is why you need to tell the compiler that both x and y need to live at least as long as z.

isaactfa
  • 5,461
  • 1
  • 10
  • 24
  • Please do correct me if I am wrong about the following statement: `lifetime concept only applies to reference variables`. Am I correct about this statement? – Harry Aug 09 '22 at 12:52
  • @Harry Not quite. Any type can be bounded by a lifetime, you could write `fn foo<'a, T: 'a>(t: T) -> ...` for example. This will take any reference or trait object that's valid for `'a` but also any owned value like a `String`. [This](https://github.com/pretzelhammer/rust-blog/blob/master/posts/common-rust-lifetime-misconceptions.md) is a really handy reference to understand lifetimes a lot better, I've found. – isaactfa Aug 09 '22 at 12:59