logoalt Hacker News

flohofwoe08/10/20252 repliesview on HN

You need to store the captured data somewhere if the lambda is called after the outer function returns. AFAIK C++ (or rather std::function) will heap-allocate if the capture size goes above some arbitrary limit (similar to small-string optimizations in std::string). Not sure how Rust handles this case, probably through some "I can't let you do that, Dave" restrictions ;)


Replies

steveklabnik08/10/2025

The trick is that “if”. Rust won’t ever automatically heap allocate, but if your closure does get returned to a place where the capture would be dangling, it will fail to compile. You can then choose to heap allocate it if you wish, or do something else instead.

Heap allocating them is fairly rare, because most usages are in things like combinators, which have no reason to enlarge their scope like that.

andrepd08/10/2025

But that's not a closure, a closure/lambda is not an std::function. It's its own type, basically syntactic sugar for a struct with the captures vars and operator().

Of course if you want to store it on a type-erased container like std::function then you may need to heap allocate. Rust's equivalent would be a Box<dyn Fn>.