back

by raphlinus·8y ago·view on hn ↗
Closures are, but functions defined using "fn" syntax cannot capture from the environment. This is a useful feature, and I can see why people would want it, but it was considered ultimately not consistent with Rust's aims to be excellent at the low level. See [1] for more discussion of the tradeoffs and why Rust chose not to include the feature.

[1] https://users.rust-lang.org/t/inner-functions-not-closed-ove...

1 comments
I believe the story here is the same in C++. Functions are just a pointer to some compiled code. Closures are an object that represents all the captured variables, in addition to the code. That object has a size, and a destructor, and the variables it's holding might have pointer lifetimes that you need to worry about. In Rust, quite a lot of type system machinery gets invoked when you create a closure, to make sure it doesn't outlive any of the references it's closing over.
Yes, it's similar to C++. A Rust `fn()` type is similar to a C++ `(*foo)()` type and at the low level is just a pointer to code. A Rust `Fn` trait object (of which there are several variants) is roughly similar to a C++ std::function and is "fat" in that it can contain data as well as code. Most higher level languages don't make the distinction, buying conceptual simplicity at the cost of potential optimizations when a simple code pointer will do.