我有一个在 trait 方法上指定生命周期的特征,并且我有一个包含也需要生命周期的值的结构。我想让结构实现特征,这意味着生命周期需要匹配。但是,我不确定如何表达。
struct Context<'d> {
name: &'d str,
}
struct Value<'d> {
name: &'d str,
}
trait Expression {
fn evaluate<'d>(&self, context: &Context<'d>) -> Value<'d>;
}
struct Constant<'d> {
value: Value<'d>,
}
尝试 1 - 指定方法的生命周期:
impl<'d> Expression for Constant<'d> {
fn evaluate<'d>(&self, _unused: &Context<'d>) -> Value<'d> {
self.value
}
}
这会导致 impl
的生命周期被隐藏,并且我会收到如下错误:
$ rustc x.rs
x.rs:18:5: 20:6 help: consider using an explicit lifetime parameter as shown: fn evaluate<'d>(&self, _unused: &Context<'d>) -> Value<'d>
x.rs:18 fn evaluate<'d>(&self, _unused: &Context<'d>) -> Value<'d> {
x.rs:19 self.value
x.rs:20 }
x.rs:19:9: 19:19 error: mismatched types: expected `Value<'d>`, found `Value<'d>` (lifetime mismatch)
x.rs:19 self.value
^~~~~~~~~~
尝试 2 - 未指定生命周期:
impl<'d> Expression for Constant<'d> {
fn evaluate(&self, _unused: &Context<'d>) -> Value<'d> {
self.value
}
}
这导致我实际上没有实现该方法:
$ rustc x.rs
x.rs:18:5: 20:6 error: method `evaluate` has an incompatible type for trait: expected concrete lifetime, found bound lifetime parameter 'd [E0053]
x.rs:18 fn evaluate(&self, _unused: &Context<'d>) -> Value<'d> {
x.rs:19 self.value
x.rs:20 }
x.rs:18:60: 20:6 note: expected concrete lifetime is the lifetime 'd as defined on the block at 18:59
x.rs:18 fn evaluate(&self, _unused: &Context<'d>) -> Value<'d> {
x.rs:19 self.value
x.rs:20 }
最佳答案
你需要给特征本身一个生命周期参数:
trait Expression<'d> {
fn evaluate(&self, context: &Context<'d>) -> Value<'d>;
}
impl<'d> Expression<'d> for Constant<'d> {
fn evaluate(&self, _unused: &Context<'d>) -> Value<'d> {
self.value
}
}
你得到错误 #1(除了阴影)的原因是你的特征限制 context
有返回类型的生命周期,而不是 self
.要约束 self
,您需要在特征本身上设置生命周期参数。
出现错误 #2 的原因很简单:生命周期是类型系统的一部分,不能不匹配。您编写的任何通用代码都应该适用于特征的所有实现者——如果生命周期在每个实现中的绑定(bind)不同,那将不起作用。
关于rust - 如何统一结构和特征之间的生命周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26953420/