Lifetimes of the method implementation for async_trait is not matching with the trait declaration

What I am trying??

Writing a common muxer (router to forward the requests) to the callback classes registered with URI. This is a wrapper lib written on top of the hyper server lib.

What my code looks like??
httpserver is a singleton and maintains a callback map with uri as key and the callback object reference as value. The callback object needs to implement trait with function "httpcallback".

trait definition

#[async_trait]
pub trait HttpCallbackFn: Sync + Send {
    // fn http_callback(&self, req: Request<Body>) -> Result<Response<Body>, Infallible>;
    fn http_callback(&self, req: Request<Body>) -> Result<Response<Body>, Infallible>;
}

implementation

#[async_trait]
impl HttpCallbackFn for TestA {
    //http callback function
    async fn http_callback(&self, req: Request<Body>) -> Result<Response<Body>, Infallible> {
        let response = Response::builder()
            .status(StatusCode::OK)
            .body(Body::from("TestA request handled"))
            .unwrap();
        Ok(response)
    }

Issue:
Rust compiler is throwing following error while implementing HttpCallbackFn trait for the TestA

error[E0195]: lifetime parameters or bounds on method `http_callback` do not match the trait declaration

    |
503 |     async fn http_callback(&self, req: Request<Body>) -> Result<Response<Body>, Infallible> {
    |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lifetimes do not match method in trait

One observation, The same implementation worked for the class defined in main thread but when the TestA is defined in some lib and the TestA spawns a thread.

Also, tried removing the Request and Response arguments for the http_callback function definition except &self and still the issue persists.

Any kind of help is appreciated. Thanks!!

1 Like

Did you apply #[async_trait] to the trait declaration as well as the implementation? You need to do that.

Yes, I did. I will update the above post, I missed it while copying form my editor.

You need to have async in the trait fn as well.

pub trait HttpCallbackFn: Sync + Send {
    async fn http_callback(&self, req: Request<Body>) -> Result<Response<Body>, Infallible>;
}