Lecture 21 - Ownership: the three rules, moves, and copies
Announcements
Remember this murky situation in Python?
What happens to a when we change b?
a = [1, 2, 3]
b = a
b.append(4)
print(a)
What does this print, and why?
[1, 2, 3, 4]. b = a didn't copy the list, it copied the address of the list. So we have two variables pointing to the same value.
So how does Python know when you're done with that part of memory?
It counts references. It adds one when you make a new reference and subtracts one when references go away, and frees the memory when the count hits zero.
That count is checked while your program runs, which costs time!
Rust's solution: Ownership
Ownership tracks what variable is responsible for data that is on the heap.
- It helps efficiently free up memory when it is no longer needed (better than Python)
- It helps prevent "undefined behavior" that arises from less-strict approaches (better than C)
Learning Objectives
By the end of today, you should be able to:
- State the three ownership rules
- Say which types are
Copy, and why everything else moves - Predict whether a program compiles after a move, including a move into or out of a function
- Draw a move and a clone on a stack and heap diagram
Rust's Three Ownership Rules
These are the fundamental rules that make Rust memory-safe:
- Each value in Rust has an owner
- There can only be one owner at a time
- When the owner goes out of scope, the value will be dropped
Rule 1: Each value in Rust has an owner
#![allow(unused)] fn main() { let s1 = String::from("hello"); // s1 owns the string // There is exactly ONE owner of the "hello" data on the heap }
Stack: Heap:
┌─────────────┐ ┌─────┬─────┬─────┬─────┬─────┐
│ s1: String │ │ 'h' │ 'e' │ 'l' │ 'l' │ 'o' │
│ ├ ptr ──────┼─▶│ │ │ │ │ │
│ ├ len: 5 │ └─────┴─────┴─────┴─────┴─────┘
│ └ cap: 5 │
└─────────────┘
Rule 2: There can only be one owner at a time
fn main() { 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 now owns it }
What happens in memory:
Before move: After move:
Stack: Stack:
┌─────────────┐ ┌─────────────┐
│ s1: String │ │ s2: String │
│ ├ ptr ──────┼──┐ │ ├ ptr ──────┼─┐
│ ├ len: 5 │ │ │ ├ len: 5 │ │
│ └ cap: 5 │ │ │ └ cap: 5 │ │
└─────────────┘ │ ├─────────────┘ │
│ │ s1: (moved) │ │
│ └─────────────┘ │
│ │
│ Heap: │
│ ┌─────┬─────┬─────┬─────┬─────┐
└─▶│ 'h' │ 'e' │ 'l' │ 'l' │ 'o' │
└─────┴─────┴─────┴─────┴─────┘
This looks the same as Python but it's different
b = a # Python: two names, one list, both usable
let s2 = s1; // Rust: two names, one string, only s2 usable
The heap looks identical in both languages. One allocation, and a second variable now pointing at it.
Python allows both names and keeps a count. Rust has the second name take over and the first one is killed.
Both approaches are valid, but there are trade-offs.
Rule 3: When the owner goes out of scope, the value is dropped
fn main() { { let s = String::from("hello"); // s owns the string } // s goes out of scope, heap memory is freed automatically! println!("{}", s); // error: there is no s here anymore }
Rule 3 is what makes it all work.
Before, we had to remember to call libc::free by hand. Rule 3 is the compiler doing that call for you every time a variable goes out of scope, and since there's only one owner, it never happens twice!
Move vs Copy
An i32 gets copied
#![allow(unused)] fn main() { let x = 5; let y = x; // x is copied to y println!("{} {}", x, y); // Both work! }
A String gets moved
#![allow(unused)] fn main() { let s1 = String::from("hello"); let s2 = s1; // s1 is moved to s2 // println!("{}", s1); // s1 is no longer valid println!("{}", s2); // Only s2 works now }
Why would an int get copied but a string get moved by default?
Think-pair-share
Because copying the i32 is cheap: it is 4 bytes on the stack.
Copying the String would mean either copying just the 24-byte handle (creating two pointers, with those dangers), or making a duplicate of all the characters too, which takes up lots of room. So by default it's a move.
If you want the characters fully copied, you can say .clone() (we'll see it in a minute).
The short list of types that copy
A type copies when copying its bytes gives you two complete values with nothing shared. These are called Copy types:
- Integers and floats:
i32,u8,usize,f64, ... boolandchar- Tuples and arrays made only of these
&Ttypes (like&str). A second read-only pointer is cheap and low-risk
Everything else moves.
"Stack types copy, heap types move" is almost always true, with a couple of small exceptions. Your own structs and enums, for example, move unless you tell them to copy.
If you want a real ("deep") copy, ask for it with .clone()
fn main() { let s1 = String::from("hello"); let s2 = s1.clone(); // new heap block, letters copied println!("{} {}", s1, s2); // both work }
Stack: Heap:
┌──────────────────────┐
│ main() │
│ ├ s1: String │ ┌───┬───┬───┬───┬───┐
│ │ ptr ─────────────┼────▶│ h │ e │ l │ l │ o │
│ │ len: 5 │ └───┴───┴───┴───┴───┘
│ │ cap: 5 │
│ └ s2: String │ ┌───┬───┬───┬───┬───┐
│ ptr ─────────────┼────▶│ h │ e │ l │ l │ o │
│ len: 5 │ └───┴───┴───┴───┴───┘
│ cap: 5 │
└──────────────────────┘
Two handles, two blocks of letters, two owners.
.clone() always compiles, which makes it tempting. But it also duplicates every byte on the heap. When the compiler complains about a move, clone is one fix, but not always the best one. (We'll see more options shortly!)
Your own structs move
struct Point {
x: i32,
y: i32,
}
struct NamedPoint {
name: String,
point: Point,
}
fn main() {
let p1 = Point { x: 3, y: 4 };
let home = NamedPoint { name: String::from("home"), point: p1 };
let work = NamedPoint { name: String::from("work"), point: p1 };
println!("{} {}", home.name, work.name);
}
Compiles, compiler error, or runtime panic?
A compiler error. p1 moved into home, so there is nothing left to put in work.
A struct copies only if you tell it to, and only if all its fields are Copy types. You can do that the same way you told it about Debug and PartialEq:
#[derive(Debug, Clone, Copy)]
struct Point {
x: i32,
y: i32,
}
Copy requires Clone as a prerequisite, so the two usually appear together.
Passing data to functions follows the same move/copy rules
fn takes_ownership(some_string: String) { println!("in fn: {}", some_string); } // some_string goes out of scope and heap memory is freed fn makes_copy(some_integer: i32) { println!("in fn: {}", some_integer); } // some_integer goes out of scope, but it's just a copy fn main() { let s = String::from("hello"); takes_ownership(s); // s is moved into the function // println!("in main: {}", s); // ERROR! s is no longer valid let x = 5; makes_copy(x); // x is copied into the function println!("in main: {}", x); // OK! x is still valid }
Function return values also transfer ownership
fn gives_ownership() -> String { let some_string = String::from("yours"); some_string // Ownership moves to caller } fn takes_and_gives_back(a_string: String) -> String { a_string // Ownership moves back to caller } fn main() { let s1 = gives_ownership(); // Ownership moves from function to s1 let s2 = String::from("hello"); // s2 comes into scope let s3 = takes_and_gives_back(s2); // s2 moves in, s3 gets it back // s2 is no longer valid, but s1 and s3 are println!("s1: {}", s1); // println!("s2: {}", s2); println!("s3: {}", s3); }
Let's draw these moves on the board!
Step 1: inside gives_ownership, just before it returns.
Stack: Heap:
┌──────────────────────────┐
│ gives_ownership() │
│ └ some_string: String │ ┌───┬───┬───┬───┬───┐
│ ptr ─────────────────┼───▶│ y │ o │ u │ r │ s │
│ len: 5, cap: 5 │ └───┴───┴───┴───┴───┘
├──────────────────────────┤
│ main() │
│ ├ s1: String = ??? │
│ ├ s2: String = ??? │
│ └ s3: String = ??? │
└──────────────────────────┘
Step 2: after it returns.
Stack: Heap:
░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░ gives_ownership() (gone) ░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░
┌──────────────────────────┐
│ main() │
│ ├ s1: String │ ┌───┬───┬───┬───┬───┐
│ │ ptr ─────────────────┼───▶│ y │ o │ u │ r │ s │
│ │ len: 5, cap: 5 │ └───┴───┴───┴───┴───┘
│ ├ s2: String = ??? │
│ └ s3: String = ??? │
└──────────────────────────┘
Step 3: inside takes_and_gives_back.
Stack: Heap:
┌──────────────────────────┐
│ takes_and_gives_back() │
│ └ a_string: String │ ┌───┬───┬───┬───┬───┐
│ ptr ─────────────────┼───▶│ h │ e │ l │ l │ o │
│ len: 5, cap: 5 │ └───┴───┴───┴───┴───┘
├──────────────────────────┤
│ main() │
│ ├ s1: String │ ┌───┬───┬───┬───┬───┐
│ │ ptr ─────────────────┼───▶│ y │ o │ u │ r │ s │
│ │ len: 5, cap: 5 │ └───┴───┴───┴───┴───┘
│ ├ s2: (moved out) │
│ └ s3: String = ??? │
└──────────────────────────┘
Step 4: at the end of main.
Stack: Heap:
┌──────────────────────────┐
│ main() │
│ ├ s1: String │ ┌───┬───┬───┬───┬───┐
│ │ ptr ─────────────────┼───▶│ y │ o │ u │ r │ s │
│ │ len: 5, cap: 5 │ └───┴───┴───┴───┴───┘
│ ├ s2: (moved out) │
│ └ s3: String │ ┌───┬───┬───┬───┬───┐
│ ptr ─────────────────┼───▶│ h │ e │ l │ l │ o │
│ len: 5, cap: 5 │ └───┴───┴───┴───┴───┘
└──────────────────────────┘
Try to predict what happens before running:
Think-pair-share
fn main() { let s1 = String::from("world"); let s2 = process_string(s1); println!("{}", s2); // Will this work? println!("{}", s1); // Will this work? } fn process_string(input: String) -> String { let greeting = format!("Hello, {}!", input); greeting }
Monday's bugs vs today's rules
| Bug from Monday | What Rust does | Rule |
|---|---|---|
| Leak: nobody frees it | The owner frees it at its closing brace | 3 |
| Double-free: two pointers, each frees it | let s2 = s1 moves. Only s2 is freed | 1 and 2 |
| Use-after-free: freed, then used | A moved or dropped value cannot be used | 2 and 3 |
Use-after-free, written in Rust:
fn main() {
let data = String::from("hello");
drop(data); // free it now, by hand
println!("{}", data); // bug 2
}
error[E0382]: borrow of moved value: `data`
3 | drop(data);
| ---- value moved here
4 | println!("{}", data);
| ^^^^ value borrowed here after move
drop is just a function that takes ownership and does nothing with it. Rule 3 does the rest at its closing brace.
Take-aways
- Three rules: every value has one owner, only one at a time, and it is dropped at the owner's closing brace
Copytypes copy: numbers,bool,char, and&T. Everything that owns heap data moves- A move hands over the handle. The heap does not change.
.clone()makes a second heap block.- Passing to/from a function follows the same rules
- Rule 3 is
free, done for you, exactly once
Activity 21
See activities/activity_21.md. Acting out ownership.
Two quick questions on Gradescope, after Act 1 and after Act 3.