And, you can pass a pointer to a function just fine:
fn call_twice<F>(f: F) where F: Fn() {
f();
f();
}
fn hello() {
println!("Hello");
}
fn main() {
call_twice(|| println!("Hi!"));
call_twice(hello);
let x = 5;
call_twice(|| println!("{}", x));
}
And all of this optimizes down just fine; if the environment being closed over is empty, it will just be an anonymous function with no extra overhead. Heck, if you try it out yourself on the playpen in release mode, and take a look at the asm, all of these just get inlined right into main: http://is.gd/p9Kd9yBy the way, function pointers have been able to be passed directly where closures, both the new and old forms, are expected since at least 0.13.
Actually, you can.
fn perr(e: &str) {
println!("There was an error :(, {}", e)
}
fn main() {
Err("ERROR").unwrap_or_else(perr);
}
The above code works, and can be run here: http://is.gd/2RCmG9Post "unboxed closures", closures are now stored on the stack (thus they usually optimize away; for example if you use an iterator with a bunch of adapters like filter/map it will optimize down to a for loop). Each closure has a unique anonymous type (you can box them if you want them to have the same type), and all closures implement one or more of the Fn* traits, as do function pointers. So arguments can be generic over all callables, and you can pass in a closure or a function or your own custom callable.
Also, functions could coerce to either of the closure types, and hence be passed straight to functions expecting them.
Huh, I recall this not working. Perhaps I made a mistake then.
> closures were pointers into the stack
Ah, the type erasure was through &mut. TIL; I always thought it was Box only.
fn main() {
Err("ERROR").unwrap_or_else(perr);
}gross.
It does. Rust closures translate to a stack struct containing the capture and a method call on that struct. In this case, the struct is zero-sized, so it doesn't exist, so it's just a function call. Additionally, unwrap_or_else will probably be monomorphised and then inlined, so there will be no call at all.
"closure" is just the term for the syntax.
> You can't pass a pointer to a function.
Sure you can.
fn main() {
Ok(1).unwrap_or_else(inc);
}
fn inc(x: u8) -> u8 {
x+1
}
Both functions and closures implement the Fn* traitsMy (limited) understanding is that all bindings closed over by a closure are represented as anonymous struct passed to the function, if nothing is closed over that will be a unit struct which will of course be optimized to nothing.
Rust is very good at optimizing away closures to have as little overhead as is possible for the semantics they describe.
You'd like for this to optimize down to a function call, without saving any state from the outer scope. Don't know if Rust does this yet.