Lifetime error should point out the reason for a lifetime

This is the error message I got:

error[E0597]: `shader_file_path_string` does not live long enough
   --> shader_roy/src/main.rs:60:48
    |
60  |     let shader_file_path = std::path::Path::new(&shader_file_path_string);
    |                           ---------------------^^^^^^^^^^^^^^^^^^^^^^^^-
    |                           |                    |
    |                           |                    borrowed value does not live long enough
    |                           argument requires that `shader_file_path_string` is borrowed for `'static`
...
242 | }
    | - `shader_file_path_string` dropped here while still borrowed

error: aborting due to previous error

For more information about this error, try `rustc --explain E0597`.

The problem is, this doesn't tell me why shader_file_path is expected to live for the static lifetime (well, it doesn't even tell me that, it only talks about shader_file_path_string). In my code, the reason is this part:

    events_loop.run(move |_, _, _| {
        foo(shader_file_path)?;
    });

Where the run function has this signature:

pub fn run<F>(self, event_handler: F) -> !
    where
        F: 'static + FnMut(Event<'_, T>, &EventLoopWindowTarget<T>, &mut ControlFlow),
    {
        self.event_loop.run(event_handler)
    }

The error message should ideally include a pointer to the lambda, and a pointer to the declaration of run which specifies the 'static constraint.

Meta: I'm tagging this with "language design" category, but it feels like there should be a "devx" category focused on errors.

3 Likes

Here's a self-contained test case, in case it helps anyone working on this:

fn main() {
    pub fn run<F>(_: F) where F: 'static + Fn() {}

    let x = String::new();
    let y = std::path::Path::new(&x);
    run(move || { dbg!(y); });
}

(Playground)

It looks like this is related to No explanation for source of static lifetime requirement in E0597 · Issue #43531 · rust-lang/rust · GitHub

3 Likes