[英]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". 我尝试的所有内容通常会导致编译器错误:“预期的绑定生命周期参数
'a
,找到具体的生命周期”或类似“考虑使用显示的显式生命周期参数”(并且显示的示例没有帮助)或“方法不兼容”特质“。
Request
, Response
, and Action
are simplified versions to keep this example minimal. 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");
}
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. 请注意,
'a
由调用者指定,可以是任何内容,并且不一定与self
绑定。
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. 'a
不在此处由调用者指定,而是与您实现该特征的类型相关联。 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>
. 关键点是
T
界限的变化: 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>
; 这意味着:“给定一个任意的生命周期参数
'a
, T
必须满足Fn(Request, Response<'a>) -> Action<'a>
; or, “ T
must, for all 'a
, satisfy Fn(Request, Response<'a>) -> Action<'a>
. 或者,“
T
必须,对于所有'a
,满足Fn(Request, Response<'a>) -> Action<'a>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.