I'm aware that Rust allocates on the stack by default, but the paper Ownership is Theft says that Rust closures are typically allocated dynamically (which I took to mean "on the heap").
Are Rust closures stack-allocated or heap-allocated by default?
Asked Answered
They are located on the stack by default. This can be proven by showing that closures are allowed in environments where there is no allocator, such as in libcore. From core::Option::map
:
pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U>
As trentcl notes:
If you're interested in the history, the release notes for 1.0.0-alpha say:
Closures have been completely redesigned to be implemented in terms of traits, can now be used as generic type bounds and thus monomorphized and inlined, or via an opaque pointer (boxed) as in the old system. The new system is often referred to as 'unboxed' closures.
See also:
Thank you for the quick answer! Do you have any links to Rust documentation which says as much? (I'm writing a paper for University coursework.) –
Tanhya
Thank you for the additional example as proof! –
Tanhya
© 2022 - 2024 — McMap. All rights reserved.
Box<dyn Fn...>
) When you're reading research it's often essential to keep the date in mind. – Kozlowski