默认情况下,Rust 闭包是堆栈分配的还是堆分配的?

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

我知道 Rust 默认在栈上分配,但是论文 Ownership is Theft 说 Rust 闭包通常是动态分配的(我认为这意味着“在堆上”)。

它们默认位于堆栈中。这可以通过显示在没有分配器的环境中允许闭包来证明,例如在 libcore 中。来自 core::Option::map:

pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U>

作为:

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.

另请参阅: