-
Notifications
You must be signed in to change notification settings - Fork 12.9k
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
Confusing compiler error for function taking closure returning reference #91966
Comments
fn unclear_compiler_error<'a>(f: &dyn Fn(&'a i32) -> Option<&i32>) -> i32 {
242
} Specifying the lifetime also makes it compile fine, so I think you're right that it seems to be a lifetime thing. |
Here's as minimal as I could get it (play): fn func(_: &dyn Fn(&i32) -> &i32) {}
fn main() {
let f = |_: &i32| &42;
func(&f);
}
But it gets weirder......If you pass the closure inline, it works: fn func(_: &dyn Fn(&i32) -> &i32) {}
fn main() {
func(&|_: &i32| &42);
} But if you make it reference a previously declared variable, it doesn't, and you get a different error message: fn func(_: &dyn Fn(&i32) -> &i32) {}
fn main() {
let x = 42;
func(&|_: &i32| &x);
}
You could try changing the function parameter from fn func(_: impl Fn(&i32) -> &i32) {}
fn main() {
let x = 42;
func(|_: &i32| &x);
}
But if you move the closure out of line again, you unlock a brand new message! fn func(_: impl Fn(&i32) -> &i32) {}
fn main() {
let x = 42;
let f = |_: &i32| &x;
func(f);
}
If you make the closure return the input directly, you get a little more information: fn func(_: impl Fn(&i32) -> &i32) {}
fn main() {
let f = |i: &i32| i;
func(f);
}
And if you move that closure inline..... IT WORKS?! fn func1(_: impl Fn(&i32) -> &i32) {}
fn func2(_: &impl Fn(&i32) -> &i32) {}
fn func3(_: &dyn Fn(&i32) -> &i32) {}
fn main() {
func1(|i: &i32| i);
func2(&|i: &i32| i);
func3(&|i: &i32| i);
} This is pretty wacky. @rustbot label +A-diagnostics +D-confusing +D-terse +T-compiler +A-lifetimes +A-closures |
Related: this code: fn main() {
let _closure = |s: &bool| s;
} produces the following error:
|
Compiling the following code:
Gives the following output:
But I think the actual issue is with lifetimes, changing to
Option<i32>
makes it compile.The text was updated successfully, but these errors were encountered: