|
|
|
|
|
by duped
1119 days ago
|
|
If you want to do anything with the closure it gets a little tricker, for example if you did something naive like fn fn_that_takes_closure (f: fn (i32, 3i2) -> i32) { ... }
let x = |a, b| a + b;
fn_that_takes_closure(x);
That would not compile, because `x` does not have the type `fn (i32, i32) -> i32` (that's reserved for "normal" functions). Every closure in Rust has a unique anonymous type, which means if you want to do anything with them besides calling them, you need to understand `Fn`, `FnOnce`, and `FnMut` traits and/or `dyn` trait objects. To write that above you'd need to do something like this: fn fn_that_takes_closure<F> (f: F)
where
F: Fn(i32, i32) -> i32
|
|
It does compile.
> because `x` does not have the type `fn (i32, i32) -> i32` (that's reserved for "normal" functions).
Closures can cast to function pointers just fine as long as they don't capture anything.