What does the lifetime parameter in the signature denote in the POV of the body when the calling side infers it is `'static`?

⚓ rust    📅 2025-05-06    👤 surdeus    👁️ 6      

surdeus

Warning

This post was published 59 days ago. The information described in this article may have changed.

Consider this example:

struct A<'a>(&'a mut &'a ());
static mut EMPTYREF: &'static () = &();
static AVAR: A<'static> = A(unsafe { &mut *&raw mut EMPTYREF });

fn call<'a>(v: &'a A<'a>) {
    let r: &'a i32 = &0;
    //let rr:&'static i32 = r;  // #1
}
fn main() {
    call(&AVAR);
}

In this example, the lifetime parameter 'a, in the POV of the calling side, must be inferred to be 'static due to the invariance of the lifetime parameter of struct A, however, if #1 is uncommented, the compiler will report an error:

error: lifetime may not live long enough
 --> src/main.rs:7:12
  |
5 | fn call<'a>(v: &'a A<'a>) {
  |         -- lifetime `'a` defined here
6 |     let r: &'a i32 = &0;
7 |     let rr:&'static i32 = r;
  |            ^^^^^^^^^^^^ type annotation requires that `'a` must outlive `'static`

So, what does the parameter lifetime declared in the signature denote in the POV of the function/implementation's body, even though it is inferred to be ''static' in the POV of the calling side?

Does it just denote a specific lifetime that lives in the whole body, regardless of how the calling side infers it? Even though it is inferred as 'static in the POV of the calling side, without having more constraints in the signature, it cannot have that property.

3 posts - 2 participants

Read full topic

🏷️ rust_feed