Diverging functions never return, so their local variables are never dropped. Would it be possible to set their lifetime to 'static in the compiler?
Currently the following error occurs:
fn foo() -> ! {
let x = 42;
bar(&x);
loop {}
}
fn bar(_: &'static u32) {}
error[E0597]: `x` does not live long enough
--> src/main.rs:7:9
|
7 | bar(&x);
| ----^^-
| | |
| | borrowed value does not live long enough
| argument requires that `x` is borrowed for `'static`
8 | loop {}
9 | }
| - `x` dropped here while still borrowed
The compiler checks that the function is really diverging, so it knows that line 9 is never reached and that x is never dropped. So why not treat x as 'static?
This feature would be useful for embedded/OSdev where some static structures are needed for hardware initialization. For example, on x86_64 an interrupt descriptor table with 'static lifetime needs to be created and loaded in the CPU before enabling interrupts. Currently, we use lazy_static to construct this table with a 'static lifetime, but it would be easier if we could just use a local variable of our diverging kernel_main function.