【发布时间】:2018-04-19 10:33:30
【问题描述】:
我正在尝试用 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)? -
另请注意,您不能将变量 (
a) 从Fn闭包中移出 - 在第一次调用后它将不再存在。 -
你的目标是什么?
-
当我把
'static生命周期我得到这个错误:error[E0507]: cannot move out of captured outer variable in an `Fn` closure -
有...各种解决方案,通常表示问题过于宽泛而无法回答。我想是时候让你告诉我们更多关于你的实际目标了 :)