I have a function that loads an struct called Executor
from a file and returns a reference to it.
- if the
Executor
struct contains a fieldModule
, it compiles and works - if the
Executor
struct contains a fieldArc<Module>
, it won't compile and complains struct belongs to the current function.
use std::sync::Arc;
#[derive(Debug)]
struct Module {
foo: bool,
}
#[derive(Debug)]
struct Executor {
module: Module,
}
impl Executor {
pub fn load() -> Result<&'static Executor, ()> {
Ok(&Executor {
module: Module { foo: true },
})
}
}
#[derive(Debug)]
struct ExecutorArc {
module: Arc<Module>,
}
impl ExecutorArc {
pub fn load() -> Result<&'static ExecutorArc, ()> {
Ok(&ExecutorArc {
module: Arc::new(Module { foo: true }),
})
}
}
fn main() {
let executor = Executor::load().unwrap();
println!("executor = {:?}", executor);
let executor_arc = ExecutorArc::load().unwrap();
println!("executor_arc = {:?}", executor_arc);
}
error[E0515]: cannot return value referencing temporary value
--> src/main.rs:28:9
|
28 | Ok(&ExecutorArc {
| __________^___-
| | _________|
| ||
29 | || module: Arc::new(Module { foo: true }),
30 | || })
| ||_________-^ returns a value referencing data owned by the current function
| |__________|
| temporary value created here
It seems to me that in both cases the struct Executor
belongs to the function called, where it is allocated.
How can I do something like this?