The heap is an area of program memory used for allocations accessed through pointers. It is not the heap data structure used for priority queues. Picture a warehouse: space is made available as data arrives and can be made available again when that data is no longer needed. section 6.3.2
The stack is generally faster, so prefer it when it fits the job. Stack placement requires the compiler to know a type’s size at compile time. The heap accommodates data whose size can change, such as String and Vec<T>. A slice, [T], has no compile-time length; it refers to elements within an array. section 6.3 section 6.3.2
Listing 6.6 Creating variables on the heap
fn main() {
let a: i32 = 40; #1
let b: Box<i32> = Box::new(60); #2
println!("{} + {} = {}", a, b, a + *b); #3
}
Compare the ordinary integer a with b, created by Box::new. The expression a + *b uses * to access the boxed value for arithmetic. section 6.3.2
Listing 6.7 Allocating and deallocating memory on the heap via Box<T>
1 use std::mem::drop; #1
2
3 fn main() {
4 let a = Box::new(1); #2
5 let b = Box::new(1); #2
6 let c = Box::new(1); #2
7
8 let result1 = *a + *b + *c; #3
9
10 drop(a); #4
11 let d = Box::new(1);
12 let result2 = *b + *c + *d;
13
14 println!("{} {}", result1, result2);
15 }
Follow several Box allocations, the explicit drop(a), and a subsequent allocation. This makes the allocation-and-release sequence visible without relying on a larger program. section 6.3.2
Heap placement is a choice about access and cost, not a requirement that a value itself change size: Box<i32> places a fixed-size integer on the heap. Other pointer types offer different ways to share or manage values. A fuller account of what the heap is depends on virtual memory. section 1.6.3 section 6.3.2






