I made a minimal example with an Accumulator
class: it takes an operator that mutates a value, and can call it a number of times.
I then tried to make a helper constructor taking a "const" binary operator, that would wrap the operator in a closure, making it mutate the underlying accumulator:
impl<T, F> Accumulator<T, F>
where
F: FnMut(&mut T, &T),
{
fn new(initial: T, accumulate: F) -> Accumulator<T, F> {
Accumulator {
acc: initial,
accumulate,
}
}
fn new_binary_op(initial: T, binary_op: impl FnMut(T, &T) -> T) -> Accumulator<T, F> {
let accumulate = |a: &mut T, b: &T| *a = binary_op(*a, b);
Accumulator {
acc: initial,
accumulate,
}
}
}
However I get the following error:
= note: expected type parameter `F`
found closure `[closure@src/main.rs:21:26: 21:44]`
= help: every closure has a distinct type and so could not always match the caller-chosen type of parameter `F`
I understand the error just enough to think that this means I can't write impl<F>
and then decide that F
is a closure, but then what kind of impl
block should I place new_binary_op
into?