I have some Rust code I\'m trying to get working but I\'m not sure how to go about it.
fn main() {
let names = vec![\"foo\", \"bar\", \"baz\"];
let p
The error says that names
must outlive the static lifetime, this is because the boxed Fn
has static lifetime. You have two options:
Add the 'static
lifetime to names
:
fn printer(names: Vec<&'static str>) -> Box<Fn() -> String>{
Box::new(move|| {
// ...
})
}
Change the lifetime of the boxed Fn
to match the names
lifetime:
fn printer<'a>(names: Vec<&'a str>) -> Box<Fn() -> String + 'a>{
Box::new(move|| {
// ...
})
}
Note that the body of closure needs to be adjusted and that you are giving the ownership of names
to printer
, so you cannot use names
in do_other_thing
. Here is a fixed version:
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()
})
}