3 ms·
The term "closure" is used in Rust for that syntax, regardless of whether it actually closes over its environment. You need some term for the syntax, and closur
by lambda 11y ago
The term "closure" is used in Rust for that syntax, regardless of whether it actually closes over its environment. You need some term for the syntax, and closure is used even if it doesn't necessarily close over anything; because much of the time, you do use it because you want it to close over its environment.
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/p9Kd9y http://is.gd/p9Kd9y
- kazagistar 11y agoHow about memory size? A pointer to a function is just a single pointer to the called code, while a pointer to a closure has at least 2 pieces of data (pointer to code + closed over data or reference) which seems incompatible.
- pcwalton 11y agoGenerics are monomorphized, so this isn't an issue.