我有一个函数可以从文件中加载名为Executor
的结构,并返回对其的引用。
Executor
结构包含字段Module
,它将编译并正常工作Executor
结构包含字段Arc<Module>
,它将不会编译,并会抱怨该结构属于当前函数。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
在我看来,在两种情况下,结构Executor
都属于所分配的函数。
我该怎么做?