Why this func not workings?

fn failed_borrow<'a>() {
    let _x = 12;
    let y: &'a i32 = &_x;
}

fn main() {
    failed_borrow();
}

(Playground)

  1. x life time has greater than y
  2. But why error shows y is longer than x.
  3. What is the meaning of the function signature above

Well the problem is that if I call failed_borrow<'static>, then your code would attempt to create a &'static reference to x, which is not allowed since x does not live forever.

How can i call func with lifetime
failed_borrow<'static>

fn failed_borrow<'a>() -> &'a str {
    "foo"
}

fn main() {
    failed_borrow::<'static>();
}

That's not what it shows. It shows that the reference you tried to store in y lasts longer than x. Here's a case where that doesn't cause any problems:

fn proof_that_i_stored_a_static(_: &'static str) {}
fn main() {
    let y: &str = "foo";
    proof_that_i_stored_a_static(y);
    // `y` drops here.  You can't take a `&'static` reference to `y` itself.
    // But it's okay to store `&'static` references in `y`.
}

When you have a generic parameter, the caller chooses the value of the parameter. So the function signature means "I can run this function with any lifetime you give me!" But as the compiler error showed, that is not true.

Lifetime parameters are generally attached to one of your inputs. If it's unconstrained like this, and it means "I can satisfy any lifetime you give me", it's generally unneeded because you can just use 'static instead. (You have to be able to satisfy 'static, and in most situations, 'static automatically coerces to something smaller.) Example.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.