Ownership

Rust's central idea — every value has one owner, ownership moves on assignment, values are dropped when their owner goes out of scope — plus Copy vs move types, Clone, stack vs heap, and how this replaces garbage collection.

Intermediate 3 min readLesson 2 of 9 Interview Q&A

Most languages manage heap memory either manually (C: malloc/free, with use-after-free and leak bugs) or with a garbage collector (Java, Go, Python: safe, but with runtime overhead and pauses). Rust takes a third path: a set of ownership rules checked at compile time. If the program compiles, memory is freed exactly once, at a predictable point, and never used after being freed — with zero runtime cost.

The three rules

  1. Each value has an owner (a variable).
  2. There can be only one owner at a time.
  3. When the owner goes out of scope, the value is dropped (its memory and resources are freed).
Rust
{
    let s = String::from("hello");   // s owns a heap buffer
    // use s
}                                    // scope ends: drop(s) runs automatically, freeing the buffer

This is RAII (resource acquisition is initialisation), as in C++: files, sockets, locks and memory are all released by Drop when their owner goes away.

Moves

Assigning a heap-owning value to another variable moves ownership; the original becomes unusable:

Rust
let s1 = String::from("hello");
let s2 = s1;                 // ownership moves to s2
println!("{s1}");            // ✗ error[E0382]: borrow of moved value: `s1`
ownsno longers1(moved — invalid)s2ptr · len 5 · cap 5heap: h e l l o

Why not copy the heap data? That would be expensive and implicit. Why not let both point to it? Then both would try to free it at the end of scope — a double free. Moving is cheap (copy three words: pointer, length, capacity) and keeps exactly one owner.

Moves also happen when passing to functions and returning from them:

Rust
fn take(s: String) {          // s comes into scope, owning the value
    println!("{s}");
}                             // s dropped here

fn give() -> String {
    String::from("yours")     // ownership moves out to the caller
}

let a = String::from("hi");
take(a);                      // a moved into take
// println!("{a}");           // ✗ a is no longer valid
let b = give();               // b owns the returned String

Passing ownership back and forth is clumsy — that's what borrowing solves (Borrowing & lifetimes).

Copy types

Simple values that live entirely on the stack — integers, floats, bool, char, and tuples/arrays of them — implement the Copy trait. Assignment duplicates them, and the original stays valid:

Rust
let x = 5;
let y = x;           // copy
println!("{x} {y}"); // ✓ both valid

A type can be Copy only if all its parts are Copy and it has no Drop logic — so String, Vec and Box are never Copy.

Clone: explicit deep copies

When you really want two independent heap copies, say so:

Rust
let s1 = String::from("hello");
let s2 = s1.clone();         // allocates and copies the bytes
println!("{s1} {s2}");       // ✓

Seeing .clone() in code is a visible signal of a potentially expensive operation — unlike languages where copies happen implicitly.

Stack and heap

StackHeap
HoldsFixed-size values: integers, structs of known size, pointersDynamically sized data: String contents, Vec elements, Box<T>
AllocationMoving a stack pointer — extremely cheapAllocator call — slower
FreedAutomatically when the function returnsWhen the owner is dropped (Rust)

A String variable is a stack struct (pointer, length, capacity) that owns a heap buffer. Ownership is how Rust knows when to free the heap part. See Memory: stack & heap.

Drop order and the Drop trait

Rust
struct Connection { name: String }

impl Drop for Connection {
    fn drop(&mut self) {
        println!("closing {}", self.name);     // cleanup logic runs automatically
    }
}

fn main() {
    let _a = Connection { name: "a".into() };
    let _b = Connection { name: "b".into() };
    // prints "closing b" then "closing a" — dropped in reverse declaration order
    drop(_a);   // or drop early, explicitly (std::mem::drop takes ownership)
}

Ownership and collections

Rust
let names = vec![String::from("ada"), String::from("alan")];
for name in names {          // into_iter: takes ownership; each name is moved out
    println!("{name}");
}
// names is gone here

let names = vec![String::from("ada")];
for name in &names {         // iterate by reference: borrow, don't take
    println!("{name}");
}
println!("{}", names.len()); // ✓ still valid

let first = names[0];        // ✗ cannot move out of index — would leave a hole in the Vec
let first = &names[0];       // ✓ borrow
let first = names[0].clone(); // ✓ copy

Why this matters

Bug classHow ownership prevents it
Use after freeUsing a moved-from or dropped value is a compile error
Double freeOnly one owner ever drops a value
Memory leaks (mostly)Values are dropped deterministically at scope end (leaks are possible but rare and explicit: Rc cycles, mem::forget)
Resource leaksFiles, sockets, locks released by Drop
Data racesCombined with borrowing rules and Send/Sync (Fearless concurrency)
Key takeaways
  • Every value has exactly one owner; it's dropped when the owner goes out of scope (RAII).
  • Assigning or passing a heap-owning value moves it; the old binding becomes invalid.
  • Copy types (integers, bool, char…) are duplicated instead of moved.
  • clone() makes explicit deep copies.
  • Ownership eliminates use-after-free and double-free at compile time with no GC.
Interview questions
QHow does Rust manage memory without a garbage collector?medium

Through ownership checked at compile time: every value has a single owner, ownership moves on assignment or when passed by value, and the value is dropped deterministically when its owner goes out of scope. Borrowing lets code use values temporarily without taking ownership, and the borrow checker ensures references never outlive the data or alias mutable data. The compiler inserts the frees, so there's no runtime collector.