Expected bound lifetime parameter, found concrete lifetime

后端 未结 1 1610
滥情空心
滥情空心 2020-12-11 00:54

I can\'t figure out the lifetime parameters for this code. Everything I try usually results in a compiler error: \"Expected bound lifetime parameter \'a, found

相关标签:
1条回答
  • 2020-12-11 01:57

    Your trait function definition is this:

    fn handle<'a>(&self, req: Request, res: Response<'a>) -> Action<'a>;
    

    Note that 'a is specified by the caller and can be anything and is not necessarily tied to self in any way.

    Your trait implementation definition is this:

    fn handle(&self, req: Request, res: Response<'a>) -> Action<'a>;
    

    'a is not here specified by the caller, but is instead tied to the type you are implementing the trait for. Thus the trait implementation does not match the trait definition.

    Here is what you need:

    trait Handler: Send + Sync {
        fn handle<'a>(&self, req: Request, res: Response<'a>) -> Action<'a>;
    }
    
    impl<T> Handler for T
    where
        T: Send + Sync + for<'a> Fn(Request, Response<'a>) -> Action<'a>,
    {
        fn handle<'a>(&self, req: Request, res: Response<'a>) -> Action<'a> {
            (*self)(req, res)
        }
    }
    

    The key point is the change in the T bound: for<'a> Fn(Request, Response<'a>) -> Action<'a>. This means: “given an arbitrary lifetime parameter 'a, T must satisfy Fn(Request, Response<'a>) -> Action<'a>; or, “T must, for all 'a, satisfy Fn(Request, Response<'a>) -> Action<'a>.

    0 讨论(0)
提交回复
热议问题