17

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 concrete lifetime" or something like "consider using an explicit lifetime parameter as shown" (and the example shown doesn't help) or "method not compatible with trait".

Request, Response, and Action are simplified versions to keep this example minimal.

struct Request {
    data: String,
}
struct Response<'a> {
    data: &'a str,
}

pub enum Action<'a> {
    Next(Response<'a>),
    Done,
}

pub trait Handler: Send + Sync {
    fn handle<'a>(&self, req: Request, res: Response<'a>) -> Action<'a>;
}

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

fn main() {
    println!("running");
}

Rust Playground

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Nathan Fox
  • 582
  • 6
  • 16

1 Answers1

15

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>.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Chris Morgan
  • 86,207
  • 24
  • 208
  • 215
  • 9
    "`for<`" appears 0 times in The Rust Book, and is used (excluding tests) a grand total of 33 times in the compiler. No wonder I haven't seen it before. If anyone's wondering about them, the only documentation I could find is [the RFC](https://github.com/nikomatsakis/rfcs/blob/hrtb/active/0000-higher-ranked-trait-bounds.md). – Veedrac Aug 25 '15 at 14:20
  • Oh, the RFC points out that parenthesis notation will elide it all anyway: http://is.gd/fdy0M7. – Veedrac Aug 25 '15 at 14:25
  • 3
    Yup, for<> is pretty much the last thing I haven't documented. – Steve Klabnik Aug 25 '15 at 14:27