Allocating and deallocating memory

Deallocation happens in one of two ways, depending on whether the type is allocated on the stack or the heap. If it's on the stack, the type is deallocated when the stack frame itself ceases to exist. Each Rust stack frame comes into the world fully allocated but uninitialized and exits the world when its associated function exits. Heap allocated types are deallocated when the last valid binding moves out of scope, either through the natural flow of the program or by an explicit std::mem::drop being called by the programmer. The implementation of drop is as follows:

fn drop<T>(_x: T) { }

The value _x is moved into drop —meaning there are no other borrows of _x—and then immediately falls out of scope when ...

Get Hands-On Concurrency with Rust now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.