【发布时间】:2016-08-03 15:37:50
【问题描述】:
我有一些 Rust 代码正在尝试使用,但我不知道如何去做。
fn main() {
let names = vec!["foo", "bar", "baz"];
let print = printer(names);
let result = print();
println!("{}", result);
do_other_thing(names.as_slice());
}
fn printer(names: Vec<&str>) -> Box<Fn() -> String> {
Box::new(move || {
let text = String::new();
for name in names {
text = text + name;
}
text
})
}
fn do_other_thing(names: &[&str]) {}
编译为:
error[E0477]: the type `[closure@src/main.rs:10:14: 16:6 names:std::vec::Vec<&str>]` does not fulfill the required lifetime
--> src/main.rs:10:5
|
10 | Box::new(move || {
| _____^ starting here...
11 | | let text = String::new();
12 | | for name in names {
13 | | text = text + name;
14 | | }
15 | | text
16 | | })
| |______^ ...ending here
|
= note: type must outlive the static lifetime
我对正在发生的事情有一个模糊的概念。看起来闭包有可能比names 参数更长寿。我可以注释为 'static 但这感觉不对,即使这样我也不想移动向量以便 do_other_thing 工作。我需要以某种方式复制。
【问题讨论】:
标签: rust