是否可以明确指定循环迭代的生命周期?

时间:2018-12-29 18:51:23

标签: loops rust lifetime

下面的代码利用生存期省略进行编译:

fn g(a: &mut str, closure: impl Fn(&mut str, &str) -> ()) {
    let data = vec![];
    for d in data.iter() {
        closure(a, d);
    }
}

但是,假设我需要在闭包中明确指定变量的生存期(在我的情况下,除非我这样做,否则调用站点是模棱两可的)。如果我显式添加生存期,则编译器会抱怨a是在闭包的先前迭代中可变地借用的。

fn g<'b, 'd>(a: &'b mut str, closure: impl Fn(&'d mut str, &str) -> ()) {
    let data: Vec<&str> = vec![];
    'd: for d in data.iter() {
        closure(a, d);
    }
}
warning: label name `'d` shadows a lifetime name that is already in scope
 --> src/lib.rs:3:5
  |
1 | fn g<'b, 'd>(a: &'b mut str, closure: impl Fn(&'d mut str, &str) -> ()) {
  |          -- first declared here
2 |     let data: Vec<&str> = vec![];
3 |     'd: for d in data.iter() {
  |     ^^ lifetime 'd already in scope

error[E0312]: lifetime of reference outlives lifetime of borrowed content...
 --> src/lib.rs:4:17
  |
4 |         closure(a, d);
  |                 ^
  |
note: ...the reference is valid for the lifetime 'd as defined on the function body at 1:10...
 --> src/lib.rs:1:10
  |
1 | fn g<'b, 'd>(a: &'b mut str, closure: impl Fn(&'d mut str, &str) -> ()) {
  |          ^^
note: ...but the borrowed content is only valid for the lifetime 'b as defined on the function body at 1:6
 --> src/lib.rs:1:6
  |
1 | fn g<'b, 'd>(a: &'b mut str, closure: impl Fn(&'d mut str, &str) -> ()) {
  |      ^^

我认为这是因为编译器不会猜测我只打算让'd持续到循环的每次迭代。我搜索了一种引用生命周期的方法,但是我发现我只能在Rust参考书中指定一个“生命周期或标签”,这似乎只是所有意图和目的的标签。

是否有任何方法可以明确指定每个循环迭代的生存期,或者以其他方式明确指出第一个示例中编译器已删除的内容?

1 个答案:

答案 0 :(得分:4)

  

是否可以明确指定循环迭代的生存期?

不。根本不需要这样的东西。


您没有提供与您的原始问题相对应的MCVE,因此无法提供能够解决该问题的解决方案。我的直觉能力和您的注释“写出编译器已忽略的内容”告诉我,您可能应该看看:

TL; DR:

<View onLayout={console.log("Hello")}>
    <Text>Hello</Text>
</View>