Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
990 views
in Technique[技术] by (71.8m points)

rust - Expected bound lifetime parameter, found concrete lifetime

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...