I have the following struct with implementation of the new()
method:
pub struct Subscriber<NextFnType> {
next_fn: Box<dyn FnMut(NextFnType)>,
complete_fn: Option<Box<dyn FnMut()>>,
}
impl<NextFnType> Subscriber<NextFnType> {
pub fn new(next_fnc: impl FnMut(NextFnType) + 'static,
complete_fnc: Option<impl FnMut() + 'static>) -> Self {
let mut s = Subscriber {
next_fn: Box::new(next_fnc), // <-- Ok
complete_fn: None,
};
if let Some(cfn) = complete_fnc {
s.complete_fn = complete_fnc.take().map(|f| Box::new(f)); // <-- Not Ok
}
s
}
}
Rust allows boxing first parameter impl FnMut(NextFnType) + 'static
, but reports mismatched error when I try to box second parameter which is optional Option<impl FnMut() + 'static>
.
Compiler reports:
expected enum Option<Box<(dyn FnMut() + 'static)>>
found enum Option<Box<impl FnMut() + 'static>>
I know I can use type Option<Box<(dyn FnMut() + 'static)>>
as a second type parameter but I don't want to change function signature.
Is there a way to Box
it like this, and why does Rust allows boxing impl
types when type is standalone and forbids when type is wrapped in Option
?