I implemented a trait to share similar logic between my structs. This trait provides a collect_responses
function, which takes vector of handlers and return vector of responses from the handlers. But after I applied this trait I got an errors like:
error[E0507]: cannot move out of `input`, a captured variable in an `FnMut` closure
--> src/lib.rs:16:30
|
12 | input: HandlerInput
| ----- captured outer variable
...
16 | .map(|func| func(input))
| ------------^^^^^-
| | |
| | move occurs because `input` has type `HandlerInput<'_>`, which does not implement the `Copy` trait
| captured by this `FnMut` closure
error[E0382]: use of partially moved value: `input`
This is my trait code:
pub trait Processor {
fn process_input(input: HandlerInput) -> Result<Vec<HandlerOutput>, Error>;
fn collect_responses(
handlers: Vec<fn(HandlerInput) -> Result<HandlerOutput, Error>>,
input: HandlerInput
) -> Result<Vec<HandlerOutput>, Error> {
let responses = handlers
.iter()
.map(|func| func(input))
.filter(|r| match r {
Ok(_) => true,
_ => false,
})
.map(|r| r.unwrap())
.collect::<Vec<HandlerOutput>>();
return if responses.is_empty() {
Err(
Error::new(
ErrorKind::Other,
"No successful response"
)
)
} else {
Ok(responses)
}
}
}
This is sandbox implementation in context of my real code.
Could somebody explain, why this issue happen and how to fix it ?