I've got a struct defined that has a function which defines a static lifetime:
impl MyStruct {
pub fn doSomething(&'static self) {
// Some code goes here
}
}
I'm consuming it from main like so:
fn main() {
let obj = MyStruct {};
obj.doSomething();
}
It's intended for the doSomething
call to block and execute for the lifetime of the application.
I'm running into issues with the lifetime checks where it's stating that it may outlive the main
function, which seems strange to me as once main
is complete the application should exit.
Is there a way to achieve this?
The naive way to do this is with a
static
variable, but it will require unsafe code if you need to actually set the value inside yourmain
function:It's also
unsafe
to do pretty much anything with a mutable static thereafter.The much better way to do it is to let a library (
lazy_static
) take care of the unsafe code.The primary way to create a reference that has the
'static
lifetime is to make the variablestatic
. A static variable is one that can be created at compile time:As Rust's constant evaluation story improves, this will be more common, but it will never allow configuration at runtime.
A far less common method is to deliberately leak memory, producing a reference that will last "forever". This should be discouraged because leaking memory isn't a good thing:
There's also the possibility of creating a singleton:
Perhaps, but the compiler doesn't treat
main
specially for lifetime purposes.No, it doesn't. It has a bound of
: 'static
, which means that any references passed in must be'static
, but you don't have to pass in a bare reference at all.For patterns like this, the most common thing is to pass in something like an
Arc
. This allows sharing of the underlying resource.You can even use interior mutability if you wanted dynamic reconfiguration.
See also: