Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 592
TJB Avatar asked Feb 15 '21 15:02

TJB


People also ask

Does Rust use heap?

Usually Rust avoid allocating anything on the heap. Never will the compiler do an implicit allocation on the heap, but may library functions can do it for you. At least anything that is dynamically sized (eg. Vec<T> ) will need something on the heap under the hood, for the rest, the documentation should hint it.

How does Rust allocate memory?

Rust doesn't have a defined memory model in the language specifications as of now and the memory structure is quite straightforward. Each Rust program process is allocated some virtual memory by the Operating System(OS), this is the total memory that the process has access to.

What is a closure in Rust?

Rust's closures are anonymous functions you can save in a variable or pass as arguments to other functions. You can create the closure in one place and then call the closure elsewhere to evaluate it in a different context. Unlike functions, closures can capture values from the scope in which they're defined.

Is heap or stack faster?

The stack is faster because the access pattern makes it trivial to allocate and deallocate memory from it (a pointer/integer is simply incremented or decremented), while the heap has much more complex bookkeeping involved in an allocation or free.


1 Answers

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:

  • How do Rust closures work and how does it execute a closure?
like image 149
Shepmaster Avatar answered Sep 20 '22 12:09

Shepmaster