If you really must create the data at runtime, and you really need to last for 'static
, then you can use one of the memory leaking methods such as Box::leak
or Vec::leak
to deliberately leak a heap allocation and ensure it is never freed.
While leaking memory is normally something one avoids, in this case it's actually a sensible thing to do. If the data must live forever then leaking it is actually the correct thing to do, semantically speaking. You don't want the memory to be freed, not ever, which is exactly what happens when memory is leaked.
Example:
fn require_static_data(data: &'static [u8]) {
unimplemented!()
}
fn main() {
let data = vec![1, 2, 3, 4];
require_static_data(data.leak());
}
Playground
That said, really think over the reallys I led with. Make sure you understand why the code you're calling wants 'static
data and ask yourself why your data isn't already 'static
.
Is it possible to create the data at compile time? Rust has a powerful build time macro system. It's possible, for example, to use include_bytes!
to read in a file and do some processing on it before it's embedded into your executable.
Is there another API you can use, another function call you're not seeing that doesn't require 'static
?
(These questions aren't for you specifically, but for anyone who comes across this Q&A in the future.)
include_bytes!
at a minimum. That's just wild for compile-time reading in of files/data. I can see how useful that could be, and yet also how utterly abused it would be by some developers I know. And on occasion, I'll admit I'll probably be both types of developer! – Leyte