Skip to main content
Be Bitwise
RustRust Basics & Ownership

The Ownership Rules

Ownership is Rust's signature move. It's the machinery that lets the language promise memory safety without ever running a garbage collector.

The Three Rules

  1. Every value has an owner.
  2. Exactly one owner at a time.
  3. When the owner falls out of scope, the value is dropped — freed automatically.
rust
{
let s = String::from("hello"); // s owns the String
// s is valid here
} // s goes out of scope - String is dropped (memory freed)

Move Semantics

Assignment doesn't copy heap-owning values — ownership moves:

rust
let s1 = String::from("hello");
let s2 = s1; // ownership moves from s1 to s2
// println!("{}", s1); // ERROR: s1 no longer owns the data
println!("{}", s2); // OK: s2 is the owner
Key Concept

A C programmer reading this expects both variables to alias the same buffer — and a careless free on one to nuke the other. Rust forecloses on the entire failure mode: the compiler tracks the move and refuses to let the dead binding speak.

Why Moves?

Picture what happens without moves:

If both s1 and s2 were live, dropping each would free the same heap allocation twice. Classic double-free. Rust shuts the door by invalidating s1 the moment the move happens.

Stack vs Heap

Stack-only types like integers don't move — they're copied:

rust
let x = 5;
let y = x; // x is copied, both are valid
println!("{} {}", x, y); // OK

It works because integers implement the Copy trait. Anything trivially copyable — integers, booleans, floats, chars — gets bitwise duplicated. Anything with a heap allocation behind it (String, Vec, your Box-wrapped types) moves.

Functions and Ownership

Passing into a function is also a move:

rust
fn take_string(s: String) {
println!("{}", s);
} // s is dropped here
let s = String::from("hello");
take_string(s);
// println!("{}", s); // ERROR: s was moved into the function

Returning hands ownership back the other way — the caller becomes the new owner:

rust
fn give_string() -> String {
let s = String::from("hello");
s // ownership moves to the caller
}
let s = give_string(); // s now owns the String

The Ownership Pattern

It can feel cramped at first. The payoff:

  • No double frees — only the owner can drop, and there's only one owner.
  • No use-after-free — moved-from bindings refuse to compile if you touch them.
  • Destruction is deterministic — you know exactly when cleanup runs.
  • Cleanup is automatic on scope exit (yes, leaks are still reachable via reference cycles or mem::forget).

All of it falls out at compile time, and your binary pays nothing for the privilege.

Time to watch the rules fire. impl Drop lets a type run code when it's freed, so Noisy announces each drop. Predict the order of the four lines before you press Run.

Try itUncomment the marked line to get a use-after-move error, then fix it by having take() return the Noisy it was given.
Rust (1.40.0)