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

标签 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 引用书中指定“生命周期或标签”,这似乎只是一个用于所有意图和目的的标签。

是否有任何方法可以显式指定每个循环迭代的生命周期,或者显式写出编译器在第一个示例中省略的内容?

最佳答案

Is it possible to specify the lifetime of an iteration of a loop explicitly?

没有。这样的事情根本不需要。


您没有提供与原始问题相对应的 MCVE,因此不可能提供解决该问题的解决方案。我的直觉和你的评论“写出编译器省略的内容”告诉我你可能应该看看:

TL;博士:

fn g(a: &mut str, closure: impl for<'a, 'd> Fn(&'a mut str, &'d str) -> ())

关于loops - 是否可以明确指定循环迭代的生命周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53972440/

相关文章:

ruby - 包含 .each_line 的 ruby​​ 循环中的高级行号

java - 将嵌套 for 循环编写为 while

string - 如何写出非文字字符串?

rust - 如何在 Rust 中实现单一生产者、多个消费者 (SPMC) channel ?

testing - 如何解释 `cargo bench` 的输出?

rust - 从消耗值中计算出生命周期以供引用

generics - 生命周期子类型和泛型 : "lifetime parameter not allowed" error

lambda - 为什么我可以将对非静态局部变量的引用传递给具有“静态绑定(bind)”的函数?

python - 循环内的 INSERT 未按我的预期工作(Python 2.7)

javascript - 我如何绘制带有循环和点的完美倍数线螺旋?