DEV Community

Cover image for Rust Doesn't Have a Garbage Collector. It Has Something Stranger.
S M Tahosin
S M Tahosin

Posted on

Rust Doesn't Have a Garbage Collector. It Has Something Stranger.

Every language you have used solves the same problem: who cleans up the memory?

In C, the answer is you. You call malloc, you call free, and if you forget, your program leaks memory until it crashes. If you free too early, you get a use-after-free bug, the kind of vulnerability that has caused real-world security exploits for three decades.

In Java, Python, and Go, the answer is a garbage collector. A background process scans your heap at runtime, finds objects nobody points to anymore, and reclaims their memory. It works, but it comes at a cost: unpredictable pauses, extra CPU cycles, and a runtime that your compiled binary must carry everywhere.

Rust looked at both approaches and said: neither.

Rust has no garbage collector. It also does not ask you to manually free memory. Instead, the Rust compiler mathematically proves, before your program ever runs, that every piece of memory will be freed at exactly the right moment, exactly once, with zero runtime overhead.

The mechanism behind this is called the ownership system, and it is unlike anything in mainstream programming.

Memory management comparison: C/C++ manual free, Java/Python/Go garbage collector, Rust ownership system


The Three Rules That Replace a Garbage Collector

Rust's entire memory model rests on three rules enforced at compile time:

  1. Every value in Rust has exactly one owner.
  2. When the owner goes out of scope, the value is dropped (its memory is freed).
  3. You can temporarily borrow a value, but the compiler tracks every borrow to make sure nothing conflicts.

That sounds simple. Almost suspiciously simple. But these three rules are powerful enough to prevent use-after-free, double-free, dangling pointers, and data races, all without a single byte of runtime overhead.

Let us see exactly how.


Rule 1: One Owner, One Cleanup Responsibility

Consider this Rust code:

fn main() {
    let s = String::from("hello");
    let s2 = s;
    println!("{}", s); // ← This line will NOT compile.
}
Enter fullscreen mode Exit fullscreen mode

If you come from Python or JavaScript, that code looks perfectly fine. You made a string, assigned it to another variable, and tried to print the original. What could go wrong?

In Rust, this fails to compile with the error:

error[E0382]: borrow of moved value: `s`
Enter fullscreen mode Exit fullscreen mode

Here is what happened. String::from("hello") allocated memory on the heap to store the text. The variable s became the owner of that heap allocation. When you wrote let s2 = s, Rust did not copy the heap data. It moved ownership from s to s2.

After the move, s is no longer valid. The compiler marks it as dead. If you try to use s after the move, the compiler refuses, because allowing that would create two variables pointing at the same heap memory, and when both go out of scope, the runtime would try to free the same block twice.

Rust ownership and automatic drop: move from s to s2, scope ends, s2 dropped, heap freed

This is the key insight: Rust does not need a garbage collector because ownership makes the cleanup point deterministic. The compiler knows exactly when each value's owner leaves scope, so it inserts the deallocation call right there, automatically, at compile time.


Rule 2: Borrowing Instead of Sharing

If ownership always moved, Rust would be unusable. Every function call would consume its arguments.

So Rust lets you borrow a value using references:

fn print_length(s: &String) {
    println!("Length: {}", s.len());
}

fn main() {
    let s = String::from("hello");
    print_length(&s);       // Borrow s, don't move it.
    println!("{}", s);       // s is still valid here.
}
Enter fullscreen mode Exit fullscreen mode

The & symbol creates a reference, a temporary, read-only view of the data. The function print_length borrows s but does not own it. When print_length returns, the borrow ends, and s remains valid in main.

But here is where Rust gets strict. The compiler enforces a fundamental aliasing rule:

At any given time, you can have either one mutable reference or any number of immutable references. Never both.

fn main() {
    let mut s = String::from("hello");

    let r1 = &s;       // Immutable borrow — fine.
    let r2 = &s;       // Another immutable borrow — still fine.
    let r3 = &mut s;   // Mutable borrow — COMPILE ERROR.
}
Enter fullscreen mode Exit fullscreen mode

Why does the compiler care? Because this rule prevents data races at compile time. If two parts of your code could read a value while a third part is modifying it, the program behavior becomes unpredictable. Languages with garbage collectors allow this and rely on the programmer to add locks. Rust makes it structurally impossible.


What the Compiler Actually Builds

Most tutorials stop at the rules. But understanding how the compiler enforces those rules reveals why the system works with zero runtime cost.

When you run cargo build, your Rust source code passes through a pipeline of transformations:

Rust compiler pipeline: Source Code → AST → HIR → MIR (borrow checker runs here) → LLVM IR → Binary

The critical stage is MIR, the Mid-level Intermediate Representation. Before your code reaches MIR, the compiler has already parsed the syntax (AST), desugared complex expressions (HIR), and resolved all types. But ownership and borrowing have not been checked yet.

