我有一些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
起作用。我需要以某种方式复制。
该错误表明names
必须超过静态寿命,这是因为盒装Fn
具有静态寿命。您有两种选择:
将'static
生存期添加到names
:
fn printer(names: Vec<&'static str>) -> Box<Fn() -> String>{
Box::new(move|| {
// ...
})
}
更改盒装Fn
的names
寿命以匹配寿命:
fn printer<'a>(names: Vec<&'a str>) -> Box<Fn() -> String + 'a>{
Box::new(move|| {
// ...
})
}
请注意,需要调整闭包的主体,并且您要赋予names
to的所有权printer
,因此不能names
在中使用do_other_thing
。这是固定版本:
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<'a>(names: &'a Vec<&str>) -> Box<Fn() -> String + 'a>{
Box::new(move || {
// this is more idiomatic
// map transforms &&str to &str
names.iter().map(|s| *s).collect()
})
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句