Rust 如何统一结构和特征之间的生命周期?

Rust 如何统一结构和特征之间的生命周期?,rust,lifetime,Rust,Lifetime,我有一个trait,它在trait方法中指定了一个生存期,我有一个结构,它包含一个值,该值也需要一个生存期。我想让结构实现trait,这意味着生命周期需要匹配。然而,我不知道该如何表达 struct Context<'d> { name: &'d str, } struct Value<'d> { name: &'d str, } trait Expression { fn evaluate<'d>(&sel

我有一个trait,它在trait方法中指定了一个生存期,我有一个结构,它包含一个值,该值也需要一个生存期。我想让结构实现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>,
}
尝试2-未指定生存期:

impl<'d> Expression for Constant<'d> {
    fn evaluate(&self, _unused: &Context<'d>) -> Value<'d> {
        self.value
    }
}
impl{
fn评估(&self,_未使用:&Context){
自我价值
}
}
这导致我没有实际实现该方法:

$ 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     }
$rustc x.rs
x、 rs:18:5:20:6错误:方法“evaluate”具有与trait不兼容的类型:预期混凝土寿命,已找到绑定寿命参数“d[E0053]
x、 rs:18 fn评估和自我、未使用和上下文{
x、 rs:19自我价值观
x、 rs:20}
x、 rs:18:60:20:6注:预期混凝土寿命是18:59时砌块上定义的寿命
x、 rs:18 fn评估和自我、未使用和上下文{
x、 rs:19自我价值观
x、 rs:20}

您需要为trait本身提供一个终生参数:

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
    }
}
trait表达式)->值表达式{
fn评估(&self,_未使用:&Context){
自我价值
}
}

得到错误#1(除了阴影)的原因是您的trait正在约束
上下文
以获得返回类型的生存期,而不是
self
。要约束
self
,您需要在trait本身上有一个生存期参数


出现错误#2的原因很简单:生命周期是类型系统的一部分,不能不匹配。您编写的任何通用代码都应该适用于trait的所有实现者——如果每个实现中的生命周期绑定不同,那就不起作用了。

谢谢,我来试一试。我真的希望情况并非如此这意味着我现在必须改变100行代码来跟踪生命周期…@Shepmaster是的,在Rust中,如果你想避免复制,你必须经常跟踪生命周期。
$ 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
    }
}