-
Notifications
You must be signed in to change notification settings - Fork 13k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
borrowed value does not live long enough in closure #76627
Comments
Minimized a bit: fn main() {
let c = |v| {};
for _ in 0..1 {
let s = ();
c(&s);
}
} |
Running below gives error: fn main() {
let c = |v| {};
x(c);
y(c);
for _ in 0..1 {
let s = ();
c(&s);
}
}
fn x<F>(_: F) where for<'a> F: FnMut(&'a ()) {}
fn y<'a, F>(_: F) where F: FnMut(&'a ()) {} gives: error[E0308]: mismatched types
--> src/main.rs:3:5
|
3 | x(c);
| ^ one type is more general than the other
|
= note: expected type `std::ops::FnOnce<(&'a (),)>`
found type `std::ops::FnOnce<(&(),)>` but running below gives no error: fn main() {
let c = |v: &()| {};
x(c);
y(c);
for _ in 0..1 {
let s = ();
c(&s);
}
}
fn x<F>(_: F) where for<'a> F: FnMut(&'a ()) {}
fn y<'a, F>(_: F) where F: FnMut(&'a ()) {} Seems like an inference problem. |
I think I ran into this issue a couple of hours ago. The following does not compile: fn main() {
struct Ref<'a>(&'a ());
let closure = |x| Ref(x);
while let Some(x) = None {
closure(&x);
}
} error[E0597]: `x` does not live long enough
--> src/main.rs:6:17
|
6 | closure(&x);
| ------- ^^ borrowed value does not live long enough
| |
| borrow later used here
7 | }
| - `x` dropped here while still borrowed However, change - while let Some(x) = None {
+ if let Some(x) = None {
closure(&x); However, duplicate the if let Some(x) = None {
closure(&x);
}
+
+ if let Some(x) = None {
+ closure(&x);
+ } error[E0597]: `x` does not live long enough
--> src/main.rs:6:17
|
6 | closure(&x);
| ^^ borrowed value does not live long enough
7 | }
| - `x` dropped here while still borrowed
...
10 | closure(&x);
| ------- borrow later used here You can fix either of the failing examples by adding a lifetime-polymorphic type annotation to the closure: - let closure = |x| Ref(x);
+ let closure: for<'a> fn(&'a ()) -> Ref<'a> = |x| Ref(x); or by manually inlining the closure: - closure(&x);
+ Ref(&x); |
How could this be a bug? I thought this is a result of closures capturing the running context. Captured reference cease before closure ceases, hence the error. Any thoughts? |
From Stackoverflow:
https://stackoverflow.com/questions/63856055/borrow-checker-complains-for-closure-inside-loop-if-type-not-provided-explicitly
I tried this code:
I expected to see this happen: Code compiles
Instead, this happened: Got below error:
But if I add explicit type to closure, code compiles
let c = |v: &str| f1(v);
Meta
rustc --version --verbose
:The text was updated successfully, but these errors were encountered: