2014-11-16 48 views
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  } 

回答

3

你需要給自身特質一輩子參數:

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有壽命e返回類型,但不是self。要約束self,您需要在特徵本身上有一個生命週期參數。

您得到錯誤#2的原因很簡單:生命時間是類型系統的一部分,不能錯配。你寫的任何通用代碼都應該適用於所有特性的實現者 - 如果每個實現中的生命週期都有不同的約束,那麼這將不起作用。

+0

謝謝,我會給你一個鏡頭。我真的希望情況並非如此,因爲這意味着我必須更改100行代碼才能跟蹤現在的生命...... – Shepmaster

+0

@Shepmaster是的,在Rust中,如果你想要經常跟蹤生命週期避免複製。 – Manishearth

相關問題