此代碼:你如何結合生鏽的生活?
struct Foo<'a> {
value: Option<&'a int>,
parent: Option<&'a Foo<'a>>
}
impl<'a> Foo<'a> {
fn bar<'a, 'b, 'c: 'a + 'b>(&'a self, other:&'b int) -> Foo<'c> {
return Foo { value: Some(other), parent: Some(self) };
}
}
fn main() {
let e = 100i;
{
let f = Foo { value: None, parent: None };
let g:Foo;
{
g = f.bar(&e);
}
// <--- g should be valid here
}
// 'a of f is now expired, so g should not be valid here.
let f2 = Foo { value: None, parent: None };
{
let e2 = 100i;
let g:Foo;
{
g = f2.bar(&e2);
}
// <--- g should be valid here
}
// 'b of e2 is now expired, so g should not be valid here.
}
失敗,錯誤編譯:
<anon>:8:30: 8:35 error: cannot infer an appropriate lifetime due to conflicting requirements
<anon>:8 return Foo { value: Some(other), parent: Some(self) };
^~~~~
<anon>:7:3: 9:4 note: consider using an explicit lifetime parameter as shown: fn bar<'a, 'b>(&'a self, other: &'b int) -> Foo<'b>
<anon>:7 fn bar<'a, 'b, 'c: 'a + 'b>(&'a self, other:&'b int) -> Foo<'c> {
<anon>:8 return Foo { value: Some(other), parent: Some(self) };
<anon>:9 }
(圍欄:http://is.gd/vAvNFi)
這顯然是一個人爲的例子,但它是我想做的事偶爾。
所以...
1)你如何結合生命期? (即返回一個Foo,它的壽命至少爲'a或'b,這個更短)
2)是否有某種方法來編寫測試資產壽命編譯失敗? (如嘗試編譯#[測試]使用在錯誤的道路的功能和失敗,一生錯誤)
(順便說一句,在後的代碼不編譯,並在圍欄鏈接的代碼不匹配。)@dbaupp我的壞 – huon 2014-09-05 07:55:18
。現在修復。 – Doug 2014-09-05 08:33:03