我正在尝试用Rust编写一个小程序,但是它无法正常工作。
我已经在一个更小的脚本中复制了这个错误:
fn main() {
let name = String::from("World");
let test = simple(name);
println!("Hello {}!", test())
}
fn simple<T>(a: T) -> Box<Fn() -> T> {
Box::new(move || -> T {
a
})
}
当我编译它时,会出现以下错误:
error[E0310]: the parameter type `T` may not live long enough
--> test.rs:8:9
|
7 | fn simple<T>(a: T) -> Box<Fn() -> T> {
| - help: consider adding an explicit lifetime bound `T: 'static`...
8 | / Box::new(move || -> T {
9 | | a
10 | | })
| |__________^
|
note: ...so that the type `[closure@test.rs:8:18: 10:10 a:T]` will meet its required lifetime bounds
--> test.rs:8:9
|
8 | / Box::new(move || -> T {
9 | | a
10 | | })
| |__________^
我尝试添加一个显式的生命周期限制T: 'static
,如错误建议所示,但是我得到了一个新的错误:
error[E0507]: cannot move out of captured outer variable in an `Fn` closure
--> test.rs:9:13
|
7 | fn simple<T: 'static>(a: T) -> Box<Fn() -> T> {
| - captured outer variable
8 | Box::new(move || -> T {
9 | a
| ^ cannot move out of captured outer variable in an `Fn` closure
T: 'static
) - MB-Fa
)移出Fn
闭包 - 在第一次调用之后,它不再存在。 - MB-F'static
生命周期时,会出现以下错误:error[E0507]: cannot move out of captured outer variable in an `Fn` closure
。 - b1zzua
移出闭包? - b1zzu