Rust 你是如何结合铁锈的寿命的?
此代码:Rust 你是如何结合铁锈的寿命的?,rust,Rust,此代码: 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
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.
}
struct Foo,
家长:选项>
}
恳求{
fn棒{
返回Foo{value:Some(other),parent:Some(self)};
}
}
fn main(){
设e=100i;
{
设f=Foo{value:None,parent:None};
让g:Foo;
{
g=f.bar(和e);
}
//删除栏上的所有limetime参数
,改用impl
中的'a
寿命参数
impl<'a> Foo<'a> {
fn bar(&'a self, other:&'a int) -> Foo<'a> { // '
return Foo { value: Some(other), parent: Some(self) };
}
}
impl{
fn条(&'a self,other:&'a int)->Foo边界'c:'a+'b
意味着'c
至少与'a
和'b
一样长。然而,在这种情况下,Foo
值对'a
和'b
中最短的一个有效:一旦任一引用后面的数据超出范围,整个Foo
必须无效。(这意味着对'c
有效的数据在'a
和'b
的联合中有效)
更具体地说,假设'b='static
,那么'c:'a+'static
意味着'c
也必须是'static
,因此返回值应该是Foo
我已经编辑了我的答案,将“最大”(联合)替换为“最小”(交叉)。但是,既然bar是这里的一种方法,那么在方法上省略'a
生命周期参数,并使用impl
中的'a
不是更好吗?我知道它在实现特征时会导致错误(生存期参数必须与trait中定义的参数匹配),但这只是一个简单的impl
,所以这两个选项都可以使用。@FrancisGagné:至少我同意你的看法。函数似乎不需要任何新的生存期参数。(顺便说一句,帖子中的代码没有编译,也与playpen链接中的代码不匹配。)@我的坏毛病,现在修好了。
impl<'a> Foo<'a> {
fn bar(&'a self, other:&'a int) -> Foo<'a> { // '
return Foo { value: Some(other), parent: Some(self) };
}
}
fn bar<'a>(&'a self, other: &'a int) -> Foo<'a>