繁体   English   中英

你如何结合生锈的生命?

[英]How do you combine lifetimes in 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 { 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)你如何结合一生? (即返回一个寿命至少为'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>

删除bar上的所有limetime参数,并使用来自impl'a lifetime参数。

impl<'a> Foo<'a> {
  fn bar(&'a self, other:&'a int) -> Foo<'a> {                  // '
    return Foo { value: Some(other), parent: Some(self) };
  }
}

'a将被编译器推断为所有引用有效的最小生命周期。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM