How do i store an async function pointer with pointer arguments?
i can store a function with owned arguments like so:
use std::{collections::HashMap, future::Future, pin::Pin, sync::Arc};
struct Param {}
type Res = Result<(), ()>;
type Handler = Arc<dyn FnOnce(Param) -> Pin<Box<dyn Future<Output = Res>>>>;
#[derive(Default)]
struct Container {
map: HashMap<String, Handler>,
}
impl Container {
pub fn insert<F, Fut>(&mut self, f: F)
where
F: FnOnce(Param) -> Fut + 'static,
Fut: Future<Output = Res> + 'static,
{
self.map.insert("demo".into(), Arc::new(|p| Box::pin(f(p))));
}
}
fn main() {
let mut c = Container::default();
c.insert(demo_handler);
}
async fn demo_handler(_: Param) -> Res {
println!("ciao dall'italia");
Ok(())
}
but if i try to change the handler signature to accept &Param like so:
type Handler = Arc<dyn FnOnce(&Param) -> Pin<Box<dyn Future<Output = Res>>>>;
i get a mismatch type error on c.insert(demo_handler);
the error:
error[E0308]: mismatched types
--> src/proto.rs:26:5
|
26 | c.insert(demo_handler);
| ^^^^^^^^^^^^^^^^^^^^^^ one type is more general than the other
|
= note: expected opaque type `impl for<'a> Future<Output = Result<(), ()>>`
found opaque type `impl Future<Output = Result<(), ()>>`
= help: consider `await`ing on both `Future`s
= note: distinct uses of `impl Trait` result in different opaque types
note: the lifetime requirement is introduced here
--> src/proto.rs:17:30
|
17 | F: FnOnce(&Param) -> Fut + 'static,
| ^^^
i tried to introduce lifetimes but i can't get to the bottom of it