Search code examples
rustclosuresheap-memorystack-memory

Are Rust closures stack-allocated or heap-allocated by default?


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").


Solution

  • 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: