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

标签 rust lifetime

我有一个在 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
    }
}

Playpen

你得到错误 #1(除了阴影)的原因是你的特征限制 context 有返回类型的生命周期,而不是 self .要约束 self,您需要在特征本身上设置生命周期参数。

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

关于rust - 如何统一结构和特征之间的生命周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26953420/

相关文章:

generics - 如何编写采用本身是通用类型的通用函数?

rust - 如何在关联类型中指定生命周期参数?

visual-studio-code - 在 VSCode 中使用 Rust Cargo TOML 变量?

linked-list - 从单向链表中删除节点出现错误 "cannot move out of borrowed content"

rust - 在 Option<Rc<Struct>> 上调用 map 与在 Option<Rc<i32>> 上调用 map 的工作方式不同

rust - 如何将创建包含具有生命周期的 Cell 的结构的函数传递给另一个函数?

rust - 使用返回与一个参数具有相同生命周期的关联类型的函数定义特征

rust - 使用actix启动计划任务并进行 self 访问

闭包环境中的 Rust 生命周期

rust - 为什么需要使用加号运算符 (Iterator<Item = &Foo> + 'a) 为特征添加生命周期?