预期的约束寿命参数,找到具体的寿命

Nat*_*Fox 12 rust

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

Request,Response和,Action是简化版本,以保持此示例最小.

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");
}
Run Code Online (Sandbox Code Playgroud)

铁锈游乐场

Chr*_*gan 12

你的特质函数定义是这样的:

fn handle<'a>(&self, req: Request, res: Response<'a>) -> Action<'a>;
Run Code Online (Sandbox Code Playgroud)

请注意,这'a是由调用者指定的,可以是任何内容,并且不一定以self任何方式绑定.

你的特质实现定义是这样的:

fn handle(&self, req: Request, res: Response<'a>) -> Action<'a>;
Run Code Online (Sandbox Code Playgroud)

'a调用者不在此处指定,而是绑定到您为其实现特征的类型.因此,特征实现与特征定义不匹配.

这是你需要的:

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

关键点是T界限的变化:for<'a> Fn(Request, Response<'a>) -> Action<'a>.这意味着:"给定一个任意的寿命参数'a,T必须满足Fn(Request, Response<'a>) -> Action<'a>; 或者," T必须,对所有人来说'a,满足Fn(Request, Response<'a>) -> Action<'a>.

  • "`for <`"在The Rust Book中出现0次,并且在编译器中使用(不包括测试)总共33次.难怪我以前没见过它.如果有人想知道他们,我能找到的唯一文件是[RFC](https://github.com/nikomatsakis/rfcs/blob/hrtb/active/0000-higher-ranked-trait-bounds.md). (5认同)
  • 是的,for &lt;&gt;几乎是我没有记录的最后一件事。 (2认同)