How to use a closure as an argument to another closure?

The code is as follows:

fn main() {
  let arg = | | println!("closure");
  let call_twice = | c | { c(); c(); };
  call_twice(arg);
}

But the compiler cannot infer the correct type of argument c. Error message:

error: the type of this value must be known in this context

How can I tell the compiler that the type of an argument is a generic type that uses Fn?


Edit: if the argument type is an object, the code can be accepted by the compiler. But indirection is not needed, is it?

fn main() {
  let arg = | | println!("closure");
  let call_twice = | c :&Fn() | { c(); c(); };
  call_twice(&arg);
}

Thanks for your reply. But this is a type input problem that confuses me. Using Fncan make the compiler happy.

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);
}

Can I add syntax to support similar functions? Eg for<F> | c:F | where F:Fn() {c(); c();}.

+4
source share
1

Rust book , move , , , Rust Playground:

fn main() {
    let arg = Box::new(move || println!("closure"));
    let call_twice = |c: Box<Fn()>| { c(); c(); };
    call_twice(arg);
}

OP : . , , . , , , , c . , " Closure , , ". , , -, .

+3

Source: https://habr.com/ru/post/1623636/


All Articles