I need to use a string for the entire life of the program. But the string is actually computed at runtime (actually by a separate process, so I get it using std::process::Command
). Here’s the idea (which doesn’t work):
#[macro_use] extern crate lazy_static;
fn main() {
let a = expensive_to_compute_data();
println!("{}", a);
let b = expensive_to_compute_data();
println!("{}", b);
}
lazy_static! {
pub static ref DATA: String = String::new();
}
pub fn expensive_to_compute_data() -> &'static str {
if DATA.is_empty() { // Will only happen once
let s = "VERY EXPENSIVE COMPUTATION";
DATA.push_str(s);
}
&DATA
}
Is this doable? If so, how?
Playground
This seems to work though:
fn main() {
let a = expensive_to_compute_data();
println!("{}", a);
let b = expensive_to_compute_data();
println!("{}", b);
}
static mut DATA: &str = "";
pub fn expensive_to_compute_data() -> &'static str {
unsafe {
if DATA.is_empty() {
DATA = get_data();
}
DATA
}
}
pub fn get_data() -> &'static str {
"VERY EXPENSIVE COMPUTATION"
}