Rust ownership from scratch — move, borrow, lifetimes, and memory safety

Contents

  1. 1. Move or copy?
  2. 2. Scopes and dropping
  3. 3. Borrowing
  4. 4. Mutation
  5. 5. Mutable borrows
  6. 6. Ownership rules
  7. 7. Interior mutability
  8. 8. Lifetimes
  9. 9. Summary

Ownership is one of Rust’s most distinctive features — and one of the hardest for newcomers.

Ownership trips up most Rust beginners. The examples below show what it is, why the compiler cares, and how move, borrow, and lifetimes fit together. Skim once for the map; come back for the line-by-line bits.

Tip: The code has comments. You don’t need every detail on the first pass — follow the flow, then dig into specific snippets later.

Move or copy?

Let’s see what ordinary assignment looks like in Rust.

1
2
3
4
5
6
7
8
9
10
println!("start");
// code 1:
let a = 1;
let _b = a;
let _c = a;

// code 2:
let d = String::from("hello");
let _e = d;
let _f = d;

You get:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
error[E0382]: use of moved value: `d`
--> src/main.rs:12:10
|
10 | let d = String::from("hello");
| - move occurs because `d` has type `String`, which does not implement the `Copy` trait
11 | let _e = d;
| - value moved here
12 | let _f = d;
| ^ value used here after move
|
help: consider cloning the value if the performance cost is acceptable
|
11 | let _e = d.clone();
| ++++++++

Why does code 2 fail when code 1 doesn’t?

Both look like “assign this value to another variable more than once” — once for the number a, once for the string d. Only the string case breaks.

That’s Rust’s split between copying a value and moving ownership.

When you pass a value to another variable or function: if the type implements Copy, Rust duplicates it; otherwise ownership moves.

a is an integer; integers are Copy, so code 1 compiles.

d is a String; strings are not Copy. The first assignment moves ownership to _e. You only get one move, so code 2 fails.

Why copy or move at all? Spoiler: Rust has no garbage collector (GC). Memory is tied to ownership — whoever owns a value is responsible for freeing it when the value is dropped.

Let’s watch that in code.

Scopes and dropping

Focus on when things get destroyed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Wrap String so we can impl Drop on our own type (orphan rule)
#[derive(Debug)]
struct MyString(String);
impl MyString {
fn from(name: &str) -> Self {
MyString(String::from(name))
}
}
struct MyData {
data: MyString,
}
// Log when the inner string is dropped
impl Drop for MyString {
fn drop(&mut self) {
println!("Dropping MyString with value: {:?}", self.0);
}
}
// Log when the wrapper struct is dropped
impl Drop for MyData {
fn drop(&mut self) {
println!("Dropping MyData with value: {:?}", self.data);
}
}

fn main() {
{
let _ = MyData {
data: MyString::from("not used"),
};
let _wrapper = MyData {
data: MyString::from("used as variable"),
};
println!("End of the scope inside main.");
}

println!("End of the scope.");
}

Output:

1
2
3
4
5
6
Dropping MyData with value: MyString("not used")
Dropping MyString with value: "not used"
End of the scope inside main.
Dropping MyData with value: MyString("used as variable")
Dropping MyString with value: "used as variable"
End of the scope.

There are two scopes here:

Tip: There are actually more — each let is its own scope too. I’m only naming two to keep the story simple.

  • The scope of main itself

  • An inner block inside main

    Inside the inner block, the MyData bound to _ (and its string) is dropped. let _ means the binding is intentionally ignored and can’t be used again, so it’s dropped right away.

    When you leave the inner block, _wrapper is dropped as well.

Together with “strings can’t be moved twice,” you get two pillars of Rust’s memory story:

  • A value has exactly one owner; when the owner leaves the scope, the value is dropped.
  • Ownership can be transferred.

That model makes manual memory management tractable.

What if you only want to refer to a value without moving it? Moves are one-shot, after all.

Borrowing

A normal “reference” first:

1
2
3
4
5
6
println!("start");
let a = String::from("hello");
let d = &a;
// Same as: let ref d = a;
let _e = d;
let _f = d;

This compiles.

Tip: Rust catches a lot of problems at compile time. That’s why you never saw "start" printed in the earlier failure — compilation stopped first.

