Vec at its real addresses; cargo; numbers that differ from Python; modules; fifteen real borrow-checker errors to practise on; the traps that cut across the language; and the map of the four child pages. Every output and compiler error is a real run (rustc 1.99.0, CPython 3.14.8) on an Apple M1 Pro. Data as of October 2026. Reading: 31 min, plus 11 in closed details.Every Rust value has exactly one owner, and the compiler checks every borrow of it before the program runs: nothing may use a value after its owner has freed it, or while someone else is changing it. So use after free, dangling references, iterator invalidation and data races become compile errors, with no garbage collector and no reference counts; the price is that you decide who owns what.
Fig. 1 follows one program, the root page's token counter, from cargo build to Python calling it, and pins each idea of the Rust pages where it acts. This page teaches the first four steps; each later step names the child page that owns it and links to that child's own figure.
lib.rs (8 lines) declares the modules tokenize.rs (44 lines) and tally.rs (53), main.rs (28) is the binary, and Cargo.toml names two dependencies, serde and serde_json. cargo run --release compiles them into one program (section 2; the module layout is section 6).gate_err.rs stops here with E0502 (it keeps a reference into a vector across a push); gate_fix.rs, which copies the number out instead, passes. None of this is checked again at run time (section 5 and its lab of fifteen real errors).Vec<u32> is a 24-byte header on the stack (pointer, capacity, length; the run printed size_of) and its elements in one heap block, here capacity 3. The header's owner is v; when v goes, the block goes.push on the full vector copied the elements into a new block of capacity 6 and freed the old one; let w = v copied only the 24-byte header to a new stack slot, the heap block stayed where it was, and v became unusable; drop(w) freed the block at that line. Fig. 2 in section 4 replays the run line by line, at every address it printed.Option<&u64> is 8 bytes, the same as the reference, because a reference is never null and the all-zero pattern is free to mean None; a trait object &dyn Tokenizer is a 16-byte fat pointer, one word to the value and one to its type's vtable. Owner: Rust: enums, traits, errors and iterators, whose enum figure and generic against trait object figure draw both.Rc keeps a count beside the value on the heap: three 8-byte handles, strong_count 3, and the value is freed when the count reaches 0. An Rc may not cross into another thread (E0277, "cannot be sent between threads safely"); Arc, whose count is updated atomically, may. Owner: Rust: lifetimes, smart pointers, threads and unsafe, with its Rc figure and threads figure..await, parks it there and takes another, so a few threads serve many tasks. In that child's 4-worker run, task A started on thread 3 and resumed on thread 5 at 103.8 ms, which is why a spawned task must be Send. Owner: Rust: async with tokio, services with axum, and CLIs, whose Fig. 1 draws the runtime.Vec<String> (72.7 ns per string) or borrowed as &str views into the Python objects (9.4 ns), as measured there. Owner: Rust: speeding up Python with PyO3 and maturin, whose Fig. 2 sends one call across.unsafe: the lifetimes child. Tasks and services: the async child. Python: the PyO3 child. Section 9 has the cards.You need: everyday Python. Nothing else: this page starts from zero for a Python programmer, and the four child pages assume it. If you know C++, section 8 maps its ownership onto Rust's.
Copy, clone()bool) are copied bit for bit; clone() is the explicit deep copy of anything else.&T, &mut TRust is the language under much of the Python tooling you already use (uv, ruff, ty, pydantic-core, Hugging Face tokenizers, polars). Python gets memory safety from reference counting and a garbage collector at run time; C++ trusts you. Rust checks a set of rules at compile time and then runs with no collector at all. Everything else follows from that:
| In Python | In Rust | Why Rust does it this way | Where |
|---|---|---|---|
python app.py, pip or uv for packages | cargo builds, runs, tests, lints and fetches packages ("crates") in one tool | A compiled language needs a build; one standard tool means every project looks the same | 2 |
| Any variable can be rebound or changed | Variables are immutable unless declared mut; integers have fixed widths and overflow is checked | Changes are visible in the code; the machine's real number types | 3 |
b = a adds a second name for one object | let b = a; moves it: a may not be used again | One owner means the compiler always knows who frees it, and when | 4 |
| Any number of names may read and change an object | Borrowing: many readers (&T) or one writer (&mut T), never both at once | Rules out dangling references, iterator invalidation and data races at compile time | 5; lifetimes: lifetimes child |
None anywhere; exceptions for errors | Option<T> and Result<T, E> are ordinary values you must handle; ? passes errors up | The type says what can be missing or fail, and the compiler checks you handled it | enums child |
| Duck typing, Protocols, classes with inheritance | Traits and generics, compiled to one specialised copy per type; no inheritance | Abstraction that costs nothing at run time | enums child |
| Threads share everything; the GIL (or locks) keeps it sane | The type system knows what may cross threads (Send, Sync); a data race does not compile | "Fearless concurrency": the checks of section 5 extended to threads | lifetimes child |
The rule you will meet most, in one line, from the Rust Book: "At any given time, you can have either one mutable reference or any number of immutable references." The root page shows it on one example (Topic: programming-languages, Reading sections 4 and 5); sections 4 and 5 here teach it, and the Borrow-checker lab in section 5 lets you practise on fifteen real compiler errors.
| Finding | Where |
|---|---|
| A while loop, a for loop, an iterator chain and a generic closure all compiled to the same speed, about 0.29 ns per element; CPython took 71.4 ns for the same loop. | Rust: enums, traits, errors and iterators, section 5 |
| Moving only the counting into Rust took the root's token counter from 1.358 s to 0.466 s; moving the JSON parsing too took it to 0.112 s, and releasing the GIL with 8 threads to 0.059 s (23 times faster). Port the whole pipeline, not one function. | Rust: speeding up Python with PyO3 and maturin, section 10 |
On free-threaded 3.14t, a Rust class with a &mut self method shared by 8 threads raised "Already borrowed" on 13% of calls; a frozen class with a Mutex fixes it. | The same child, section 9 |
| The same service in axum and FastAPI (4 workers each): 4,804 against 206 requests/s counting a 391 KB log, and 27 against 281 MB of memory. | Rust: async with tokio, services with axum, and CLIs, "Measured" |
CPU work inside an async handler slowed every other request (/health median 10.7 ms); moving it to spawn_blocking brought it back to 0.44 ms. | The same child, "Blocking the runtime" |
How to read the code on this page: each block is a file in this page's src/ra/code/, then the command that ran and its real output (green border) or error (orange border). Dashed boxes are predictions: guess, then open. Every program was compiled with rustc 1.99.0 (edition 2024) and run on an Apple M1 Pro (macOS 27) on 2026-10-05; the children's runs also used PyO3 0.29.3, tokio 1.53.2, axum 0.8.9 and clap 4.6.7.
Rust is compiled: rustc, the compiler, turns source files into a machine-code program before anything runs. You rarely call it yourself. Cargo is the build tool and package manager: it creates projects, downloads dependencies, calls rustc, runs tests and lints. A package of Rust code is a crate; the public registry is crates.io. Toolchains are installed and updated by rustup (here the stable 1.99.0 of 2026-10-01; a new stable ships every six weeks, RELEASES.md).
cargo new on 1.99.0 writes edition = "2024", below.
$ cargo new hello && cd hello && find . -not -path "./.git/*" -not -name .git | sort && cat Cargo.toml && cat src/main.rs
Creating binary (application) `hello` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
.
./.gitignore
./Cargo.toml
./src
./src/main.rs
[package]
name = "hello"
version = "0.1.0"
edition = "2024"
[dependencies]
fn main() {
println!("Hello, world!");
}
Cargo.toml plays the role of pyproject.toml. edition = "2024" picks the language edition: editions let Rust make small incompatible changes every few years while crates of different editions still link together (2024 has been stable since 1.85.0, Edition Guide). cargo run compiles and runs:
$ cargo run
Compiling hello v0.1.0 (hello)
Finished `dev` profile [unoptimized + debuginfo] target(s) in <time>
Running `target/debug/hello`
Hello, world!
"dev profile, unoptimized + debuginfo" is a debug build: fast to compile, slow to run, with extra checks (section 3). Always measure with cargo run --release, which turns the optimiser on; the enums child measures what the optimiser does to a loop.
| Command | What it does | Python equivalent |
|---|---|---|
cargo new name | new project (add --lib for a library) | uv init |
cargo add serde | add a dependency to Cargo.toml | uv add |
cargo check | type-check and borrow-check without producing a program (the fastest feedback) | mypy, ty |
cargo build / cargo run (--release) | compile / compile and run | python app.py |
cargo test | unit, integration and documentation tests (the enums child, section 7) | pytest |
cargo clippy | the linter: hundreds of lints, many teaching idioms | ruff check |
cargo fmt | the formatter (there is one style) | ruff format |
cargo doc --open | HTML docs for your crate and every dependency | (none built in) |
Clippy is the fastest way to learn idioms. On a correct program written the way a Python programmer first writes it, it warned five times, and each warning is a lesson: borrow a slice &[u64] rather than &Vec<u64>, iterate instead of indexing, write +=, test is_empty() rather than a length against zero, and the last expression of a block is its value so return is unneeded (section 3). cargo clippy --fix applies the mechanical ones (3 of the 5 here).
// Compiles and runs, but clippy has opinions: each one teaches an idiom. fn total(v: &Vec<u64>) -> u64 { let mut sum = 0; for i in 0..v.len() { sum = sum + v[i]; } return sum; } fn main() { let v = vec![3, 4, 5]; let empty = v.len() == 0; println!("total {} empty {}", total(&v), empty); }
$ cargo clippy
Checking clip v0.1.0 (clip)
warning: unneeded `return` statement
--> src/main.rs:7:5
|
7 | return sum;
| ^^^^^^^^^^
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.99.0/index.html#needless_return
= note: `#[warn(clippy::needless_return)]` on by default
help: remove `return`
|
7 - return sum;
7 + sum
|
warning: writing `&Vec` instead of `&[_]` involves a new object where a slice will do
--> src/main.rs:2:13
|
2 | fn total(v: &Vec<u64>) -> u64 {
| ^^^^^^^^^
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.99.0/index.html#ptr_arg
= note: `#[warn(clippy::ptr_arg)]` on by default
help: change this to
|
2 - fn total(v: &Vec<u64>) -> u64 {
2 + fn total(v: &[u64]) -> u64 {
|
warning: the loop variable `i` is only used to index `v`
--> src/main.rs:4:14
|
4 | for i in 0..v.len() {
| ^^^^^^^^^^
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.99.0/index.html#needless_range_loop
= note: `#[warn(clippy::needless_range_loop)]` on by default
help: consider using an iterator
|
4 - for i in 0..v.len() {
4 + for <item> in &v {
|
warning: manual implementation of an assign operation
--> src/main.rs:5:9
|
5 | sum = sum + v[i];
| ^^^^^^^^^^^^^^^^ help: replace it with: `sum += v[i]`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.99.0/index.html#assign_op_pattern
= note: `#[warn(clippy::assign_op_pattern)]` on by default
warning: length comparison to zero
--> src/main.rs:12:17
|
12 | let empty = v.len() == 0;
| ^^^^^^^^^^^^ help: using `is_empty` is clearer and more explicit: `v.is_empty()`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.99.0/index.html#len_zero
= note: `#[warn(clippy::len_zero)]` on by default
warning: `clip` (bin "clip") generated 5 warnings (run `cargo clippy --fix --bin "clip" -p clip -- ` to apply 3 suggestions)
Finished `dev` profile [unoptimized + debuginfo] target(s) in <time>Cargo.lock pins the exact versions resolved, like uv.lock, and the version rules differ from pip's in one way that bites: for a 0.x crate the minor number is the breaking one.
Cargo.toml lists dependencies with version requirements; Cargo.lock pins the exact versions resolved, like uv.lock. Commit it.serde = "1.0" means "compatible with 1.0": any 1.x. For 0.x versions the minor number is the breaking one: "0.14" accepts 0.14.9 but not 0.15.0 (Cargo book, SemVer compatibility). Much of the ecosystem is at 0.x, so this matters.rand 0.8 and 0.9). That avoids dependency deadlock, at the cost of a confusing error: two types with the same name that are not the same type.serde = { version = "1", features = ["derive"] }. They are unified: if any crate in the build turns one on, everyone gets it.build.rs) and procedural macros run code at build time, the same trust question as a Python package's setup code. cargo audit checks the lock file against the RustSec advisory database.fn main() { let x = 5; // immutable by default let mut y = 5; // `mut` makes it changeable y += 1; let spaces = " "; // shadowing: a new variable with the same name... let spaces = spaces.len(); // ...may even have a different type const MAX_TOKENS: u32 = 4_096; // a compile-time constant, type required println!("x={x} y={y} spaces={spaces} max={MAX_TOKENS}"); let z; // declared now, assigned once later if y > 5 { z = "big" } else { z = "small" } println!("z={z}"); }
$ rustc --edition 2024 vars.rs && ./vars
x=5 y=6 spaces=3 max=4096
z=big
let introduces a variable. Its type is inferred from use, like Python, but fixed at compile time: y is an i32 (the default integer type) forever.let mut.
$ rustc --edition 2024 vars_err.rs
error[E0384]: cannot assign twice to immutable variable `count`
--> vars_err.rs:3:5
|
2 | let count = 0;
| ----- first assignment to `count`
3 | count += 1;
| ^^^^^^^^^^ cannot assign twice to immutable variable
|
help: consider making this binding mutable
|
2 | let mut count = 0;
| +++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0384`.
[exit code 1]That error has the shape of every Rust error: a code (E0384; rustc --explain E0384 prints a page about it), the file and line, the source with labels under the relevant spans, and usually a help with the fix (+++ marks inserted text).
let spaces makes a new variable that hides the old one, even with a new type. Useful for "parse this string into a number and keep the name"; it is not mutation.if, match and blocks { ... } produce values. A block's value is its last expression without a semicolon, which is why functions end in sum rather than return sum;.println! ends in ! because it is a macro: code that writes code at compile time. {x} in the format string is like an f-string; {:?} prints the debug form (like repr), {:#?} pretty-prints it.Python's int grows as needed. Rust's integers are the machine's: i8 i16 i32 i64 i128 (signed) and u8 ... u128 (unsigned), plus usize/isize, the pointer-sized types used for lengths and indexes (64 bits here). Floats are f32 and f64. Nothing converts implicitly, not even u32 to f64:
u32 * f64
$ rustc --edition 2024 mix_err.rs
error[E0277]: cannot multiply `u32` by `f64`
--> mix_err.rs:4:27
|
4 | println!("{}", tokens * ratio);
| ^ no implementation for `u32 * f64`
|
= help: the trait `Mul<f64>` is not implemented for `u32`
= help: the following other types implement trait `Mul<Rhs>`:
`&u32` implements `Mul<u32>`
`&u32` implements `Mul`
`u32` implements `Mul<&u32>`
`u32` implements `Mul<Duration>`
`u32` implements `Mul`
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0277`.
[exit code 1]That is E0277, "cannot multiply u32 by f64". The fix is an explicit conversion: tokens as f64 * ratio, or f64::from(tokens). Before reading on, predict what three translations of one line of Python do:
print(2 ** 64)
$ python3.14 d12.py
18446744073709551616fn main() { let base: u64 = std::env::args().count() as u64 + 1; // 2, read at run time println!("{}", base.pow(64)); }
fn main() { println!("{}", 2u64.wrapping_pow(64)); }
fn main() { println!("{}", 2u128.pow(64)); }
u64 (max 264 minus 1): a debug build panics.
$ rustc --edition 2024 d12_a.rs && ./d12_a
thread 'main' (16606907) panicked at /rustc/b940084d7eb6a299eb4bfeb8e34901bc051e7ac4/library/core/src/num/mod.rs:1322:5:
attempt to exponentiate with overflow
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
[exit code 101]
$ rustc --edition 2024 d12_b.rs && ./d12_b
0u128 holds it. Python's int is unbounded; Rust's integers are fixed-width, so you choose a width that fits.
$ rustc --edition 2024 d12_c.rs && ./d12_c
18446744073709551616What happens at the edge of a type's range:
fn main() { // read the value at run time so the compiler cannot see the overflow coming let x: u8 = std::env::args().nth(1).unwrap().parse().unwrap(); println!("checked_add: {:?}", x.checked_add(1)); println!("wrapping_add: {}", x.wrapping_add(1)); println!("saturating_add: {}", x.saturating_add(1)); println!("overflowing_add:{:?}", x.overflowing_add(1)); let y = x + 1; // plain +: panics in a debug build, wraps in a release build println!("x + 1 = {y}"); }
./overflow 255 print on its last line?
$ rustc --edition 2024 overflow.rs && ./overflow 254 && ./overflow 255
checked_add: Some(255)
wrapping_add: 255
saturating_add: 255
overflowing_add:(255, false)
x + 1 = 255
checked_add: None
wrapping_add: 0
saturating_add: 255
overflowing_add:(0, true)
thread 'main' (16488861) panicked at overflow.rs:8:13:
attempt to add with overflow
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
[exit code 101]-O)?
$ rustc --edition 2024 -O overflow.rs && ./overflow 255
checked_add: None
wrapping_add: 0
saturating_add: 255
overflowing_add:(0, true)
x + 1 = 0This is the documented rule (Rust Book 3.2, Integer Overflow): debug builds check and panic; release builds wrap with two's complement and "relying on integer overflow's wrapping behavior is considered an error". When overflow is possible, say what you want: checked_* (an Option), wrapping_*, saturating_* or overflowing_*. A panic is Rust's crash for bugs: it prints the message and location, unwinds the thread and exits with code 101. If the compiler can see the overflow (255 + 1 as a u8), it refuses outright: "this arithmetic operation will overflow".
$ rustc --edition 2024 overflow_const.rs
error: this arithmetic operation will overflow
--> overflow_const.rs:2:17
|
2 | let x: u8 = 255 + 1;
| ^^^^^^^ attempt to compute `u8::MAX + 1_u8`, which would overflow
|
= note: `#[deny(arithmetic_overflow)]` on by default
error: aborting due to 1 previous error
[exit code 1]Division is the other arithmetic surprise. Predict again:
print(-7 // 2)
$ python3.14 d03.py
-4fn main() { println!("{}", -7 / 2); }
fn main() { println!("{}", ((-7 / 2) as f64).floor()); }
fn main() { println!("{}", (-7i32).div_euclid(2)); }
/ on integers truncates toward zero: -3.
$ rustc --edition 2024 d03_a.rs && ./d03_a
-3-7 / 2; flooring -3.0 changes nothing.
$ rustc --edition 2024 d03_b.rs && ./d03_b
-3div_euclid rounds so that the remainder is never negative, which for a positive divisor is Python's //.
$ rustc --edition 2024 d03_c.rs && ./d03_c
-4The arithmetic differences that bite Python programmers:
/ truncates toward zero (-7 / 2 is -3, Python's // gives -4); div_euclid and rem_euclid give Python's answers for positive divisors.as never fails: it truncates integers (300 as u8 is 44), reinterprets signs (-1 as u32 is 4294967295), and saturates float to integer (not-a-number becomes 0). Use TryFrom when a value might not fit.0.1 + 0.2 prints the same.
$ rustc --edition 2024 numbers.rs && ./numbers
i32 range -2147483648 .. 2147483647
u64::MAX 18446744073709551615
-7 / 2 -3
-7 % 2 -1
(-7i32).div_euclid(2) -4
(-7i32).rem_euclid(2) 1
7 / 2 3
7.0 / 2.0 3.5
0.1 + 0.2 0.30000000000000004
300i32 as u8 44
-1i32 as u32 4294967295
3.99f64 as i32 3
1e20f64 as i32 2147483647
f64::NAN as i32 0
u8::try_from(300i32) Err(TryFromIntError(PosOverflow))
usize bits 64
2u64.pow(40) 1099511627776
n as f64 / 2.0 1.5
$ python3.14 numbers.py
-7 // 2 -4
-7 % 2 1
int(-3.5) -3
7 / 2 3.5
0.1 + 0.2 0.30000000000000004
2**64 18446744073709551616
255 + 1 256// Prints the real addresses behind the ownership animation: a Vec is three // machine words on the stack (pointer, capacity, length) and a buffer on the heap. fn show(step: &str, name: &str, v: &Vec<u32>) { println!( "{step} {name} stack={:p} heap={:p} len={} cap={} data={:?}", v as *const Vec<u32>, v.as_ptr(), v.len(), v.capacity(), v ); } fn main() { println!("size_of::<Vec<u32>>() = {}", std::mem::size_of::<Vec<u32>>()); let mut v: Vec<u32> = Vec::with_capacity(3); v.extend([10, 20, 30]); show("1", "v", &v); let r = &v; // a shared borrow: a pointer to v's stack slot println!("2 r points to {:p} (v's stack slot), r.len()={}", r as *const Vec<u32>, r.len()); v.push(40); // r is no longer used, so v may be mutated: the buffer is full, so it grows show("3", "v", &v); let m = &mut v; // one exclusive borrow m[0] = 11; println!("4 m points to {:p}, wrote m[0]=11", m as *const Vec<u32>); let w = v; // move: the three words are copied to w's slot, the heap buffer is not touched show("5", "w", &w); let c = w.clone(); // clone: a new heap buffer with a copy of the elements show("6", "c", &c); drop(w); // w's buffer is freed now println!("7 dropped w"); show("8", "c", &c); }
$ rustc --edition 2024 own_anim.rs && ./own_anim
size_of::<Vec<u32>>() = 24
1 v stack=0x16da0a2a8 heap=0x102d3d4a0 len=3 cap=3 data=[10, 20, 30]
2 r points to 0x16da0a2a8 (v's stack slot), r.len()=3
3 v stack=0x16da0a2a8 heap=0x102d3d510 len=4 cap=6 data=[10, 20, 30, 40]
4 m points to 0x16da0a2a8, wrote m[0]=11
5 w stack=0x16da0a350 heap=0x102d3d510 len=4 cap=6 data=[11, 20, 30, 40]
6 c stack=0x16da0a368 heap=0x102d3d4a0 len=4 cap=4 data=[11, 20, 30, 40]
7 dropped w
8 c stack=0x16da0a368 heap=0x102d3d4a0 len=4 cap=4 data=[11, 20, 30, 40]
# The same steps in Python: names point at objects; nothing is moved. import sys v = [10, 20, 30] print("1 v id=%#x refcount=%d len=%d" % (id(v), sys.getrefcount(v) - 1, len(v))) r = v print("2 r id=%#x (same object) refcount=%d" % (id(r), sys.getrefcount(v) - 1)) v.append(40) print("3 v id=%#x r sees %s" % (id(v), r)) m = v m[0] = 11 print("4 m id=%#x refcount=%d v=%s" % (id(m), sys.getrefcount(v) - 1, v)) w = v print("5 w id=%#x refcount=%d (v still usable: %s)" % (id(w), sys.getrefcount(v) - 1, v)) c = w.copy() print("6 c id=%#x (new object) refcount=%d" % (id(c), sys.getrefcount(c) - 1)) del w print("7 del w: object still alive, refcount=%d (v, r, m remain)" % (sys.getrefcount(v) - 1)) print("8 c=%s v=%s" % (c, v))
$ python3.14 own_anim.py
1 v id=0x105e26140 refcount=1 len=3
2 r id=0x105e26140 (same object) refcount=2
3 v id=0x105e26140 r sees [10, 20, 30, 40]
4 m id=0x105e26140 refcount=3 v=[11, 20, 30, 40]
5 w id=0x105e26140 refcount=4 (v still usable: [11, 20, 30, 40])
6 c id=0x10a8842c0 (new object) refcount=1
7 del w: object still alive, refcount=3 (v, r, m remain)
8 c=[11, 20, 30, 40] v=[11, 20, 30, 40]
First, where values live. Each function call gets a stack frame, a block of memory for its local variables, released automatically when the function returns. Data whose size is only known at run time (a growing vector, a string read from a file) goes on the heap, which someone must release explicitly. A Rust String or Vec is a small fixed-size header on the stack (three machine words: a pointer to the heap buffer, the capacity, the length; 24 bytes) plus a buffer on the heap. Python hides all of this: every object is on the heap and names are references to it.
Fig. 2 is one small program, stepped line by line; every address and number in it was printed by the program itself when it ran (rustc 1.99.0), and the counters under it keep the score: allocations, live blocks, bytes copied by moves, elements copied. Predict first: after let w = v;, which address changes, the stack slot or the heap block? Switch the figure to Python for the same steps in Python's model: names pointing at one object, and a reference count.
Vec with capacity 3 holds 10, 20, 30. Its header is on the stack at 0x16da0a2a8; the elements are in one heap block at 0x102d3d4a0.r = &v is just an 8-byte pointer to v's stack slot (the run printed 0x16da0a2a8, the same address as v).push(40) on a full vector allocated a new block (capacity 3 to 6) at 0x102d3d510, copied the elements and freed the old one. r pointed at the header and is not used again, so this was allowed; a reference into the buffer (like &v[0]) would now point at freed memory, which is exactly why the borrow checker refuses a reference into the buffer across a push (section 5).m = &mut v is an exclusive borrow: while m is in use nobody else may read or write v. m[0] = 11 writes into the heap block through it.let w = v copies the header to w's slot (0x16da0a350); the heap block is untouched and still at 0x102d3d510. v is now unusable: any use is a compile error.c = w.clone() is a deep copy with its own block (4 slots, at 0x102d3d4a0). On this run the allocator handed it the block freed at step 3. Reusing freed memory is normal, and is why a dangling pointer can read someone else's data in C++.drop(w) releases the second block now, at a line you can point to. No garbage collector, no reference count.c is still valid and owns its own block.c goes out of scope at the end of main and its block is freed: not printed, because this is the drop the compiler inserts.v = [10, 20, 30]: the name v points at one list object on the heap (id 0x105e26140), reference count 1.r = v names the same object; the count becomes 2. Python never copies on assignment.v.append(40): the list grows in place (its internal pointer array may move, the object does not), and r sees the change.m = v; m[0] = 11: a third name; a change through any of them is visible through all. Count 3.w = v: a fourth name, and the count rises to 4; v stays usable.c = w.copy() is the only allocation after the first (id 0x10a8842c0).del w removes a name, not the object: the count drops to 3 and the list lives on.The ownership rules (Rust Book 4.1): each value has one owner (a variable, a field, a vector slot); when the owner goes out of scope the value is dropped (its heap memory freed); assigning or passing a value moves ownership.
fn shout(s: String) -> String { // takes ownership of s; returns ownership of a new String s.to_uppercase() } fn main() { let a = String::from("hello"); let b = a; // move: b now owns the heap buffer println!("b = {b}"); let c = b.clone(); // explicit deep copy: a second heap buffer let d = shout(b); // b moves into the function println!("c = {c}, d = {d}"); let n = 5; // i32 is Copy: assignment copies the bits let m = n; println!("n = {n}, m = {m}"); // both still usable }
$ rustc --edition 2024 move.rs && ./move
b = hello
c = hello, d = HELLO
n = 5, m = 5
After let b = a; the 24-byte header was copied into b and a became unusable. The heap buffer was not copied and not freed: it now has exactly one owner again. Using a afterwards is refused with E0382, "borrow of moved value: a", and the error names the cause: String does not implement the Copy trait.
$ rustc --edition 2024 move_err.rs
error[E0382]: borrow of moved value: `a`
--> move_err.rs:4:16
|
2 | let a = String::from("hello");
| - move occurs because `a` has type `String`, which does not implement the `Copy` trait
3 | let b = a;
| - value moved here
4 | println!("{a} {b}");
| ^ value borrowed here after move
|
help: consider cloning the value if the performance cost is acceptable
|
3 | let b = a.clone();
| ++++++++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0382`.
[exit code 1]b = a makes two names for one object, kept alive by a reference count. Rust refuses the second name, so it never needs a count: the single owner frees the buffer at a point the compiler knows. Think of a move as handing over the only key.Copy types (integers, floats, bool, char, and tuples or arrays of them) have no heap part, so assignment copies the bits and both stay usable (n and m above).clone() is the explicit deep copy: a second heap buffer. It is visible in the code on purpose, so you can see every place that copies data.shout(b)); returning moves ownership back out.A type can run code when it is dropped by implementing the Drop trait, which is how files close, locks release and buffers free themselves. There is no garbage collector, so the order is fixed:
struct Noisy(&'static str); impl Drop for Noisy { fn drop(&mut self) { println!("drop {}", self.0); } } fn consume(n: Noisy) { println!("consume got {}", n.0); } // n is dropped here, at the end of the function that owns it fn main() { let _a = Noisy("a"); let b = Noisy("b"); { let _c = Noisy("c"); println!("inner scope ends"); } // c dropped here consume(b); // b moved into consume; dropped inside it let _d = Noisy("d"); println!("main ends"); } // locals dropped in reverse order of declaration: d, then a
drop lines printed?
$ rustc --edition 2024 drop.rs && ./drop
inner scope ends
drop c
consume got b
drop b
main ends
drop d
drop aLocals drop at the end of their scope in reverse order of declaration; a value moved into a function drops at the end of that function. This is C++'s RAII (resource acquisition is initialisation) made the default; Python's equivalent is with, which you have to remember to write.
Rc, Arc: the lifetimes child, section 2)..clone() until it compiles. Fine for small values; in a hot loop it allocates on every iteration. Borrow first.The Python habit that a move breaks first, as a prediction:
a = [1, 2]
b = a
b.append(3)
print(a)
$ python3.14 d02.py
[1, 2, 3]fn main() { let a = vec![1, 2]; let mut b = a; b.push(3); println!("{a:?}"); }
fn main() { let a = vec![1, 2]; let mut b = a.clone(); b.push(3); println!("{a:?}"); }
fn main() { let mut a = vec![1, 2]; let b = &mut a; b.push(3); println!("{a:?}"); }
let mut b = a moves the vector; a is dead: E0382.
$ rustc --edition 2024 d02_a.rs && ./d02_a
error[E0382]: borrow of moved value: `a`
--> d02_a.rs:5:16
|
2 | let a = vec![1, 2];
| - move occurs because `a` has type `Vec<i32>`, which does not implement the `Copy` trait
3 | let mut b = a;
| - value moved here
4 | b.push(3);
5 | println!("{a:?}");
| ^ value borrowed here after move
|
help: consider cloning the value if the performance cost is acceptable
|
3 | let mut b = a.clone();
| ++++++++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0382`.
[exit code 1]clone made a second vector, so a is unchanged: [1, 2].
$ rustc --edition 2024 d02_b.rs && ./d02_b
[1, 2]a may be read again.
$ rustc --edition 2024 d02_c.rs && ./d02_c
[1, 2, 3]&v aliveexclusive borrow &mut v (push)conflictMoving everything everywhere would be unbearable, so you lend a value instead: a reference &v borrows it without taking ownership. Two kinds:
&T, a shared reference: read only; any number at once.&mut T, an exclusive (mutable) reference: may change the value; while it is in use, no other reference to that value may be.fn total(v: &[u64]) -> u64 { // borrows: reads, does not own v.iter().sum() } fn add_one(v: &mut Vec<u64>) { // borrows exclusively: may change it v.push(1); } fn main() { let mut v = vec![3, 4, 5]; let a = &v; // any number of shared borrows at once let b = &v; println!("{} {}", total(a), total(b)); add_one(&mut v); // a and b are no longer used, so this is allowed println!("{:?} total {}", v, total(&v)); }
$ rustc --edition 2024 borrow.rs && ./borrow
12 12
[3, 4, 5, 1] total 13
The part of the compiler that enforces this is the borrow checker. A borrow lasts from where it is created to its last use, not to the end of the block (the Book: "a reference's scope starts from where it is introduced and continues through the last time that reference is used"). That is why add_one(&mut v) is accepted above: a and b are never used again.
The old page's "gate" question: why does this fail to compile?
fn main() { let mut v = vec![1]; let first = &v[0]; v.push(2); println!("{first}"); }
$ rustc --edition 2024 gate_err.rs
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
--> gate_err.rs:4:5
|
3 | let first = &v[0];
| - immutable borrow occurs here
4 | v.push(2);
| ^^^^^^^^^ mutable borrow occurs here
5 | println!("{first}");
| ----- immutable borrow later used here
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0502`.
[exit code 1]
first points into the vector's heap buffer. push may find the buffer full, allocate a bigger one, copy the elements and free the old one (step 3 of Fig. 2); first would then point at freed memory. In C++ the same code compiles and reads freed memory (the root page runs it: Reading section 5).
Predict first: which of the three versions in Fig. 3 compile? Each bar runs from a borrow's creation to its last use, and red is an overlap; the steps walk the program one line at a time and end with what the compiler said.
main starts.v owns a vector with one element.first borrows v (shared, blue). The borrow lives until first is last used.push needs &mut v (orange) while the blue borrow is still alive (it is used on line 5): the bars overlap.v goes out of scope and its buffer is freed.main starts.v owns a vector with one element.first borrows v (shared, blue).first is used for the last time: the blue borrow ends here.push takes &mut v; no other borrow is alive, so it is allowed.v borrows it again briefly.v goes out of scope and its buffer is freed.main starts.v owns a vector with one element.v[0] is an i32, which is Copy: first is a copy of the number, not a borrow.push takes &mut v; nothing else borrows v.first is an independent number; the vector may have moved, it does not matter.v goes out of scope and its buffer is freed.Two fixes, both recorded: use the reference before mutating (its last use moves up, so the bars no longer overlap), or copy the i32 out (no borrow at all). Both are what you would do in Python if you knew the list might move. When a borrow must outlive one function, the span becomes a lifetime: the lifetimes child draws it in its lifetimes figure.
error[E0502], "cannot borrow v as mutable because it is also borrowed as immutable") say which rule broke; --> gate_err.rs:4:5 is the file, line and column of the main conflict.^^^ span), and where the first borrow is later used. That third label is the key: it is the reason the first borrow is still alive.help: lines often propose one, as a concrete edit (+++ marks inserted text, ~ changed lines); they are usually right for the code as written, and not always right for your design.rustc --explain E0502 prints a full explanation with examples (also online in the error code index).Fig. 4 is the practice ground: pick a scenario, decide what you think happens, then reveal the real rustc 1.99.0 output, how to read it, and the fix. Fourteen are refused at compile time (one of them wrongly: the code is safe), and one compiles and fails at run time. The lifetime, thread and RefCell scenarios are taught in depth on the lifetimes child.
Rc and RefCell.Score: 0 of 0 predicted right in this visit. Sources: every file is in src/ra/code/bc/ and every output in src/ra/out/, recorded by src/ra/run_all.sh.
cargo new makes (one Cargo.toml); it contains a library crate (src/lib.rs), and/or one or more binary crates (src/main.rs, src/bin/*.rs). A crate is the unit the compiler builds at once.mod tokenize; in lib.rs loads src/tokenize.rs. Paths use :: (crate::tokenize::count_tokens); use imports a name, like Python's from x import y.pub exports it; pub(crate) exports it within the crate only. Python's leading underscore is a convention; this is enforced: calling a private tokenizer::split from outside its module is E0603, "function split is private".mod tokenizer { pub fn count(text: &str) -> usize { split(text).len() } fn split(text: &str) -> Vec<&str> { text.split_whitespace().collect() } } fn main() { println!("{}", tokenizer::count("a b c")); println!("{:?}", tokenizer::split("a b c")); }
$ rustc --edition 2024 modvis_err.rs
error[E0603]: function `split` is private
--> modvis_err.rs:12:33
|
12 | println!("{:?}", tokenizer::split("a b c"));
| ^^^^^ private function
|
note: the function `split` is defined here
--> modvis_err.rs:5:5
|
5 | fn split(text: &str) -> Vec<&str> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0603`.
[exit code 1]The root page's running program (count tokens per user in a JSONL chat log, the Rosetta tab of Topic: programming-languages) is reorganised here as a library with two modules (tokenize, tally) and a thin binary on top, the shape most Rust projects take, so the logic can be tested and reused (the PyO3 child turns the same functions into a Python extension):
$ cargo run -q --release -- ../chat.jsonl
lines 2000 ok 1992 malformed 8 (first at line 53)
users 176 tokens 44698
top 5 users by tokens:
1. u0029 9491
2. u0005 4816
3. u0042 3499
4. u0169 2291
5. u0121 1401
The output matches the root's specification exactly (2000 lines, 8 malformed, u0029 first with 9491). per_user has no pub, so code outside tally can only read the totals through the methods: the invariant "totals are only changed by add_line" is enforced by the compiler.
lib.rs, main.rs and tally.rs//! Count tokens per user in a JSONL chat log (the root page's running program), //! split into modules so that each part can be tested on its own. pub mod tally; pub mod tokenize; // Re-export: users of the crate write tokstat::count_tokens. pub use tokenize::count_tokens;
use std::io::{BufRead, BufReader}; use std::process::ExitCode; use tokstat::tally::Tally; fn main() -> ExitCode { let path = std::env::args().nth(1).unwrap_or_else(|| "chat.jsonl".to_string()); let file = match std::fs::File::open(&path) { Ok(f) => f, Err(e) => { eprintln!("error: cannot open {path}: {e}"); return ExitCode::from(1); } }; let mut t = Tally::default(); for line in BufReader::new(file).lines() { match line { Ok(l) => t.add_line(&l), Err(_) => t.add_line(""), // unreadable bytes count as malformed } }
//! Per-user totals. use crate::tokenize::count_tokens; use serde::Deserialize; use std::collections::HashMap; #[derive(Deserialize)] struct Message { user: String, text: String, } /// The result of reading a log. #[derive(Debug, Default)] pub struct Tally { pub lines: u64, pub ok: u64, pub malformed: u64, pub first_bad: Option<u64>, per_user: HashMap<String, u64>, // private field: only this module can touch it } impl Tally { /// Feed one line of the log. pub fn add_line(&mut self, line: &str) { self.lines += 1;
Each row is a Python habit that compiles, or nearly, and then costs you; the last column is where the mechanism is taught.
| Trap | What happens | The habit instead | Taught on |
|---|---|---|---|
| Cloning until it compiles. | Each clone() of a String or Vec allocates and copies. | Ask first whether the callee could borrow (&str, &[T]), whether the value could move, or whether its last use could come earlier. Clone small things freely; never in a hot loop without a reason. | sections 4 and 5 |
Rc<RefCell<T>> everywhere to recreate Python's object graph. | It compiles and then panics at run time (lab scenario 15). | Give the data one owner (often a struct holding Vecs) and refer to items by index. | lifetimes child, section 2 |
| Lifetimes in every struct. | The lifetime parameter spreads to every type that holds the struct (lab scenario 13). | Store owned data first; borrow in structs only when a profile says the copies matter. | lifetimes child, section 1 |
&String or &Vec<T> parameters. | Fewer callers can use the function. | Take &str and &[T]: they accept more callers and are what clippy suggests (section 2). | enums child, section 1 |
| Byte indexes on text. | s.len() is bytes and &s[0..n] panics inside a character. | Use chars(), char_indices(), or a byte-level algorithm on purpose (the token counter works on bytes because tokens are ASCII). | enums child, section 1 |
unwrap() in library code. | A panic where the caller could have handled an error. | Return Result and use ?; reserve expect("reason") for states you can prove impossible. | enums child, section 3 |
Expecting dict order from HashMap. | Its order changes between runs. | Sort, or use BTreeMap, or a Vec of pairs. | enums child, section 6 |
| Timing a debug build. | cargo run is unoptimised; and a release build silently wraps on overflow. | Measure with --release; use checked_* where overflow matters. | sections 2 and 3 |
| Blocking inside async code. | A long computation or a blocking file read inside an async fn stalls every task on that thread. | Move it to spawn_blocking. | async child, "Blocking the runtime" |
Rust's ownership is C++'s RAII plus move semantics, with the compiler enforcing what the C++ Core Guidelines only recommend (C++: the essentials and C++: ownership, moves and object lifetimes teach the C++ side).
| C++ | Rust | The difference |
|---|---|---|
auto b = std::move(a); | let b = a; | Moves are the default and the moved-from variable is unusable (a compile error), not "valid but unspecified". |
| destructor | impl Drop | Same deterministic order (reverse of declaration). |
const T&, T& | &T, &mut T | Aliasing XOR mutation is checked, so iterator invalidation and dangling references do not compile. |
std::string_view into a temporary | &str with a lifetime | Undefined behaviour in C++; E0515 or E0597 in Rust. |
| templates, concepts | generics with trait bounds | Both monomorphise; Rust checks the generic body against the bounds once, at definition, so errors are short. |
virtual | dyn Trait | Opt-in at the use site, no inheritance; the vtable pointer lives in the fat pointer, not in the object. |
unique_ptr, shared_ptr | Box, Rc/Arc | Rc is a non-atomic shared_ptr, allowed only on one thread (not Send). |
exceptions, std::expected | Result and ? | Panics exist but are for bugs. |
| everything | unsafe { } | C++'s rules apply only inside the block, and the block is searchable. |
No function overloading and no implicit conversions; prefer indexes and arenas to pointer graphs, because self-referential structs are the design Rust refuses.
Each assumes this page and stands alone otherwise. Times are each child's own header (230 words a minute), with the closed blocks counted apart; much of each child's core is recorded code and output, which is scanned rather than read.
Rust turns what a Python program discovers while running into types the compiler checks before running. Strings as UTF-8 bytes, enums with data and exhaustive match, Option, Result and ?, traits and generics, iterators that cost nothing (measured), collections, cargo test; nine Python to Rust predictions inline. 3D figures: an enum in memory one cube per byte, a generic against a trait object, an iterator chain pulled one word at a time.
Where one owner and compile-time borrows are not enough. Lifetimes as a contract checked at every call, Box, Rc, RefCell and Arc, threads without data races (Send and Sync), and unsafe checked with Miri. 3D figures: a borrow resting on what it borrows, handles and counted blocks, what may cross into a thread, raw pointers through the unsafe gate.
Port the whole pipeline, not one function. Profiling first, PyO3 and maturin, what each conversion costs, NumPy without copies, releasing the GIL with rayon, free-threaded 3.14t, abi3 wheels, and the root's token counter from 1.36 s to 0.059 s step by step. 3D figures: from crate to import, one call across the boundary, four threads and one GIL, one wheel and the interpreters that load it.
Futures are lazy and the runtime is a library you choose. Async Rust from zero with tokio, blocking the runtime (measured), Send + 'static errors, an axum service measured against FastAPI, a CLI with clap, shipping a binary. 3D figures: tokio's multi-thread runtime, jobs A, B and C on a real trace, six recorded requests to an axum service.
Three ways through. "I have slow Python and want it fast": this page, then the enums child's sections 1 to 3, then the PyO3 child in order; profile first, because its section 1 shows when porting does not help. "I want to write a service or a CLI": this page, the enums child, then the async child. "I just want to understand Rust": the children in the order above, with the Borrow-checker lab here.
Elsewhere: how Rust compares with Python, C++ and TypeScript, with the same program written in all four, is on the parent page Topic: programming-languages. The sibling language pages are Python: the essentials, C++: the essentials and JavaScript and TypeScript: the essentials; Rust on the GPU (cutile-rs, cuda-oxide, CubeCL) belongs to Topic: cuda-and-gpu-programming.
Every output, compiler error and panic on this page is a real run (rustc 1.99.0, edition 2024, and CPython 3.14.8 on an Apple M1 Pro, 2026-10-05), recorded by src/ra/run_all.sh; the Python side of the enums child's hero was rerun on 3.14.8 on 2026-10-26. This page replaces the old written page "Rust: zero to expert"; every claim from it was checked, and the corrections are shown in boxes on the page that owns each subject. Rebuilt on 2026-10-26 as the essentials page of four children (src/README.md says how).
Links checked 2026-10-26. Times for outside sources are rough reading estimates; each child page has its own Further reading for its subject.
Box, Rc, RefCell and unsafe on one data structure. about 4 hunsafe: what you must uphold and why. about 3 hrustc --explain. referenceSources and reproduction: src/ra/ in this page's folder (run_all.sh reruns every example; check.mjs proves the page embeds the recorded outputs, that every lab scenario and fix behaves as stated, and that each prediction has exactly one right answer).