-
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
(expected closure, found a different closure) [E0308] #24036
Comments
The error is a bit confusing if you're not familiar with closures. Check out the chapters on Closures and Static and Dynamic Dispatch in the book to understand the semantics and performance tradeoffs. Currently in Rust, no two closures, even if identical, have the same type. Closures are essentially anonymous structs (containing the environment they close over) expanded at compile time, and made to impl the Fn* family of traits. In your code, producing a bare closure from a match arm that could produce other closures is not possible. You must use trait objects. The easiest approach would probably be to just box each closure, and coerce it into a trait object with a type annotation. use std::env;
fn main() {
let args: Vec<_> = env::args().collect();
let op: Box<Fn(i32) -> i32> = match &args[1][..] {
"foo" => Box::new(|c: i32| c + 1),
"bar" => Box::new(|c: i32| c + 1),
"baz" => Box::new(|c: i32| c - 1),
"other" => Box::new(|c: i32| c - 1),
_ => return,
};
println!("{:?}", op(11));
} There may be other ways to accomplish what you want. And if you aren't closing over your environment, just use function pointers. use std::env;
fn first_thing(c: i32) -> i32 {
c + 1
}
fn second_thing(c: i32) -> i32 {
c - 1
}
fn main() {
let args: Vec<_> = env::args().collect();
let op: fn(i32) -> i32 = match &args[1][..] {
"foo" => first_thing,
"bar" => first_thing,
"baz" => second_thing,
"other" => second_thing,
_ => return,
};
println!("{:?}", op(11));
} Or if your situation ultimately allows for it, use generics in some way. |
Sorry, I forgot to mention that this is a regression from about a week ago when https://github.com/richo/karma-rs/blob/master/src/main.rs#L49-L55 built
|
Closures in rust used to be "boxed" so they acted similar to my first example solution. |
different closures fail typechecking. See rust-lang#24036
Great fix, and thanks for the explaination! |
…pnkfelix Also fixed bug calling .note() instead of .help() See rust-lang#24036
Also fixed bug calling .note() instead of .help() See #24036
If you're satisfied the issue can be closed now. |
Thanks! |
playpen
The error here is extremely unclear to me:
Not sure if actually a bug in rust (That's my intuition, this looks very valid to me) or just an issue where the error message is incredibly unhelpful.
The text was updated successfully, but these errors were encountered: