The code below works if &dyn Fn(&mut [u8])
is changed to &dyn FnOnce(&mut [u8])
, because then f
can be moved safely. However, I really can't make it FnOnce
because further I find some problems. Fn
would work.
However, I really need to capture the result r
and return it in consume
, like in below
use std::sync::Arc;
pub type OnVirtualTunWrite = Arc<dyn Fn(&dyn Fn(&mut [u8]) , usize) -> Result<(), ()> + Send + Sync>;
struct A {
on_virtual_tun_write: OnVirtualTunWrite
}
impl A {
fn consume<R, F>(self, len: usize, f: F) -> Result<R,()>
where
F: FnOnce(&mut [u8]) -> Result<R,()>,
{
let mut r: Option<Result<R,()>> = None;
let result = (self.on_virtual_tun_write)(&|b: &mut [u8]| {
r = Some(f(b));
}, len);
r.unwrap()
}
}
I know that making it Box<dyn FnOnce(&mut [u8])
would work but I'm trying to avoid dynamic allocation.
Is there a way to make this work?