Module 2 · Ownership & memory
2.1Stack vs. heap
Where your data lives, why Rust stores values inline unless a type like String, Vec or Box owns heap memory, and what Rust's Box has to do with boxing.
On this page
Concept map
| Concept | TypeScript | C# | Rust |
|---|---|---|---|
| Who decides where data lives | The engine; you can't see or choose it | The type's author (struct or class), then the runtime | You, through the types you pick |
| A small record like a point | An object on the heap, reached through a reference | class: on the heap. struct: stored inline, wherever its variable or container is | A struct is stored inline, wherever its owner is |
| Growable text or list | string and arrays live on the heap | string and List<T> are heap objects | String and Vec<T>: pointer, length and capacity inline; the data on the heap |
| Boxing | No boxing you can see | Implicit. Converting a value type to object or an interface copies it into a new heap object | Explicit. Box::new(value) moves the value into one heap allocation that the Box owns |
| Freeing heap memory | The garbage collector, later | The garbage collector, later | The owner, when it goes out of scope |
In TypeScript you never decide where data lives: the engine does. Rust hands that choice to you, through one simple rule:In C# the author of a type decides once, with struct or class, and the runtime adds exceptions such as boxing. Rust takes a simpler line: every value is stored right where its owner is, and nothing goes on the heap unless you use a type that puts it there, such as String, Vec or Box. You can read where each byte lives from the types.
The stack and the heap in one minute
The stack holds the local variables of each function call. Each call gets a frame whose size the compiler knows in advance, and the whole frame disappears when the function returns. Allocating there is just moving a pointer, so it’s very fast.
The heap holds data whose size is only known at runtime, or that must outlive the call that created it. Someone has to free it later. In TypeScriptC#, that’s the garbage collector. In Rust, it’s the owner, at the end of its scope, as the ownership lesson shows.
Values live inline by default
Here’s a Line made of two Points in each language. The code looks the same; the memory doesn’t.
type Point = { x: number; y: number };
type Line = { start: Point; end: Point };
// Three heap objects: the line and two points it refers to
const line: Line = { start: { x: 0, y: 0 }, end: { x: 3, y: 4 } };
console.log(`(${line.start.x}, ${line.start.y}) to (${line.end.x}, ${line.end.y})`);// One heap object: the Line. Its two Points are stored inside it.
var line = new Line(new Point(0, 0), new Point(3, 4));
Console.WriteLine($"({line.Start.X}, {line.Start.Y}) to ({line.End.X}, {line.End.Y})");
readonly record struct Point(int X, int Y);
record Line(Point Start, Point End);struct Point {
x: i32,
y: i32,
}
struct Line {
start: Point,
end: Point,
}
// No heap at all: the whole 16-byte Line sits in main's stack frame
let line = Line {
start: Point { x: 0, y: 0 },
end: Point { x: 3, y: 4 },
};
println!(
"({}, {}) to ({}, {})",
line.start.x, line.start.y, line.end.x, line.end.y
);Output
(0, 0) to (3, 4)
-
TypeScript allocates three objects, and
lineholds a reference to one of them.C# allocates oneLineobject, becauseLineis arecord(a class).Pointis arecord struct, so both points are stored inside thatLineobject, on the heap. - Rust allocates nothing. A
structis just its fields laid side by side, andlineis a local variable, so all four numbers are on the stack.
Mental model shiftRust has no reference types
In TypeScript, every object is reached through a reference, and the engine decides where it lives. Rust has only values: a Rust struct is just its fields, stored wherever its owner is.C# splits types into value types and reference types. Rust has only values. A Rust struct behaves like a C# struct that the runtime never boxes: it’s stored wherever its owner is. Put it in a local and it’s on the stack. Push it into a Vec and it’s in the vector’s heap buffer. Put it in a Box and it’s in that box’s heap allocation.
Heap data needs an owner
Text and lists can grow, so their contents can’t sit in a fixed-size stack slot. Rust’s String and Vec<T> keep a small, fixed-size part inline (a pointer, a length and a capacity) and put the contents on the heap. They own that heap buffer, so they free it when they go out of scope.
const name = "Ada";
const scores = [90, 85];
scores.push(77); // the array may move to a bigger heap block
console.log(`${name}: ${scores.join(", ")}`);var name = "Ada";
var scores = new List<int> { 90, 85 };
scores.Add(77); // the list may copy its items to a bigger heap array
Console.WriteLine($"{name}: {string.Join(", ", scores)}");let name = String::from("Ada");
let mut scores = vec![90, 85];
scores.push(77); // may reallocate the heap buffer; `scores` itself stays 24 bytes
let joined: Vec<String> = scores.iter().map(|s| s.to_string()).collect();
println!("{name}: {}", joined.join(", "));Output
Ada: 90, 85, 77
Both versions keep the text and the numbers on the heap. The difference is who frees them: in TypeScriptC#, the garbage collector, at some point after nothing refers to them; in Rust, name and scores free their buffers at the closing brace of main.
Boxing vs. Box<T>
Boxing means wrapping a plain value, like a number, in a heap object. JavaScript has no value types to box, so TypeScript never does it behind your back. The nearest thing is the primitive wrapper objects: new Number(5) creates a heap object that wraps the number 5, and .valueOf() reads the number back out (unboxing). Calling a method on a primitive, as in (5).toFixed(1), is defined as if the number were first wrapped in a temporary Number object. You rarely meet either in real code, so the TypeScript version below uses a plain object, { value: count }, to play the box’s role.
C# boxing happens when you treat a value type as object or as an interface. The runtime allocates a new heap object and copies the value into it. Unboxing is the cast that copies it back out, and it must name the exact type: unboxing a boxed int as a long throws InvalidCastException. Boxing and unboxing happen without a visible new, and the box is a separate copy: changing the original doesn’t change the box.
Rust’s Box<T> is a plain type you create on purpose. Box::new(value) moves the value into a new heap allocation, and the Box owns it. You read the value through it with * (dereference), and the allocation is freed when the Box goes out of scope.
let count = 1;
const boxed = { value: count }; // no boxing in TS: a wrapper object is the closest thing
count++;
console.log(`${count} ${boxed.value}`);
const unboxed = boxed.value;
console.log(unboxed);int count = 1;
object boxed = count; // boxing: copies 1 into a new heap object
count++;
Console.WriteLine($"{count} {boxed}");
int unboxed = (int)boxed; // unboxing: copies the 1 back out
Console.WriteLine(unboxed);let mut count = 1;
let boxed = Box::new(count); // you ask for the heap allocation
count += 1;
println!("{count} {boxed}");
let unboxed = *boxed; // `*` reads the value inside the box
println!("{unboxed}");Output
2 1 1
The output matches, because both put a copy of 1 on the heap. What differs is everything around it:
- Visibility. Here both versions ask for the wrapper, but in general TypeScript code never shows whether a value is on the heap: the engine decides.C# also boxes when you pass an
intto anobjectparameter, store it in anobject[]or anArrayList, or assign a struct to a variable of an interface type. Nothing in the code says “allocate”. (Generics avoid it: aList<int>stores its numbers unboxed, unlike anArrayList.) In Rust, the only way to get aBoxis to writeBox::new(or call something whose return type saysBox). - Lifetime. The wrapper objectA C# box lives until the garbage collector finds it unreachable. A Rust
Boxis freed exactly when its owner goes out of scope. - Ownership. A
Boxfollows the same move rules as aString:let other = boxed;moves it, and only one variable owns the allocation. In TypeScript,const other = boxed;would give you two names for one wrapper object.
Identity differs too. Every C# boxing creates a new object, so boxing the same int twice gives two separate objects:
int score = 42;
object first = score; // one box
IComparable<int> second = score; // boxing again: a second heap object
Console.WriteLine(ReferenceEquals(first, second));That prints False. Rust has no equivalent: no conversion silently moves a value to the heap.
Idiomatic RustBox methods work on the value inside
You rarely need to write * yourself. Method calls and println! look through the box automatically, so boxed.pow(2) and println!("{boxed}") both use the i32 inside. You write * to copy the value out or to assign through the box: *boxed += 5;. Reading Rust’s symbols covers * next to &.
When you actually need Box<T>
Most Rust code never writes Box, because String and Vec already manage the heap for you. You need it in three situations:
- Recursive types. A type that contains itself needs a pointer, or its size would be infinite. This is the common case, and it’s shown below.
- Large values you move around. Moving a value copies its bytes. Moving a
Boxcopies only the 8-byte pointer. This matters only for values of many kilobytes, so measure first. - Trait objects.
Box<dyn Trait>holds “any type that implements this trait”, like a variable typed with an interface in TypeScriptC#. Module 9 covers it.
In TypeScriptC#, a type can refer to itself directly, because its fields hold references. In Rust, a field holds the value itself, so a self-referencing field needs a Box:
type ListNode = { value: number; next: ListNode | null };
const list: ListNode = { value: 1, next: { value: 2, next: null } };
console.log(`${list.value} -> ${list.next?.value}`);var list = new ListNode(1, new ListNode(2, null));
Console.WriteLine($"{list.Value} -> {list.Next?.Value}");
record ListNode(int Value, ListNode? Next);struct ListNode {
value: i32,
next: Option<Box<ListNode>>, // Option: "a node or nothing" (Module 6)
}
fn main() {
let list = ListNode {
value: 1,
next: Some(Box::new(ListNode {
value: 2,
next: None,
})),
};
// `if let` (Module 4) runs the block only if there is a next node
if let Some(next) = &list.next {
println!("{} -> {}", list.value, next.value);
}
}Output
1 -> 2
Option<Box<ListNode>> is Rust’s version of ListNode | nullListNode?: either nothing, or a pointer to a node on the heap. Module 11 covers Box and other smart pointers in depth.
Which one should I use?
| What | When | Why | How |
|---|---|---|---|
Plain value (i32, your own struct, arrays, tuples) | The default for anything with a size known at compile time. | No allocation, no pointer to follow, freed for free when the owner’s scope ends. | let line = Line { ... }; |
Vec<T> | A list whose length changes or is only known at runtime. | It owns a heap buffer and grows it for you. | let mut scores = vec![90, 85];, scores.push(77); |
String | Text you build, change or keep. | It owns a heap buffer of UTF-8 bytes and grows it for you. | String::from("Ada"), format!(...) |
Box<T> | A recursive type, a very large value you move often, or a trait object. | It puts exactly one value on the heap, with one owner and a pointer-sized handle. | Box::new(value); read with *boxed or call methods directly. |
Rule of thumb: use plain values, and let Vec and String handle the heap. Reach for Box<T> only when the compiler tells you a type has infinite size, you need a trait object, or you’ve measured that moving a large value is slow. Box<T> is not a way to get a shared object like a TypeScript onenot C# boxing and not a way to make a “reference type”: wrapping a Vec or String in a Box just adds a second pointer to follow, and Clippy warns about it (box_collection).
Under the hood
Here are the three kinds of value side by side:
let count: i32 = 7;
let name = String::from("Ada");
let boxed: Box<i32> = Box::new(7);
println!("{count} {name} {boxed}");Every type has a size fixed at compile time, and that’s what goes on the stack. You can ask for it with size_of:
println!("i32: {} bytes", size_of::<i32>());
println!("String: {} bytes", size_of::<String>());
println!("Vec<i32>: {} bytes", size_of::<Vec<i32>>());
println!("Box<i32>: {} bytes", size_of::<Box<i32>>());On a 64-bit target this prints 4, 24, 24 and 8 today: a String or Vec is three 8-byte numbers, however much text or data it holds, and a Box is one pointer. When main ends, Rust drops boxed (freeing its allocation), then name (freeing its buffer); count needs no cleanup.
Drawn to scale, the part of each value that sits on the stack looks like this:
| Value | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | Size |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
i32 | value4 bytes | 4 bytes | |||||||||||||||||||||||
String | ptr8 bytes · pointer | len8 bytes | capacity8 bytes | 24 bytes | |||||||||||||||||||||
Vec<i32> | ptr8 bytes · pointer | len8 bytes | capacity8 bytes | 24 bytes | |||||||||||||||||||||
Box<i32> | ptr8 bytes · pointer | 8 bytes | |||||||||||||||||||||||
Each row is drawn to scale in bytes. An i32 is 4 bytes holding the number itself. A String and a Vec<i32> are each 24 bytes today, on a 64-bit target: an 8-byte pointer to the heap buffer, an 8-byte length and an 8-byte capacity, however long the text or list is (Rust doesn't fix the order of those three fields; this is one possible order). A Box<i32> is a single 8-byte pointer to its heap allocation. The text, the list items and the boxed number are all on the heap, outside these bytes.
That fixed size is also why a recursive type needs a pointer. Without one, a ListNode would contain a ListNode, which contains a ListNode, forever:
struct ListNode {
value: i32,
next: Option<ListNode>,
}Rust doesn't compile this: error E0072
error[E0072]: recursive type `ListNode` has infinite size
--> main.rs:1:1
|
1 | struct ListNode {
| ^^^^^^^^^^^^^^^
2 | value: i32,
3 | next: Option<ListNode>,
| -------- recursive without indirection
|
help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to break the cycle
|
3 | next: Option<Box<ListNode>>,
| ++++ +The compiler suggests the fix itself: insert some indirection, such as a Box.
Common pitfalls
Common pitfallThe types tell you where data lives
In TypeScript, where a value lives is the engine’s choice, and nothing in your code shows it. In Rust you don’t have to guess, because the rule has no exceptions: a value lives inside its owner. A local is on the stack; anything inside a Vec, String or Box is on the heap. The compiler never moves a value to the heap behind your back.
Common pitfall'struct = stack, class = heap' is only roughly true
In C#, that rule of thumb breaks in many everyday cases. A struct field inside a class lives inside that object, on the heap. A Point[] array stores its points in the array, on the heap. A struct local captured by a lambda, or used across an await in an async method, can end up in a heap-allocated closure or state machine object. Boxing copies it to the heap. Going the other way, recent .NET JITs use escape analysis to put some objects that never leave a method on the stack.
Rust’s rule has no exceptions: a value lives inside its owner. A local is on the stack; anything inside a Vec, String or Box is on the heap. The compiler never moves a value to the heap behind your back.
Common pitfallA box is a copy, not the original
In C#, calling an interface method on a boxed struct changes the box, not your variable:
var counter = new Counter();
IIncrementable boxed = counter; // boxing copies the struct
boxed.Increment(); // changes the copy in the box
Console.WriteLine($"{counter.Value} {((Counter)boxed).Value}");
interface IIncrementable
{
void Increment();
}
struct Counter : IIncrementable
{
public int Value;
public void Increment() => Value++;
}This prints 0 1. In Rust, Box::new(counter) moves counter into the box, so there’s no stale original left to confuse you: the compiler stops you from using counter afterwards unless its type is Copy.
Here’s memory after boxed.Increment(): two separate Counter values, and the method changed the one in the box.
Common pitfallBox<T> doesn't make a value shared
Coming from TypeScript, where every object is shared by reference, it’s tempting to read Box<T> as “make this a shared object”.Coming from C#, it’s tempting to read Box<T> as “make this a reference type”. It isn’t. A Box has one owner: let other = boxed; moves it, and boxed.clone() allocates a second box with a copy of the value inside. Shared ownership, where several variables point at one heap value, is opt-in with Rc<T> or Arc<T>, covered in Module 11.
Try it yourself
Exercise: port this to Rust
Port this program to Rust. Put a copy of original in a Box<i32>, add 5 to the value in the box, and print both numbers.
const original = 10;
const boxed = { value: original };
boxed.value += 5;
console.log(`${original} ${boxed.value}`);int original = 10;
object boxed = original;
boxed = (int)boxed + 5; // unbox, add, then box the result as a new object
Console.WriteLine($"{original} {boxed}");Expected output
10 15
Show a hint
Box::new(original) copies the i32 into the heap. Declare the box with let mut, then change the value inside it with *boxed += 5.
Show a solution
let original = 10;
let mut boxed = Box::new(original);
*boxed += 5;
println!("{original} {boxed}");The box owns its own copy of 10, so changing it leaves original alone. Rust writes through the pointer with *, so no new box is made: the same heap allocation now holds 15.
Saved in this browser only.