I’d like to pass a closure to a methods which mutates a captured variable.
I can do it, but then the compiler suggests me to give the static lifetime to the captured variables, or they may not live long enough. I have a hunch that this is not what I want, but I’m a bit stuck.
Here is an example:
fn main() {
struct NeedleFinder {
on_needle_found: Box<dyn FnMut(usize)>,
}
impl NeedleFinder {
fn new(on_needle_found: Box<dyn FnMut(usize)>) -> Self {
Self { on_needle_found }
}
fn find_needles(& mut self, haystack: &Vec<&str>) {
for (i, element) in haystack.iter().enumerate() {
if *element == "needle" {
(self.on_needle_found)(i);
}
}
}
}
// This poses no problem
let mut needle_finder = NeedleFinder::new(Box::new(|index| {
println!("Found needle at index {}", index);
}));
needle_finder.find_needles(&vec!["haystack", "needle", "haystack", "needle"]);
/*
// This on the other hand does not work
let mut needle_positions: Vec<usize> = vec![];
let mut needle_finder = NeedleFinder::new(Box::new(|index| {
println!("Found needle at index {}", index);
needle_positions.push(index);
}));
needle_finder.find_needles(&vec!["haystack", "needle", "haystack", "needle"]);
*/
}
and the playground link.
I imagine this is a trivial problem for someone versed in rust, but I’m struggling a bit here, I’ll take any suggestion!