An order slip at Rusdi's Pancake Stall is a single sheet. When the cashier hands it to the kitchen, the cashier no longer holds it. To keep one too, the cashier must photocopy it first, which costs paper and time. A price of $32, on the other hand, can just be said out loud: everyone can know the number and nobody loses anything. At closing time, each person throws away the slips they still hold, so no slip is ever thrown away twice.
This slip rule is the same as how Rust manages memory without a garbage collector, and it is called ownership. Earlier lessons showed that a String can move to another variable. This lesson explains the rules behind that, and why a number is copied while a String is moved. Every value has exactly one owner, usually a variable, and when the owner is gone (at the end of its block), the value is thrown away. In code, the slip is a String, handing it over is a move, the photocopy is a clone, the number said out loud is a copy, and throwing the slip away at closing time is a drop.
The three ownership rules
- Every value has one owner, usually the variable that holds it. The items of a Vec and the fields of a struct are owned by that Vec or struct.
- At any one time there is only one owner.
- When the owner goes out of scope, the value is dropped (removed from memory).
A scope is the part of the code where a variable exists: from its let line to the closing curly brace } of its block. The borrow checker checks these three rules at compile time, so they cost nothing while the program runs.
Move: the owner changes
In the code below, the cashier hands the slip to the kitchen, then still tries to read it:
fn main() {
let slip = String::from("2x sweet pancake");
let kitchen = slip;
println!("Kitchen: {}", kitchen);
println!("Cashier: {}", slip);
}
error[E0382]: borrow of moved value: `slip`
--> src/main.rs:5:29
|
2 | let slip = String::from("2x sweet pancake");
| ---- move occurs because `slip` has type `String`, which does not implement the `Copy` trait
3 | let kitchen = slip;
| ---- value moved here
4 | println!("Kitchen: {}", kitchen);
5 | println!("Cashier: {}", slip);
| ^^^^ value borrowed here after move
|
help: consider cloning the value if the performance cost is acceptable
|
3 | let kitchen = slip.clone();
| ++++++++
There can be only one owner (rule 2), so let kitchen = slip; moves ownership to kitchen, and slip is no longer valid. If you still use slip, the compiler refuses. This is the same error you met in the first lesson, the String lesson and the Vec lesson. There you saw that a String moves. The next section explains why Rust moves it instead of copying it.
Stack, heap, and why a String moves
A program keeps data in two places. The stack is for values whose size is known at compile time. The stack is fast. The part of the stack a function uses is cleared automatically when that function ends. The heap is for data whose size can change while the program runs, like text that can grow. Space on the heap is requested (allocated) when it is needed, and must be given back when it is no longer needed.
The code below measures how many bytes each type takes on the stack with size_of. Then as_ptr() gives the address of the text's contents on the heap, and {:p} prints that address:
use std::mem::size_of;
fn main() {
let slip = String::from("2x sweet pancake");
println!("{} {}", slip.len(), slip.capacity());
println!("String: {}", size_of::<String>());
println!("Vec<u32>: {}", size_of::<Vec<u32>>());
println!("u32: {}", size_of::<u32>());
println!("&str: {}", size_of::<&str>());
println!("ptr: {:p}", slip.as_ptr());
let kitchen = slip;
println!("ptr: {:p}", kitchen.as_ptr());
let copy = kitchen.clone();
println!("ptr: {:p}", copy.as_ptr());
}
16 16
String: 24
Vec<u32>: 24
u32: 4
&str: 16
ptr: 0x105009f00
ptr: 0x105009f00
ptr: 0x105009f60
- On a 64-bit computer a
Stringis always 24 bytes on the stack. Inside are three 8-byte numbers: the pointer (the address of its contents on the heap), the length (len, 16) and the capacity (capacity, 16). The 16 characters of2x sweet pancakethemselves are on the heap. AVec<u32>is 24 bytes too, with the same three numbers. A&stris 16 bytes: only a pointer and a length, because a&strborrows text and can't grow it. - A
u32is just 4 bytes, right on the stack. Nothing on the heap. - The addresses (
{:p}) will differ on your computer and change on every run. What matters is the pattern:slipandkitchenpoint at the same address, whilecopypoints at a different one.
So a move copies just the 24 bytes on the stack, and the contents on the heap aren't touched. Imagine that slip and kitchen both stayed valid afterwards. When main ends, both would give back the same 16 heap bytes. This mistake is called a double free (the same memory given back twice). It is a bug that can corrupt memory, and it is a common security hole in C and C++. Rust prevents it with rule 2: after the move, only kitchen is the owner, only kitchen drops the contents, and slip may not be used.
Copy and clone
The code below copies a number with =, then copies a String with .clone():
fn main() {
let price: u32 = 32;
let copy = price;
println!("{} {}", price, copy);
let slip = String::from("2x sweet pancake");
let kitchen = slip.clone();
println!("Cashier: {}", slip);
println!("Kitchen: {}", kitchen);
}
32 32
Cashier: 2x sweet pancake
Kitchen: 2x sweet pancake
- Number types like
u32,i32andf64, and alsoboolandchar, have theCopytrait. Their whole contents live on the stack.let copy = price;copies its 4 bytes, andpricestays valid. There is no heap, so nothing can be thrown away twice. StringandVecdon't haveCopy..clone()makes a full copy: it requests new space on the heap and copies every byte (the address0x105009f60in the earlier output). The result is two owners and two contents, and each is dropped on its own.- A clone has a cost. For a 16-byte slip you won't notice it, but for a Vec of a million orders you will. Use a clone when you really need two copies. If you only need to read, there is a cheaper way in the borrowing lesson, the next lesson.
Ownership and functions
Giving a value without Copy, like a String, to a function as an argument is also a move. The function's parameter becomes its new owner:
fn cook(slip: String) {
println!("Cooked: {}", slip);
}
fn main() {
let slip = String::from("2x sweet pancake");
cook(slip);
println!("Cashier: {}", slip);
}
The last line is refused with borrow of moved value: `slip` , and the compiler adds the note consider changing this parameter type in function `cook` to borrow instead if owning the value isn't necessary. One way to use the slip again: the function (cook) gives the slip back, so ownership moves back:
fn cook(slip: String) -> String {
println!("Cooked: {}", slip);
slip
}
fn main() {
let slip = String::from("2x sweet pancake");
let slip = cook(slip);
println!("Back at the cashier: {}", slip);
}
The output is Cooked: 2x sweet pancake, then Back at the cashier: 2x sweet pancake. let slip = cook(slip); uses shadowing: the new slip receives the slip that comes back. Passing it back and forth like this soon becomes tiring. The usual way is to lend the slip without handing it over, with &slip. That is the subject of the next lesson: borrowing.
Drop: thrown away when the scope ends
The Drop trait adds code that runs when a value is thrown away. Below, that code prints a message, so we can see when each slip is thrown away. Rust calls the method drop automatically, so you never call it yourself.
struct Slip {
name: String,
}
impl Drop for Slip {
fn drop(&mut self) {
println!("Slip {} thrown away", self.name);
}
}
fn main() {
let sari = Slip { name: String::from("Sari") };
{
let budi = Slip { name: String::from("Budi") };
println!("Serving {}", budi.name);
}
let rina = Slip { name: String::from("Rina") };
println!("Serving {} and {}", sari.name, rina.name);
}
Sari's slip is made first, then Budi's slip inside a { } block, then Rina's slip. Each slip prints Slip ... thrown away when it is dropped. Before you look at the output, guess: in what order do the three messages appear?
Serving Budi
Slip Budi thrown away
Serving Sari and Rina
Slip Rina thrown away
Slip Sari thrown away
The order is Budi, then Rina, then Sari. budi is dropped as soon as its inner block closes with }, before Rina is even made. At the end of main, variables are dropped in reverse order of creation: rina (made last) first, and sari (made first) last. It is like a stack of plates: the plate put on last is taken off first. Suppose a function cook takes a Slip, and sari is moved into it with cook(sari). Then the message Slip Sari thrown away appears at the end of cook, not at the end of main, because the owner is now that function's parameter.
⚠️ Getting it wrong about who the owner is
- Using a variable after a move.
let kitchen = slip;orcook(slip), then usingslip: E0382borrow of moved value. - A move inside a loop.
let kitchen = slip;inside aforis refused withvalue moved here, in previous iteration of loop: the second round has no slip left. - Cloning everywhere so that the code compiles. It does compile, but every clone requests heap space and copies every byte. Usually all you need is a borrow (
&). - Thinking a u32 moves too.
Copytypes are copied, so the original stays valid. What moves are types withoutCopy, likeString,Vecand structs that contain them.
TL;DR: Every value has one owner, and when the owner leaves its scope (the code from let to the } that closes its block), the value is dropped (removed from memory). let kitchen = slip; and cook(slip) move ownership, so slip may not be used again (E0382). A move copies just the String's 24 bytes on the stack (memory for values of a fixed size): pointer (the address of its contents), len and capacity. Its contents on the heap (memory for data whose size can change) are not copied, and the one-owner rule is what prevents a double free (the same memory given back twice). Copy types like u32 (4 bytes, no heap) are copied, not moved. .clone() copies the heap contents too, so it has a cost. A function can give ownership back by returning the value. Drop happens automatically at the end of a scope, in reverse order of creation. Next: borrowing with & without moving.
⚡ One value, one owner
Write:
let slip = String::from("2x sweet pancake");
let kitchen = slip;
println!("Cashier: {}", slip); // error[E0382]
Meaning: Every value has one owner, usually the variable that holds it. let kitchen = slip; moves ownership to kitchen, so slip is no longer valid, and using slip is refused at compile time.
⚡ Why a String moves
Meaning: A String is 24 bytes on the stack (memory for values of a fixed size): the pointer (the address of its contents), len and capacity. The text itself is on the heap (memory for data whose size can change). A move copies just those 24 bytes, so the contents on the heap are not copied. Only one owner throws them away, so there is no double free (the same memory given back twice).
⚡ Copy and clone
Write:
let price: u32 = 32;
let copy = price; // price stays valid
let kitchen = slip.clone(); // slip stays valid
Meaning: u32 has the Copy trait: its 4 bytes are copied, with no heap, so price stays valid. .clone() makes a full copy of slip, its heap contents included, so it has a cost.
⚡ Thrown away when the scope ends
Guess first: each slip prints a thrown away message when it is removed from memory, that is, when the block where its variable was made ends. Sari's slip is made first, then Budi's inside a { } block, then Rina's. In what order do the thrown away messages appear?
Budi, Rina, then Sari. budi is dropped as soon as its { } block closes. At the end of main, the rest are dropped in reverse order of creation: Rina first, Sari last.
Meaning: A value is dropped (removed from memory) automatically when its owner leaves its scope, the part of the code where that owner exists. All of this happens with no garbage collector.