Rust usually lets data structures handle allocation and deallocation. When memory overhead or allocation behavior matters, start by identifying whether a value uses the heap or the stack; Rust types often make that distinction visible. section 5.0 section 4.1.1
Use the storage requirements to guide the choice:
- The stack is thread-local and tied to function scope. It suits values whose size is known without dynamic allocation. section 5.1
- The heap supports dynamic allocation, including resizable structures and values sized at run time. An allocator manages that memory; memory-constrained systems may avoid heap use. section 5.1
- String owns heap-allocated string data; a borrowed &str may refer to heap-allocated data. Do not infer where referenced data lives solely from the reference. section 4.1.1
Listing 5.1 Code showing heap-allocated values
let heap_integer = Box::new(1);
let heap_integer_vec = vec![0; 100];
let heap_string = String::from("heap string"); #1
Compare Box::new, vec!, and String::from as concrete ways to create heap-allocated values. section 5.1
Allocation choices can become more specialized through ownership, reference-counted pointers, smart pointers, or custom allocators. Reach for that complexity when ordinary data structures do not meet the application’s needs. section 5.0


