2
我有一個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>,
}
嘗試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 }
謝謝,我會給你一個鏡頭。我真的希望情況並非如此,因爲這意味着我必須更改100行代碼才能跟蹤現在的生命...... – Shepmaster
@Shepmaster是的,在Rust中,如果你想要經常跟蹤生命週期避免複製。 – Manishearth