The stack

Like most programming languages, Rust uses a stack to handle memory management for scopes. A stack is a simple data structure, also referred to as a Last In, First Out Queue or LIFO. Stacks support two operations: push, which stores a new value, and pop, which removes and returns the most recently stored value.

We can think of a stack as a pile of boxes. If we want to remove the stuff stored in the top box, we can just take it down and look inside. However, if we want to remove the stuff stored in one of the boxes underneath, we first have to remove the boxes above it. Here's a diagram of what I'm talking about, with access to the boxes underneath blocked by the ones above them:

When a Rust block expression starts, it makes a note of how tall the stack is and, when the block ends, it removes things from the stack until the stack is the same height as it was to begin with. In between, when the block needs to store a new value, it pushes that value onto the stack.

When a value is removed from the stack, the Rust compiler also makes sure to do any cleanup that is needed before discarding the value, including calling a custom cleanup function for the value if one is defined.

Most programming languages do this, but not exclusively. In Rust, even when a data value uses heap memory, it is represented on the stack and controlled by the rules of ownership. By following that simple procedure, it's easy for Rust to handle all of the record keeping and memory management for a program, efficiently and with no garbage collection required.

Garbage collection is a mechanism used in many programming languages to remove the burden of memory management from the programmer. It's even easier to use than Rust's method, but it does require time for the garbage collection mechanism to run, which can impact program performance. Rust's method is almost entirely deterministic at compile time: the Rust compiler knows when to allocate and deallocate memory without having to figure it out while the program runs.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.137.117