Skip to content

Jargon #1 - Stack vs heap

Course: Rust Bootcamp - chapter 12

Stack vs. Heap Allocation

Rust has clear rules about stack and heap data management:

  • Stack: Fast allocation and deallocation. Rust uses the stack for most primitive data types and for data where the size is known at compile time (eg: numbers).
  • Heap: Used for data that can grow at runtime, such as vectors or strings.

Numbers - i32, i64, f64 …

Booleans - true, false

Fixed sized arrays (we’ll come to this later)

Strings

Vectors (we’ll come to this later)

Hello world with numbers

Hello world with functions

Hello world with strings

fn main() {
stack_fn(); // Call the function that uses stack memory
heap_fn(); // Call the function that uses heap memory
update_string(); // Call the function that changes size of variable at runtime
}
fn stack_fn() {
// Declare a few integers on the stack
let a = 10;
let b = 20;
let c = a + b;
println!("Stack function: The sum of {} and {} is {}", a, b, c);
}
fn heap_fn() {
// Create a string, which is allocated on the heap
let s1 = String::from("Hello");
let s2 = String::from("World");
let combined = format!("{} {}", s1, s2);
println!("Heap function: Combined string is '{}'", combined);
}
fn update_string() {
// Start with a base string on the heap
let mut s = String::from("Initial string");
println!("Before update: {}", s);
// Append some text to the string
s.push_str(" and some additional text");
println!("After update: {}", s);
}