这段代码:
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.
}
Run Code Online (Sandbox Code Playgroud)
无法编译错误:
<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 }
Run Code Online (Sandbox Code Playgroud)
(围栏:http://is.gd/vAvNFi)
这显然是一个人为的例子,但我偶尔也想这样做.
所以...
1)你如何结合一生?(即返回一个寿命至少为'a或'b的Foo,它的寿命更短)
2)有没有办法将测试写入资产生命周期编译失败?(例如,尝试编译以错误方式使用该函数的#[test],并以生命周期错误失败)
边界'c: 'a + 'b意味着'c至少与长度'a一样长'b.但是,在这种情况下,该Foo值对于恰好最短的'a和有效'b:一旦引用后面的数据超出范围,整个Foo必须无效.(这是说,数据的有效期为'c在有效工会的'a和'b.)
更具体地说,比方说'b = 'static,那'c: 'a + 'static意味着'c必须也是'static,所以返回值就是Foo<'static>.这显然是不对的,因为它将有限的'a self引用"升级"为永久持续的引用.
这里的正确行为是生命周期的交集:Foo只有在两个函数参数都有效时才有效.交集操作只是用相同的名称标记引用:
fn bar<'a>(&'a self, other: &'a int) -> Foo<'a>
Run Code Online (Sandbox Code Playgroud)