Hi,
I am some what new to Rust and after looking at some opensource code, my understanding of implementing callbacks in Rust is to write a wrapper struct that holds function pointers (not sure if this is the suggested way of writing generic callbacks in Rust). so I am trying to do the same in my test project where I am trying to implement message router for incoming http requests and running into following issue.
Defined HttpHandler that saves the callback function pointer/closure
struct HttpHandler<F>
where
F: FnMut(
Request<Body>,
) -> Pin<Box<dyn Future<Output = Result<Response<Body>, Infallible>> + Send>>
+ Send,
{
handler: F,
}
impl<F> HttpHandler<F>
where
F: FnMut(
Request<Body>,
) -> Pin<Box<dyn Future<Output = Result<Response<Body>, Infallible>> + Send>>
+ Send,
{
fn new(handler: F) -> Self {
Self { handler }
}
async fn handle(&mut self, req: Request<Body>) -> Result<Response<Body>, Infallible> {
(self.handler)(req).await
}
}
Now, challenge is how to define a HashMap that store values of type HttpHandler??
I tried some thing like below but it is failing
callback_map: Arc<RwLock<HashMap<uri: String, HttpHandler<dyn FnMut(Request<Body>) -> Pin<Box<dyn Future<Output = Result<Response<Body>, Infallible>> + Send>> + Send>>>>>,
Error
error[E0277]: the size for values of type `(dyn FnMut(Request<Body>) -> Pin<Box<(dyn Future<Output = Result<Response<Body>, Infallible>> + Send + 'static)>> + Send + 'static)` cannot be known at compilation time
--> src/http_server_mux.rs:55:19
|
55 | ...p: Arc<RwLock<HashMap<String, HttpHandler<dyn FnMut(Request<Body>) -> Pin<Box<dyn Future<Output = Result<Response<Body>, Infallible>> + Send>> + Send>>>...
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `(dyn FnMut(Request<Body>) -> Pin<Box<(dyn Future<Output = Result<Response<Body>, Infallible>> + Send + 'static)>> + Send + 'static)`
note: required by a bound in `HttpHandler`
--> src/http_server_mux.rs:227:20
|
227 | struct HttpHandler<F>
| ^ required by this bound in `HttpHandler`
help: you could relax the implicit `Sized` bound on `F` if it were used through indirection like `&F` or `Box<F>`
--> src/http_server_mux.rs:227:20
|
227 | struct HttpHandler<F>
| ^ this could be changed to `F: ?Sized`...
...
234 | handler: F,
| - ...if indirection were used here: `Box<F>`
I am not clear why the compiler is returning size error?? I tried changing &dyn FnMut but it is throwing some different errors.
Wondering what's the write way to solve the above requirement?? Appreciate any kind of help or pointers
Thanks!!