[SOLVED]A explicit lifetime design question


#1

Here are two functions declare.


fn foo1() -> &str // illegal

fn foo2() -> &'static str; // legal

I think when the Rust compiler meet with the first function declare, because there is no input, the return lifetime is the same with the lifetime of function caller, such as ‘a, all the variables’ lifetime in the foo1 is smaller than 'a, so the compiler think this declare is wrong. But we can actually return a static string etc.

but the second can hold the same reason.

So what’s the design consideration in these ?
maybe the second one is convenient for us to return some const variable or static string ?


#2

Exactly, the second one can return a reference to a static or constant:

static X: i32 = 42;

fn foo3() -> &'static i32 { &X }

the return lifetime is the same with the lifetime of function caller

no, the issue is that there is no input lifetime, so it can’t infer an output lifetime, meaning you need to manually give it an output lifetime:

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

This function isn’t very useful, but you can use it to restrict a 'static lifetime to something shorter.


#3

Thanks! I got it. So every variable in Rust must own a lifetime, no matter explicit or implicit.

what I mis-understand is that I thought the return I thought the following is equal, but it seem wrong.