Rust splits “references” further; here we call it borrowing (Borrow). We’ll see why in a bit.

From this snippet, one borrow of a string can be assigned to many variables — handy when you don’t need to move the whole String, just read through it.

When is a borrow reclaimed?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Struct that holds a borrow
struct MyDataRef<'a> {
reference: &'a MyData,
}

impl Drop for MyDataRef<'_> {
fn drop(&mut self) {
println!("Dropping MyDataRef");
}
}

fn main() {
{
let a = MyData {
data: MyString::from("used as variable"),
};
let b = MyDataRef { reference: &a };
let c = MyDataRef { reference: &a };
println!("End of the scope inside main.");
}

println!("End of the scope.");
}

Output:

1
2
3
4
5
6
End of the scope inside main.
Dropping MyDataRef
Dropping MyDataRef
Dropping MyData with value: MyString("used as variable")
Dropping MyString with value: "used as variable"
End of the scope.

Borrows are dropped before the owned value. You can have many borrows (specifically immutable borrows — more on that soon), but when the owner is dropped, every borrow goes with it. That’s how Rust avoids use-after-free.

Mutation

We haven’t mutated anything yet.

Can you reassign like in other languages?

1
2
let d = String::from("hello");
d = String::from("world");

No:

1
2
3
4
5
6
7
8
9
10
error[E0384]: cannot assign twice to immutable variable `d`
--> src/main.rs:33:5
|
32 | let d = String::from("hello");
| -
| |
| first assignment to `d`
| help: consider making this binding mutable: `mut d`
33 | d = String::from("world");
| ^ cannot assign twice to immutable variable

Rust separates read from write. As the hint says, you need mut:

1
2
let mut d = String::from("hello");
d = String::from("world");

What does drop look like then?

1
2
3
4
5
6
7
8
9
10
11
fn main() {
{
let mut wrapper = MyData {
data: MyString::from("used as mut variable1"),
};
wrapper.data = MyString::from("used as mut variable2");
println!("[Mutable] End of the scope inside main.");
}

println!("End of the scope.");
}

Output:

1
2
3
4
5
Dropping MyString with value: "used as mut variable1"
[Mutable] End of the scope inside main.
Dropping MyData with value: MyString("used as mut variable2")
Dropping MyString with value: "used as mut variable2"
End of the scope.

Much like immutable bindings — except after reassignment the old value is dropped first. Memory accounting is granular.

We’ve seen borrowing and mut. Borrowing itself has another flavor: the mutable borrow.

Mutable borrows

A mutable binding can have a mutable borrow:

1
2
3
let mut d = String::from("hello");
let g = &mut d;
*g = "world".to_string();

Can you mix mutable and immutable borrows like this?

1
2
3
4
5
6
7
8
fn main() {
let mut d = String::from("hello");
let e = &d;
let f = &d;
let g = &mut d;
*g = "world".to_string();
println!("{f}");
}

No:

1
2
3
4
5
6
7
8
9
10
error[E0502]: cannot borrow `d` as mutable because it is also borrowed as immutable
--> src/main.rs:5:13
|
4 | let f = &d;
| -- immutable borrow occurs here
5 | let g = &mut d;
| ^^^^^^ mutable borrow occurs here
6 | *g = "world".to_string();
7 | println!("{f}");
| --- immutable borrow later used here

The compiler is explicit: while a mutable borrow is active, you can’t also hold immutable borrows.

Think read–write lock: a mutable borrow is like holding the write lock — no concurrent readers, or your writes and their reads could disagree.

Borrowing rules, summarized:

  • You can have many immutable borrows.
  • At most one mutable borrow at a time, and it excludes immutable borrows.

Ownership rules

All three ownership principles are on the table now:

  • Each value has exactly one owner; when the owner leaves its scope, the value is dropped.
  • Ownership can be transferred.
  • Borrowing:
    • Many immutable borrows allowed.
    • One mutable borrow at a time (exclusive with immutable borrows).

These rules define who owns a value, when memory can be freed, and what mutation and sharing are allowed — no dangling use-after-free, and no torn reads during writes (no data races on shared data in the single-threaded borrow-checker sense).

