我无法弄清楚这段代码的生命周期参数 . 我尝试的所有内容通常会导致编译器错误:“预期绑定生存期参数 'a
,发现具体生命周期" or something like "考虑使用显式生命周期参数,如图所示" (and the example shown doesn't help) or "方法与特征不兼容” .
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");
}
1 回答
你的特质函数定义是这样的:
请注意,
'a
由调用者指定,可以是任何内容,并且不一定以任何方式绑定到self
.你的特质实现定义是这样的:
'a
在此处未由调用者指定,而是与您为其实现特征的类型相关联 . 因此,特征实现与特征定义不匹配 .这是你需要的:
关键点是
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>
.