MIR represents your program as a control-flow graph: a network of basic blocks connected by branches. Each block contains simple, flat statements. No nested expressions, no hidden control flow.

Here is a simplified view of what MIR looks like for a small function:

bb0: {
    _1 = String::from("hello")   // allocate
    _2 = move _1                 // ownership transfers
    drop(_2)                     // compiler inserts cleanup
    return
}
Enter fullscreen mode Exit fullscreen mode

Notice the word move. In MIR, every ownership transfer is explicit. The compiler can now walk this graph and track exactly which variable owns each value at every point in the program.

This is where the borrow checker runs. It performs dataflow analysis on the MIR, tracing every value's lifetime, every borrow's span, and every move. If the analysis finds a conflict, it rejects the program with a compile error.

If no conflicts exist, the compiler knows something powerful: every value will be freed exactly once, at a known location, and no reference will ever outlive its data.

The safety proof is complete. Everything after this point is pure optimization.


The "Zero-Cost" Part: What Reaches the CPU

After the borrow checker approves your code, the MIR is translated into LLVM IR and handed to the LLVM optimization engine, the same backend used by Clang for C and C++.

By this point, the ownership rules have already been enforced. LLVM does not know or care about Rust's borrow checker. It sees ordinary code with explicit allocation and deallocation points, and it optimizes the result like any other systems language.

Consider this function:

fn sum_lengths(a: &str, b: &str) -> usize {
    a.len() + b.len()
}
Enter fullscreen mode Exit fullscreen mode

No heap allocation. No reference counting. No garbage collector scan. The compiler verifies the borrows at compile time, and the generated machine code is a plain addition of two integers. The abstraction evaporated completely.

This is what Rust means by "zero-cost abstractions": the safety checks happen during compilation and leave no trace in the final binary. Your program runs as fast as an equivalent C program, but the compiler has already proven it cannot corrupt memory.


Lifetimes: The Compiler's Invisible Bookkeeping

Sometimes the borrow checker needs help figuring out how long a reference should live. That is where lifetime annotations appear:

fn longer<'a>(s1: &'a str, s2: &'a str) -> &'a str {
    if s1.len() > s2.len() { s1 } else { s2 }
}
Enter fullscreen mode Exit fullscreen mode

The 'a annotation does not change your program's behavior. It is a hint to the borrow checker: "the returned reference lives at least as long as both input references."

This lets the compiler verify, at compile time, that the caller does not use the returned reference after either s1 or s2 has been freed. If it cannot prove safety, it refuses to compile.

Lifetime annotations are not runtime markers. They are erased during compilation, just like the ownership checks. They exist only to help the compiler complete its proof.

Most of the time, you never write them. Rust has lifetime elision rules that infer the common patterns automatically. You only need explicit annotations when the compiler genuinely cannot determine the relationships on its own.


When Ownership Is Not Enough

Rust's ownership system covers the vast majority of programs, but it has limits. Some data structures, like graphs or doubly-linked lists, require multiple owners by design. The compiler's single-owner rule would make them impossible to express.

For these cases, Rust provides opt-in runtime mechanisms:

  • Rc<T> (Reference Counting): Tracks the number of owners at runtime. When the count reaches zero, the value is dropped. Single-threaded only.
  • Arc<T> (Atomic Reference Counting): Like Rc, but safe to share across threads using atomic operations.
  • RefCell<T>: Moves borrow checking from compile time to runtime. Panics if you violate the aliasing rules.

These types carry a small runtime cost, which is why they are explicit and opt-in. Rust does not hide the cost. You choose exactly where to pay it, and the compiler enforces everything else for free.


Why This Matters Beyond Rust

The ownership model is not just a language feature. It represents a fundamentally different answer to a problem every programmer faces.

C and C++ gave the programmer full control and full responsibility. Entire classes of security vulnerabilities, buffer overflows, use-after-free, dangling pointers, exist because humans make mistakes with manual memory management. Microsoft estimated that roughly 70% of their security vulnerabilities were caused by memory safety issues.

Garbage-collected languages solved safety by adding a runtime process. That works, but it introduces latency spikes, higher memory usage, and a floor on performance that no amount of tuning can fully remove.

Rust found a third path: prove safety at compile time and generate code with no overhead. The tradeoff is compilation time and a steeper learning curve. The borrow checker requires you to think about data ownership explicitly, something that most languages let you ignore.

But once you internalize the model, the compiler stops being an obstacle and starts acting as a collaborator that catches entire categories of bugs before your code ever executes.

If you have tried Rust and hit a wall with the borrow checker, try looking at it from the compiler's perspective. It is not being difficult. It is building a mathematical proof that your program cannot corrupt memory, and it is asking you for enough information to finish that proof. Once you see the errors through that lens, they start making sense.

What was the first Rust compiler error that genuinely surprised you? And if you have not tried Rust yet, what is the one thing that still feels intimidating about it?


References:

Top comments (0)