The striking part: the compiler enforces this before you ship. Crashes in production with a late stack trace are worse.

Ownership isn’t done yet — two more ideas: interior mutability and lifetimes.

Interior mutability

So far a borrow is either read-only or write-only — strict. What if you want “mostly read-only” but occasionally mutate through the same handle?

You can.

Rust offers Cell (for Copy types), RefCell (any type; borrow checks at runtime), Arc (thread-safe reference counting), and friends. Mutex and RwLock are the multithreaded face of the same idea.

Tip: Think of these as different granularities of read/write exclusion — mutation without an &mut in your API surface, but mutability inside.

RefCell in action:

1
2
3
4
5
6
7
8
9
10
11
12
13
use std::cell::RefCell;
let value = RefCell::new(5);
// Read through a shared RefCell borrow
let borrowed = value.borrow();
println!("Before mutation: {}", *borrowed);
drop(borrowed);
// Interior mutation
{
let mut borrowed_mut = value.borrow_mut();
*borrowed_mut += 1;
}
let borrowed = value.borrow();
println!("After mutation: {}", *borrowed);

Lifetimes

Last topic: lifetimes.

Why doesn’t this compile?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
fn longest(str1:  &str, str2: &str) -> &str {
if str1.len() > str2.len() {
str1
} else {
str2
}
}

fn main() {
let str1 = "hello";
let str2 = "world!";

let result = longest(str1, str2);
println!("The longest string is: {}", result);
}

Error:

1
2
3
4
5
6
7
8
9
10
11
error[E0106]: missing lifetime specifier
--> src/main.rs:1:39
|
1 | fn longest(str1: &str, str2: &str) -> &str {
| ---- ---- ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `str1` or `str2`
help: consider introducing a named lifetime parameter
|
1 | fn longest<'a>(str1: &'a str, str2: &'a str) -> &'a str {
| ++++ ++ ++ ++

Two borrowed parameters, one borrowed return — the compiler can’t tell which input the return might outlive.

Enter lifetimes: annotations that describe how long references must remain valid, so borrows don’t dangle.

If inputs and output share one lifetime 'a, the returned reference can’t live longer than both inputs — as long as the inputs are valid, the return is valid. If the return could point at something created only inside the function, it would become a dangling pointer after the function returns.

You can picture a lifetime as an extra parameter on a reference, telling the compiler whether that reference is still in-bounds for a given scope.

Side note: Go’s escape analysis solves a related problem — values that must survive the stack frame get heap-allocated. That’s also lifetime reasoning, but with a GC underneath. Rust prefers compile-time lifetime proofs; Box helps when you need heap ownership across scopes (not expanded here).

Does every reference need a label?

No. The compiler infers lifetimes in most code. You only add them when inference clashes. For the deep end, see Subtyping and Variance.

This failing example shows why explicit lifetimes matter for scope checks:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
fn get_longest<'a>(str1: &'a str, str2: &'a str) -> &'a str {
if str1.len() > str2.len() {
str1
} else {
str2
}
}

fn main() {
let result;
{
let str1 = String::from("hello");
let str2 = "world!";
result = get_longest(str1.as_str(), str2);
}

println!("The longest string is: {}", result);
}

Error:

1
2
3
4
5
6
7
8
9
10
11
12
13
error[E0597]: `str1` does not live long enough
--> src/main.rs:15:30
|
13 | let str1 = String::from("hello");
| ---- binding `str1` declared here
14 | let str2 = "world!";
15 | result = get_longest(str1.as_str(), str2);
| ^^^^^^^^^^^^^ borrowed value does not live long enough
16 | }
| - `str1` dropped here while still borrowed
17 |
18 | println!("The longest string is: {}", result);
| ------ borrow later used here

Summary

Wrapping up:

  • Ownership is about who owns values and when memory is freed.
  • The borrow checker enforces that borrows are valid at compile time.
  • Lifetimes describe how long references must stay alive.

Together they give Rust strong memory safety without a GC — fewer leaks, fewer dangling pointers, and less runtime overhead from collection.

If you’re curious, the ownership story is worth the learning curve: one coherent model instead of implicit rules scattered across the language.

Questions? Leave a comment below or email: newbvirgil@gmail.com