I am trying to change the elements of a vector inside a closure:
pub struct Foo<'a, T> {
cb: Box<dyn FnMut(Vec<T>) + 'a>,
}
impl<'a, T> Foo<'a, T> {
pub fn new<F: FnMut(Vec<T>) + 'a>(cb: F) -> Self {
Self { cb: Box::new(cb) }
}
pub fn fun(&mut self, v: T) {
let vector = vec![v];
(self.cb)(vector);
}
}
fn main() {
let mut a = Vec::new();
let mut foo = Foo::new(move |v| {
for i in v {
a.push(i);
}
});
foo.fun(1);
println!("{:?}", a);
}
I'm getting an error:
error[E0382]: borrow of moved value: `a`
--> src/main.rs:24:22
|
17 | let mut a = Vec::new();
| ----- move occurs because `a` has type `std::vec::Vec<i32>`, which does not implement the `Copy` trait
18 | let mut foo = Foo::new(move |v| {
| -------- value moved into closure here
19 | for i in v {
20 | a.push(i);
| - variable moved due to use in closure
...
24 | println!("{:?}", a);
| ^ value borrowed here after move
I understand that Rust can't copy the value of a
in the closure because Vec
does not implement the trait Copy
, so it has to move it, and moving a
as mutable makes it unusable by println!
later.
Am I storing the closure correctly? Is the use of the lifetime 'a
correct here? Should I wrap the vector in something like Box
or Cell
?