预期的绑定生命周期参数,找到了具体的生命周期 [英] Expected bound lifetime parameter, found concrete lifetime

查看:60
本文介绍了预期的绑定生命周期参数,找到了具体的生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚这段代码的生命周期参数.我尝试的一切通常都会导致编译器错误:预期的绑定生命周期参数 'a,找到具体的生命周期"或类似考虑使用如图所示的显式生命周期参数"之类的东西(并且显示的示例没有帮助)或方法与特征不兼容".

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

RequestResponseAction 是简化版本,以保持此示例最小化.

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

推荐答案

你的 trait 函数定义是这样的:

Your trait function definition is this:

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

请注意,'a 由调用者指定,可以是任何内容,不一定以任何方式与 self 相关联.

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 在这里不是由调用者指定的,而是与您正在为其实现特征的类型相关联.因此特征实现与特征定义不匹配.

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

这是您需要的:

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)
    }
}

关键是T边界的变化:for<'a>Fn(请求,响应<'a>)->动作<'a>.这意味着:给定一个任意生命周期参数 'aT 必须满足 Fn(Request, Response<'a>) ->动作<'a>;或者,对于所有 'aT 必须满足 Fn(Request, Response<'a>) ->操作<'a>.

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

这篇关于预期的绑定生命周期参数,找到了具体的生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