以下代码利用生命周期省略进行编译:
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,因此不可能提供解决该问题的解决方案。我的直觉和你的评论“写出编译器省略的内容”告诉我你可能应该看看:
- How do I bound a generic type with a trait that requires a lifetime parameter if I create the reference inside the function?
- How does for<> syntax differ from a regular lifetime bound?
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/