This question was also posted on stackoverflow.
Question
The code is as follows:
fn main() {
let arg = | | println!("closure");
let call_twice = | c | { c(); c(); };
call_twice(arg);
}
But the compiler can’t inference the correct type of the argument c
. Error message:
error: the type of this value must be known in this context
The compiler can not infer the type of the argument is an anonymous type which impls Fn
.
Alternative 1
If the argument type is trait object, the code can be accepted by compiler. But the indirection isn’t necessary, since the closure is not escape.
fn main() {
let arg = | | println!("closure");
let call_twice = | c :&Fn() | { c(); c(); };
call_twice(&arg);
}
Alternative 2
Using an fn
can make the compiler happy, and no indirection involved. Type inference works well, but it can’t capture variables.
fn main() {
let arg = | | println!("closure");
// now compiler knows the argument `c` is a closure
fn call_twice<F>(c: F) where F:Fn() {c(); c();}
call_twice(arg);
}
My Suggestion
Can we add a syntax to support similar functionality? Such as
for<F> | c:F | where F:Fn() {c(); c();}
Thanks!