There are certain cases where you can pass a closure as a function pointer. This works:
fn main() {
let x = || {
let a = String::from("abc");
println!("{}", a);
};
fn wrap(c: fn()) {
c()
}
wrap(x);
}
The important difference is that the closure is not allowed to capture anything from its environment. That means that we had to prevent the String
from crossing the closure boundary.
Any closure that doesn't capture environment can be trivially rewritten as a anonymous standalone function and then converted into a function pointer.
Once you add an environment, it is no longer convertible and everything from the existing answer applies.
Note that stating -> ()
is non-idiomatic as that's the default if nothing is specified.
See also:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…