The idea in one sentence. Rust has one rule, many readers or one writer, and no reference outlives what it points to; lifetimes let the compiler check it for references, Send and Sync carry it across threads, RefCell and Mutex move the check to run time, and inside unsafe it becomes your job, with Miri checking it in your tests.
You need Rust: the essentials: ownership, moves, and borrowing with its "many readers or one writer" rule on one Vec (its Ownership animation and Borrow-checker lab). This page starts where that one stops. Every program here was compiled and run with rustc 1.99.0 (edition 2024) on an Apple M1 Pro, and every output is the recorded one.
'aT: 'staticT holds no borrow that could expire (not "lives forever")Send, Sync&T may be shared between threadsunsafe; the program may do anything, including appear to workRead left to right as "how late the mistake is found". Most code lives in the first column; each step right buys flexibility and pays for it in when, and how loudly, a mistake shows up.
A lifetime is the stretch of the program during which a reference is valid. The checker computes them itself almost everywhere. You write one, as 'a, only when a function returns a reference (or a struct holds one) and the compiler cannot tell which input it came from:
$ rustc --edition 2024 life_err.rs
error[E0106]: missing lifetime specifier
--> life_err.rs:1:33
|
1 | fn longest(a: &str, b: &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 `a` or `b`
help: consider introducing a named lifetime parameter
|
1 | fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
| ++++ ++ ++ ++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0106`.
[exit code 1]
Read 'a as a name for "some region of the program". The fixed signature fn longest<'a>(a: &'a str, b: &'a str) -> &'a str says: the result is valid as long as both inputs are, so at each call 'a shrinks to the overlap of the two. Lifetimes generate no code; they are a contract the checker verifies at every call.
The stage draws one call of longest along the lines of main: each value is a slab from its declaration to the end of its scope, a value of an inner block stacked on the outer one, and the borrow w on top of what it borrows. A borrow has to rest on its owners along its whole length. (The stacking pictures "must fit inside", not where anything sits in memory.)
let a = String::from("tokens"); at line 6, alive to the end of main (line 13).b is declared at line 9 inside a block that closes at line 11: its slab sits on a's and ends at that brace.w = longest(&a, &b); (line 10) gives w the lifetime 'a, and 'a must fit inside both inputs: the dots run from a and b into w.'a may reach. The overlap of a and b is b's span, so 'a may reach no further than line 11, where b is dropped (the glass plate).println!("{w}") at line 12 stretches w past b's end; that part has nothing under it. The error names exactly the three points on the timeline: where b was borrowed, where it was dropped, where the borrow was used later.println! moves inside the block (line 23, before b's end at 24), so w rests on b along its whole length: it compiles and prints longest: logits!. Moving one use is the whole difference.
$ rustc --edition 2024 life_err2.rs
error[E0597]: `b` does not live long enough
--> life_err2.rs:10:25
|
9 | let b = String::from("logits!");
| - binding `b` declared here
10 | w = longest(&a, &b);
| ^^ borrowed value does not live long enough
11 | } // b is freed here
| - `b` dropped here while still borrowed
12 | println!("{w}");
| - borrow later used here
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0597`.
[exit code 1]
// 'a names "some region of the program". The signature promises: the result // lives no longer than the shorter-lived of a and b. fn longest<'a>(a: &'a str, b: &'a str) -> &'a str { if a.len() >= b.len() { a } else { b } } // One input reference: the compiler fills in the lifetimes itself (elision). fn first_word(s: &str) -> &str { s.split(' ').next().unwrap_or("") } // A struct that holds a reference must say how long it may live. struct Token<'a> { text: &'a str, } fn main() { let a = String::from("tokens"); let w; { let b = String::from("logits!"); w = longest(&a, &b); println!("longest: {w}"); } let t = Token { text: first_word("hello world") }; let s: &'static str = "string literals live for the whole program"; println!("{} | {}", t.text, s); }
$ rustc --edition 2024 life.rs && ./life
longest: logits!
hello | string literals live for the whole program
fn main() { let a = String::from("tokens"); let w; { let b = String::from("logits!"); w = longest(&a, &b); } // b is freed here println!("{w}"); }
The elision rules fill in the common cases, so most signatures carry no 'a:
| Rule | Example | Filled in as |
|---|---|---|
| 1. Each input reference gets its own lifetime. | fn f(a: &str, b: &str) | fn f<'1, '2>(a: &'1 str, b: &'2 str) |
| 2. Exactly one input lifetime: outputs get it. | fn first_word(s: &str) -> &str | the result borrows from s |
3. A method with &self: outputs get self's. | fn name(&self) -> &str | the result borrows from self |
So you write lifetimes when a function has two or more reference inputs and returns a reference, or a struct stores a reference (struct Token<'a> { text: &'a str } in life.rs). Rule 3 is the one that surprises: in a method it guesses self, even when the result can come from another argument.
impl Vocab { // Elision rule 3: with &self, the returned reference is assumed to borrow from self. fn pick(&self, other: &str) -> &str { if other.is_empty() { &self.name } else { other } } }
$ rustc --edition 2024 elide_self_err.rs
error: lifetime may not live long enough
--> elide_self_err.rs:8:51
|
7 | fn pick(&self, other: &str) -> &str {
| - - let's call the lifetime of this reference `'1`
| |
| let's call the lifetime of this reference `'2`
8 | if other.is_empty() { &self.name } else { other }
| ^^^^^ method was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
|
help: consider introducing a named lifetime parameter and update trait if needed
|
7 | fn pick<'a>(&self, other: &'a str) -> &'a str {
| ++++ ++ ++
error: aborting due to 1 previous error
[exit code 1]
The compiler's suggestion ties only other to the result, which would then refuse &self.name. The fix that matches what the code does names one lifetime for both inputs:
impl Vocab { // Say it explicitly: the result may come from self or from other. fn pick<'a>(&'a self, other: &'a str) -> &'a str { if other.is_empty() { &self.name } else { other } } }
$ rustc --edition 2024 elide_self_fix.rs && ./elide_self_fix
cl100k
gpt2
Annotations describe lifetimes and never extend them, so no 'a makes a reference to a value that is about to die:
fn make_greeting(name: &str) -> &str { let s = format!("hello {name}"); &s }
$ rustc --edition 2024 dangle_err.rs
error[E0515]: cannot return reference to local variable `s`
--> dangle_err.rs:3:5
|
3 | &s
| ^^ returns a reference to data owned by the current function
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0515`.
[exit code 1]
The fix is to return the owned String. That is the general rule of thumb: if "just add a lifetime" spreads 'a through many types, store an owned value instead; borrowing in structs is an optimisation for later.
'static: two meanings, one of which is a bound&'static str is a reference valid for the whole program: string literals are &'static str because they live in the program's binary. T: 'static as a bound is weaker and far more common: T holds no borrow that could expire. Every owned type (String, Vec, Arc<Mutex<..>>) satisfies it, and is still freed whenever its owner drops it. This is the bound on std::thread::spawn and tokio::spawn, and the reason section 3's first error says "requires argument type to outlive 'static".
$ rustc --edition 2024 static_bound.rs && ./static_bound
"an owned String is 'static"
dropped; a 'static bound never kept it alive
use std::fmt::Debug; // T: 'static means "T holds no borrow that could expire", not "T lives forever". fn keep<T: Debug + 'static>(t: T) -> Box<dyn Debug> { Box::new(t) } fn main() { let owned = String::from("an owned String is 'static"); let b = keep(owned); // fine: a String borrows nothing println!("{b:?}"); drop(b); // ... and it is freed right here, long before the program ends println!("dropped; a 'static bound never kept it alive"); }
$ rustc --edition 2024 static_bound_err.rs
error[E0597]: `local` does not live long enough
--> static_bound_err.rs:9:18
|
8 | let local = String::from("local");
| ----- binding `local` declared here
9 | let b = keep(&local); // a borrow of a local is not 'static
| -----^^^^^^-
| | |
| | borrowed value does not live long enough
| argument requires that `local` is borrowed for `'static`
10 | println!("{b:?}");
11 | }
| - `local` dropped here while still borrowed
|
note: requirement that the value outlives `'static` introduced here
--> static_bound_err.rs:3:20
|
3 | fn keep<T: Debug + 'static>(t: T) -> Box<dyn Debug> {| ^^^^^^^ error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0597`. [exit code 1]
'_, the anonymous lifetime: "the elided one", written where a type needs a lifetime parameter but you want elision, as in impl fmt::Display for Token<'_>.T: 'a bounds say every reference inside T outlives 'a; they appear on structs holding generic references, and the compiler infers most of them.&'long T may be used where a &'short T is expected (always, for shared references) and why &mut T is stricter; the Rustonomicon's chapter on subtyping is the reference.Single ownership and compile-time borrowing cover most code. For the rest, the standard library has types that own their contents in other ways, each with a cost:
| Type | What it gives you | Cost | Python analogue |
|---|---|---|---|
Box<T> | one owner, value on the heap; needed for recursive types and trait objects | one allocation | every object |
Rc<T> | shared ownership in one thread; freed when the last Rc goes | a counter update per clone and drop | reference counting |
Arc<T> | the same across threads | atomic counter updates (slower) | reference counting in free-threaded CPython |
Cell<T>, RefCell<T> | interior mutability: change through a shared reference; RefCell checks the borrow rules at run time | a flag check per borrow; a panic if the rules are broken | (all objects are mutable) |
Mutex<T>, RwLock<T> | the same across threads, by locking | a lock per access; contention | threading.Lock |
Weak<T> | a non-owning pointer to an Rc/Arc value; breaks cycles | upgrade() may find it gone | weakref |
A recursive type needs Box, because a value that contains itself directly would have infinite size; with the Box each child is one 8-byte pointer, as the run below prints (size_of Box<Expr> = 8).
$ rustc --edition 2024 recursive_err.rs
error[E0072]: recursive type `Expr` has infinite size
--> recursive_err.rs:1:1
|
1 | enum Expr {
| ^^^^^^^^^
2 | Num(f64),
3 | Add(Expr, Expr),
| ---- recursive without indirection
|
help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to break the cycle
|
3 | Add(Box<Expr>, Expr),
| ++++ +
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0072`.
[exit code 1]
Rc: shared ownership is a counter beside the value. Cloning an Rc copies an 8-byte pointer and bumps a count; the value is freed when the count reaches 0. The stage steps through smart.rs: handles on the stack plate, the blocks they own on the heap floor, dots running along each owning pointer. The counts the program prints are marked printed; the others follow from the code. Positions and block sizes are illustrative.
e is an Expr::Add holding two Boxes, and the Mul holds two more: a tree of heap allocations, each Box 8 bytes, the Expr itself 24. Printed: 2 + 3 * 4 = 14. Dropping e frees the whole tree, owner by owner.Rc::new: count 1. Line 31: one heap block holds the count and the Doc; shared is an 8-byte pointer to it (Rc<Doc> = 8, printed). strong_count = 1.Rc::clone(&shared): copies the pointer and adds 1. The Doc and its String are not copied.b; b.cache_hits.set(..) changes the shared value through Cell. Printed: strong_count inside = 3.b leaves its block: dropping an Rc subtracts 1. Printed: strong_count after = 2, hits = 1. The Doc is freed only when the last handle goes and the count reaches 0.Rc<RefCell<Vec>>: a borrow flag. Line 41: log and its clone writer share one RefCell (count 2). Each borrow_mut() sets the flag to "one writer" while it lasts, and the pushes land: printed log = ["first", "second"].borrow_mut() at the same time. The flag already says "one writer", so the second one panics: RefCell already borrowed, at smart.rs:58:22.The same program also shows Cell: b.cache_hits.set(...) changes the Doc through a shared Rc, which plain & would refuse. Cell does it by copying values in and out, never handing out a reference, so it needs no check at all; RefCell hands out references, so it must count them.
$ rustc --edition 2024 smart.rs && ./smart
2 + 3 * 4 = 14
strong_count inside = 3
strong_count after = 2, hits = 1, name = system prompt
log = ["first", "second"]
weak upgrade while alive: true
weak upgrade after drop: false
size_of Box<Expr> = 8, Rc<Doc> = 8, Expr = 24
thread 'main' (16492202) panicked at smart.rs:58:22:
RefCell already borrowed
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
[exit code 101]
// RefCell: borrow rules checked at run time instead of compile time let log = Rc::new(RefCell::new(Vec::<String>::new())); let writer = Rc::clone(&log); writer.borrow_mut().push("first".into()); writer.borrow_mut().push("second".into()); println!("log = {:?}", log.borrow()); // Weak: a non-owning pointer (it does not keep the value alive); used to break cycles let parent = Rc::new(String::from("parent")); let w: Weak<String> = Rc::downgrade(&parent); println!("weak upgrade while alive: {}", w.upgrade().is_some()); drop(parent); println!("weak upgrade after drop: {}", w.upgrade().is_some()); println!("size_of Box<Expr> = {}, Rc<Doc> = {}, Expr = {}", std::mem::size_of::<Box<Expr>>(), std::mem::size_of::<Rc<Doc>>(), std::mem::size_of::<Expr>()); // The run-time check, failing: two mutable borrows at once let first = log.borrow_mut(); let second = log.borrow_mut(); // panics: already mutably borrowed println!("{} {}", first.len(), second.len());
The panic is the price of RefCell: the same rule as compile-time borrowing, but discovered while the program runs. Rc<RefCell<T>> compiles in situations where plain references would not, and it is the most common way learners make a borrow error go away and turn it into a crash. So: Rc<RefCell<T>> compiles but can still panic because the exclusivity check moved from compile time to run time. try_borrow_mut returns an error instead of panicking (RefCell docs), for code that can recover.
use std::cell::{Cell, RefCell}; use std::rc::{Rc, Weak}; // Box: put a value on the heap. Needed for recursive types, whose size would otherwise be infinite. #[derive(Debug)] enum Expr { Num(f64), Add(Box<Expr>, Box<Expr>), Mul(Box<Expr>, Box<Expr>), } fn eval(e: &Expr) -> f64 { match e { Expr::Num(x) => *x, Expr::Add(a, b) => eval(a) + eval(b), Expr::Mul(a, b) => eval(a) * eval(b), } } #[derive(Debug)] struct Doc { name: String, cache_hits: Cell<u32>, // interior mutability for a Copy value } fn main() { let e = Expr::Add(Box::new(Expr::Num(2.0)), Box::new(Expr::Mul(Box::new(Expr::Num(3.0)), Box::new(Expr::Num(4.0))))); println!("2 + 3 * 4 = {}", eval(&e)); // Rc: shared ownership in one thread; the last owner to go frees the value let shared = Rc::new(Doc { name: "system prompt".into(), cache_hits: Cell::new(0) }); let a = Rc::clone(&shared); // copies a pointer, bumps a counter { let b = Rc::clone(&shared); b.cache_hits.set(b.cache_hits.get() + 1); // mutate through a shared reference println!("strong_count inside = {}", Rc::strong_count(&shared)); } println!("strong_count after = {}, hits = {}, name = {}", Rc::strong_count(&a), a.cache_hits.get(), a.name);
Reference counting cannot free a cycle, in Rust as in Python (where the cycle collector cleans up afterwards; Rust has none). Leaking memory is safe in Rust's sense, so the compiler allows it. The figure is leak.rs's two blocks: a pair of nodes that own each other, and the same pair with the back edge made Weak. (The C++ ownership page replays the same cycle with shared_ptr and weak_ptr on its smart-pointer stage: Rc is shared_ptr without atomic counts, Arc with them.)
$ rustc --edition 2024 leak.rs && ./leak
cycle: x strong_count = 2
weak: x strong_count = 1, weak_count = 1
y.back.upgrade() is x (Weak back edge)
drop x (Weak back edge)
drop y (Weak back edge)
end of main: the Rc cycle was never dropped (a leak, which safe Rust allows)Rule of thumb: ownership should form a tree. Back pointers (child to parent, node to previous) are Weak, or better, indexes into a Vec that owns all the nodes (an "arena"), which is how most Rust graph code is written. Miri (section 4) reports memory still allocated when a program ends, so it would flag this leak in a test.
use std::cell::RefCell; use std::rc::{Rc, Weak}; struct Node { name: &'static str, next: RefCell<Option<Rc<Node>>>, // owning edge back: RefCell<Weak<Node>>, // non-owning edge } impl Drop for Node { fn drop(&mut self) { println!("drop {}", self.name); } } fn node(name: &'static str) -> Rc<Node> { Rc::new(Node { name, next: RefCell::new(None), back: RefCell::new(Weak::new()) }) } fn main() { { let x = node("x (cycle of Rc)"); let y = node("y (cycle of Rc)"); *x.next.borrow_mut() = Some(Rc::clone(&y)); // x -> y *y.next.borrow_mut() = Some(Rc::clone(&x)); // y -> x: a cycle println!("cycle: x strong_count = {}", Rc::strong_count(&x)); } // our two handles go, but each node still owns the other: neither count reaches 0 { let x = node("x (Weak back edge)"); let y = node("y (Weak back edge)"); *x.next.borrow_mut() = Some(Rc::clone(&y)); // x owns y *y.back.borrow_mut() = Rc::downgrade(&x); // y only points back at x println!("weak: x strong_count = {}, weak_count = {}", Rc::strong_count(&x), Rc::weak_count(&x)); println!("y.back.upgrade() is {}", y.back.borrow().upgrade().map(|n| n.name).unwrap_or("gone")); } println!("end of main: the Rc cycle was never dropped (a leak, which safe Rust allows)"); }
Counts are leak.rs's printed values (cycle: x strong_count = 2; weak: x strong_count = 1, weak_count = 1); the code and the full output are below.
A data race is two threads touching the same memory at the same time, at least one of them writing, with nothing ordering them. Updates get lost or values tear. In CPython the GIL used to hide most of these; free-threaded Python 3.14 does not, and an unsynchronised counter there loses updates (measured on Python: concurrency, asyncio and the GIL). Rust makes data races a compile error in safe code by applying the borrowing rule across threads: shared data may be read by many threads, and changed only through a type that synchronises (a lock or an atomic). What a race, a mutex and an atomic are at the OS level is taught on Concurrency: threads, locks, futexes, deadlock, and event-driven I/O; this section is what Rust's types add.
The obvious Python translation, eight threads incrementing one counter, does not compile, and the three errors are the three problems:
use std::thread; fn main() { let mut counter = 0u64; let mut hs = vec![]; for _ in 0..8 { hs.push(thread::spawn(|| for _ in 0..100_000 { counter += 1; })); } for h in hs { h.join().unwrap(); } println!("{counter}"); }
| Error | The problem | The fix |
|---|---|---|
E0373 | the thread may outlive counter: a spawned thread is not joined automatically, so spawn demands a 'static closure (section 1) | move owned data in, or use thread::scope, whose threads are joined before it returns |
E0499 | eight closures would each hold &mut counter at once: the data race itself | a Mutex or an atomic |
E0502 | the final read overlaps the mutable borrows | read after joining, through the lock |
$ rustc --edition 2024 race_err.rs
error[E0373]: closure may outlive the current function, but it borrows `counter`, which is owned by the current function
--> race_err.rs:7:31
|
7 | hs.push(thread::spawn(|| for _ in 0..100_000 { counter += 1; }));
| ^^ ------- `counter` is borrowed here
| |
| may outlive borrowed value `counter`
|
note: function requires argument type to outlive `'static`
--> race_err.rs:7:17
|
7 | hs.push(thread::spawn(|| for _ in 0..100_000 { counter += 1; }));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: to force the closure to take ownership of `counter` (and any other referenced variables), use the `move` keyword
|
7 | hs.push(thread::spawn(move || for _ in 0..100_000 { counter += 1; }));
| ++++
error[E0499]: cannot borrow `counter` as mutable more than once at a time
--> race_err.rs:7:31
|
7 | hs.push(thread::spawn(|| for _ in 0..100_000 { counter += 1; }));
| --------------^^---------------------------------------
| | | |
| | | borrows occur due to use of `counter` in closure
| | `counter` was mutably borrowed here in the previous iteration of the loop
| argument requires that `counter` is borrowed for `'static`
|
note: requirement that the value outlives `'static` introduced here
--> /rustc/b940084d7eb6a299eb4bfeb8e34901bc051e7ac4/library/std/src/thread/functions.rs:128:14
error[E0502]: cannot borrow `counter` as immutable because it is also borrowed as mutable
--> race_err.rs:10:16
|
7 | hs.push(thread::spawn(|| for _ in 0..100_000 { counter += 1; }));
| -------------------------------------------------------
| | | |
| | | first borrow occurs due to use of `counter` in closure
| | mutable borrow occurs here
| argument requires that `counter` is borrowed for `'static`
...
10 | println!("{counter}");
| ^^^^^^^ immutable borrow occurs here
|
note: requirement that the value outlives `'static` introduced here
--> /rustc/b940084d7eb6a299eb4bfeb8e34901bc051e7ac4/library/std/src/thread/functions.rs:128:14
error: aborting due to 3 previous errors
Some errors have detailed explanations: E0373, E0499, E0502.
For more information about an error, try `rustc --explain E0373`.
[exit code 1]Scoped threads fix the first problem but not the second, which is the race (thread::scope still gives E0499).
$ rustc --edition 2024 race_scope_err.rs
error[E0499]: cannot borrow `counter` as mutable more than once at a time
--> race_scope_err.rs:7:21
|
5 | thread::scope(|s| {
| - has type `&'1 Scope<'1, '_>`
6 | for _ in 0..8 {
7 | s.spawn(|| for _ in 0..100_000 { counter += 1; });
| --------^^---------------------------------------
| | | |
| | | borrows occur due to use of `counter` in closure
| | `counter` was mutably borrowed here in the previous iteration of the loop
| argument requires that `counter` is borrowed for `'1`
|
note: requirement that the value outlives `'1` introduced here
--> /rustc/b940084d7eb6a299eb4bfeb8e34901bc051e7ac4/library/std/src/thread/scoped.rs:203:34
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0499`.
[exit code 1]
Two marker traits carry the rule. They have no methods; the compiler implements them automatically for a type whose parts all qualify (std::marker::Send, the Rustonomicon on Send and Sync):
Send: a value of this type may be moved to another thread.Sync: a &T may be shared between threads (precisely, T is Sync if &T is Send).thread::spawn requires its closure to be Send, so everything the closure captures must be. Rc is neither, because two threads updating its non-atomic counter at once would be a race; Arc uses atomic updates and is both. Moving an Rc into a thread is refused with E0277, "Rc<Vec<i32>> cannot be sent between threads safely", naming spawn's bound as the reason.
$ rustc --edition 2024 rc_thread_err.rs
error[E0277]: `Rc<Vec<i32>>` cannot be sent between threads safely
--> rc_thread_err.rs:7:27
|
7 | let h = thread::spawn(move || s2.len());
| ------------- -------^^^^^^^^^
| | |
| | `Rc<Vec<i32>>` cannot be sent between threads safely
| | within this `{closure@rc_thread_err.rs:7:27: 7:34}`
| required by a bound introduced by this call
|
= help: within `{closure@rc_thread_err.rs:7:27: 7:34}`, the trait `Send` is not implemented for `Rc<Vec<i32>>`
note: required because it's used within this closure
--> rc_thread_err.rs:7:27
|
7 | let h = thread::spawn(move || s2.len());
| ^^^^^^^
note: required by a bound in `spawn`
--> /rustc/b940084d7eb6a299eb4bfeb8e34901bc051e7ac4/library/std/src/thread/functions.rs:125:0error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0277`. [exit code 1]
use std::cell::{Cell, RefCell}; use std::sync::atomic::AtomicU64; use std::sync::{Arc, Mutex, MutexGuard, RwLock}; fn send<T: Send>() {} fn sync<T: Sync>() {} // Every "yes" cell of the page's Send and Sync table, checked by the compiler. // The "no" cells are in sendsync_err.rs, each refused with its own error. fn main() { send::<i32>(); sync::<i32>(); send::<String>(); sync::<String>(); send::<Vec<u8>>(); sync::<Vec<u8>>(); send::<Box<i32>>(); sync::<Box<i32>>(); send::<&i32>(); sync::<&i32>(); send::<Arc<i32>>(); sync::<Arc<i32>>(); send::<Cell<i32>>(); send::<RefCell<i32>>(); send::<Mutex<i32>>(); sync::<Mutex<i32>>(); send::<Mutex<Cell<i32>>>(); sync::<Mutex<Cell<i32>>>(); send::<Arc<Mutex<Vec<u8>>>>(); sync::<Arc<Mutex<Vec<u8>>>>(); send::<RwLock<i32>>(); sync::<RwLock<i32>>(); send::<AtomicU64>(); sync::<AtomicU64>(); sync::<MutexGuard<'static, i32>>(); println!("all 25 \"yes\" claims compile"); }
$ rustc --edition 2024 sendsync.rs && ./sendsync
all 25 "yes" claims compile
use std::cell::{Cell, RefCell}; use std::rc::Rc; use std::sync::{Arc, MutexGuard}; fn send<T: Send>() {} fn sync<T: Sync>() {} // Every "no" cell of the page's Send and Sync table: each line is refused with its own E0277. fn main() { send::<Rc<i32>>(); sync::<Rc<i32>>(); sync::<Cell<i32>>(); sync::<RefCell<i32>>(); send::<Arc<RefCell<i32>>>(); sync::<Arc<RefCell<i32>>>(); send::<MutexGuard<'static, i32>>(); send::<*const i32>(); sync::<*const i32>(); }
$ rustc --edition 2024 sendsync_err.rs
error[E0277]: `Rc<i32>` cannot be sent between threads safely
--> sendsync_err.rs:10:12
|
10 | send::<Rc<i32>>();
| ^^^^^^^ `Rc<i32>` cannot be sent between threads safely
|
= help: the trait `Send` is not implemented for `Rc<i32>`
note: required by a bound in `send`
--> sendsync_err.rs:5:12
|
5 | fn send<T: Send>() {}
| ^^^^ required by this bound in `send`
error[E0277]: `Rc<i32>` cannot be shared between threads safely
--> sendsync_err.rs:11:12
|
11 | sync::<Rc<i32>>();
| ^^^^^^^ `Rc<i32>` cannot be shared between threads safely
|
= help: the trait `Sync` is not implemented for `Rc<i32>`
note: required by a bound in `sync`
--> sendsync_err.rs:6:12
|
6 | fn sync<T: Sync>() {}
| ^^^^ required by this bound in `sync`
error[E0277]: `Cell<i32>` cannot be shared between threads safely
--> sendsync_err.rs:12:12
|
12 | sync::<Cell<i32>>();
| ^^^^^^^^^ `Cell<i32>` cannot be shared between threads safely
|
= help: the trait `Sync` is not implemented for `Cell<i32>`
= note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead
note: required by a bound in `sync`
--> sendsync_err.rs:6:12
|
6 | fn sync<T: Sync>() {}
| ^^^^ required by this bound in `sync`
error[E0277]: `RefCell<i32>` cannot be shared between threads safely
--> sendsync_err.rs:13:12
|
13 | sync::<RefCell<i32>>();
| ^^^^^^^^^^^^ `RefCell<i32>` cannot be shared between threads safely
|
= help: the trait `Sync` is not implemented for `RefCell<i32>`
= note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead
note: required by a bound in `sync`
--> sendsync_err.rs:6:12
|
6 | fn sync<T: Sync>() {}
| ^^^^ required by this bound in `sync`
error[E0277]: `RefCell<i32>` cannot be shared between threads safely
--> sendsync_err.rs:14:12
|
14 | send::<Arc<RefCell<i32>>>();
| ^^^^^^^^^^^^^^^^^ `RefCell<i32>` cannot be shared between threads safely
|
= help: the trait `Sync` is not implemented for `RefCell<i32>`
= note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead
= note: required for `Arc<RefCell<i32>>` to implement `Send`
note: required by a bound in `send`
--> sendsync_err.rs:5:12
|
5 | fn send<T: Send>() {}
| ^^^^ required by this bound in `send`
error[E0277]: `RefCell<i32>` cannot be shared between threads safely
--> sendsync_err.rs:15:12
|
15 | sync::<Arc<RefCell<i32>>>();
| ^^^^^^^^^^^^^^^^^ `RefCell<i32>` cannot be shared between threads safely
|
= help: the trait `Sync` is not implemented for `RefCell<i32>`
= note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead
= note: required for `Arc<RefCell<i32>>` to implement `Sync`
note: required by a bound in `sync`
--> sendsync_err.rs:6:12
|
6 | fn sync<T: Sync>() {}
| ^^^^ required by this bound in `sync`
error[E0277]: `std::sync::MutexGuard<'static, i32>` cannot be sent between threads safely
--> sendsync_err.rs:16:12
|
16 | send::<MutexGuard<'static, i32>>();
| ^^^^^^^^^^^^^^^^^^^^^^^^ `std::sync::MutexGuard<'static, i32>` cannot be sent between threads safely
|
= help: the trait `Send` is not implemented for `std::sync::MutexGuard<'static, i32>`
note: required by a bound in `send`
--> sendsync_err.rs:5:12
|
5 | fn send<T: Send>() {}
| ^^^^ required by this bound in `send`
error[E0277]: `*const i32` cannot be sent between threads safely
--> sendsync_err.rs:17:12
|
17 | send::<*const i32>();
| ^^^^^^^^^^ `*const i32` cannot be sent between threads safely
|
= help: the trait `Send` is not implemented for `*const i32`
note: required by a bound in `send`
--> sendsync_err.rs:5:12
|
5 | fn send<T: Send>() {}
| ^^^^ required by this bound in `send`
error[E0277]: `*const i32` cannot be shared between threads safely
--> sendsync_err.rs:18:12
|
18 | sync::<*const i32>();
| ^^^^^^^^^^ `*const i32` cannot be shared between threads safely
|
= help: the trait `Sync` is not implemented for `*const i32`
note: required by a bound in `sync`
--> sendsync_err.rs:6:12
|
6 | fn sync<T: Sync>() {}
| ^^^^ required by this bound in `sync`
error: aborting due to 9 previous errors
For more information about this error, try `rustc --explain E0277`.
[exit code 1]A type you write gets Send and Sync for free when its fields have them. Only a type holding a raw pointer (a wrapper around a C handle, say) has to claim them by hand with unsafe impl Send for T {}, which is a promise the compiler cannot check: one of section 4's five unsafe operations.
Predict before reading the columns: is Arc<RefCell<i32>> Send? Is a Mutex holding a Cell Sync?
| Type | Send | Sync | Why |
|---|---|---|---|
i32, String, Vec<u8>, Box<i32> | yes | yes | own their data; nothing shared behind them |
&i32 | yes | yes | a shared reference is Send because i32 is Sync |
Rc<i32> | no | no | two clones in two threads would update the plain counter at once |
Arc<i32> | yes | yes | the counter is updated atomically |
Cell<i32>, RefCell<i32> | yes | no | may move to one thread; sharing would let two threads mutate unsynchronised |
Arc<RefCell<i32>> | no | no | Arc is only as shareable as its contents |
Mutex<i32>, RwLock<i32> | yes | yes | the lock orders every access |
Mutex<Cell<i32>> | yes | yes | a Mutex makes a non-Sync value Sync (it needs only Send) |
Arc<Mutex<Vec<u8>>> | yes | yes | the shared-mutable-state pattern |
AtomicU64 | yes | yes | hardware atomic operations |
MutexGuard<i32> | no | yes | some platforms require the locking thread to unlock |
*const i32 | no | no | raw pointers opt out; unsafe code must vouch with unsafe impl |
The 25 "yes" cells are asserted in sendsync.rs, which compiles (all 25 "yes" claims compile); the 9 "no" cells are each refused with E0277 in sendsync_err.rs. Arc<T> is Send and Sync only when T is both; Mutex<T> is Sync when T is merely Send, which is how a lock makes unshareable data shareable. MutexGuard's reason is from its documentation.
threads.rs uses the five tools in turn; every number on the stage is its printed output. The main thread is in front, the threads it starts on an arc behind it (positions illustrative).
thread::spawn(move || ...) plus join(). Each thread gets its own document, moved in, and hands back a count when joined. Printed: spawned: [(0, 3), (1, 2), (2, 1)].thread::scope. Two threads read the two halves of one vector that stays owned by main; the scope joins both before it returns, so the borrow cannot outlive the data. Printed: scoped sum: 1000000.Rc moved into a spawned thread is refused at compile time: `Rc<Vec<i32>>` cannot be sent between threads safely (E0277), because two threads could update its plain counter at once.Arc<Mutex<T>>. One counter on the heap behind a lock; each of the 8 threads holds an Arc clone, so the strong count is 8 + 1 while they run (from the code; not printed).lock(): one thread holds the guard, the others wait for it.mutex counter: 800000 (expected 800000), 8 × 100000.AtomicU64). The same 8 threads call fetch_add with no lock; the hardware makes each add indivisible. Printed: atomic counter: 800000.mpsc). 3 workers send a string each into one receiver on the main thread. Printed: channel: ["worker 0 done", "worker 1 done", "worker 2 done"].lock() returns a guard that unlocks when dropped, and the data is reachable only through the guard, so you cannot forget the lock. What Ordering::Relaxed on the atomic means (and when you need stronger orderings) is memory order, taught on the OS concurrency page; a counter needs only Relaxed. For data parallelism over a collection, the rayon crate turns iter() into par_iter(); Rust: speeding up Python with PyO3 and maturin uses it to parallelise the token counter inside a Python extension.
use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::mpsc; use std::sync::{Arc, Mutex}; use std::thread; fn main() { // 1. spawn + join; `move` gives the thread its own copy of what it uses let docs = vec!["a b c", "d e", "f"]; let handles: Vec<_> = docs.into_iter().enumerate().map(|(i, d)| { thread::spawn(move || (i, d.split_whitespace().count())) }).collect(); let counts: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect(); println!("spawned: {counts:?}"); // 2. scoped threads may borrow local data, because they are joined before the scope ends let data = vec![1u64; 1_000_000]; let (left, right) = data.split_at(data.len() / 2); let total = thread::scope(|s| { let a = s.spawn(|| left.iter().sum::<u64>()); let b = s.spawn(|| right.iter().sum::<u64>()); a.join().unwrap() + b.join().unwrap() }); println!("scoped sum: {total}"); // 3. shared mutable state: Arc (shared ownership across threads) + Mutex (one writer at a time) let counter = Arc::new(Mutex::new(0u64)); let mut hs = vec![]; for _ in 0..8 { let c = Arc::clone(&counter); hs.push(thread::spawn(move || for _ in 0..100_000 { *c.lock().unwrap() += 1; })); } for h in hs { h.join().unwrap(); } println!("mutex counter: {} (expected 800000)", *counter.lock().unwrap()); // 4. an atomic does the same without a lock let hits = Arc::new(AtomicU64::new(0)); thread::scope(|s| for _ in 0..8 { let h = &hits; s.spawn(move || for _ in 0..100_000 { h.fetch_add(1, Ordering::Relaxed); }); }); println!("atomic counter: {}", hits.load(Ordering::Relaxed)); // 5. channels: send values from many producers to one consumer let (tx, rx) = mpsc::channel(); for id in 0..3 { let tx = tx.clone(); thread::spawn(move || tx.send(format!("worker {id} done")).unwrap()); } drop(tx); // close our copy so the loop below ends when the workers finish let mut got: Vec<String> = rx.iter().collect(); got.sort(); println!("channel: {got:?}"); }
$ rustc --edition 2024 threads.rs && ./threads
spawned: [(0, 3), (1, 2), (2, 1)]
scoped sum: 1000000
mutex counter: 800000 (expected 800000)
atomic counter: 800000
channel: ["worker 0 done", "worker 1 done", "worker 2 done"]
Async is the other way to be concurrent: for thousands of network calls rather than CPU work, Rust uses async fn and a runtime library, almost always tokio. The same two traits decide what may cross .await points on a multi-threaded runtime (tokio::spawn needs Send + 'static); Rust: async with tokio, services with axum, and CLIs owns it.
Some correct code cannot be proved safe by the compiler: the inside of Vec, calls into C libraries, hardware access. Inside an unsafe block you may do five extra things, the "unsafe superpowers" (Rust Book 20.1): dereference a raw pointer; call an unsafe function; access or modify a mutable static; implement an unsafe trait (such as Send, section 3); access fields of a union. Nothing else changes: "unsafe doesn't turn off the borrow checker or disable any of Rust's other safety checks".
fn main() { let v = vec![10u32, 20, 30]; let p: *const u32 = v.as_ptr(); // making a raw pointer is safe let second = unsafe { *p.add(1) }; // dereferencing it is not: we promise it is in bounds println!("second = {second}"); // A safe API built on unsafe: split_at_mut hands out two &mut halves of one slice, // which the borrow checker cannot prove disjoint by itself. let mut a = [1, 2, 3, 4]; let (l, r) = a.split_at_mut(2); l[0] += 100; r[0] += 100; println!("{a:?}"); }
$ rustc --edition 2024 unsafe_ok.rs && ./unsafe_ok
second = 20
[101, 2, 103, 4]
The stage follows the two programs: an unsafe gate between the pointers on the stack and the memory they point at, crossed by every dereference.
v owns a 12-byte heap allocation, three u32s (10, 20, 30) at byte offsets +0, +4 and +8. p = v.as_ptr() is only an address; nothing has been read.unsafe. unsafe { *p.add(1) } crosses the gate: the read is in bounds because we promise it is. Printed: second = 20.split_at_mut(2). Two &mut halves of one array, [0, 2) and [2, len), which the borrow checker cannot prove disjoint and the invariant guarantees never overlap. Each half changes once through its own &mut: printed [101, 2, 103, 4].*p.add(3) is byte +12 of a 12-byte allocation: past the end. The native release build reads whatever is there and carries on: read past the end: 0, exit code 0.src/main.rs:6:29.w is freed at the end of its block, but q still holds its address; the release build prints read after free: 0. Miri never reached this line: it stopped at the first violation.
$ rustc --edition 2024 unsafe_deref_err.rs
error[E0133]: dereference of raw pointer is unsafe and requires unsafe block
--> unsafe_deref_err.rs:4:20
|
4 | println!("{}", *p.add(1));
| ^^^^^^^^^ dereference of raw pointer
|
= note: raw pointers may be null, dangling or unaligned; they can violate aliasing rules and cause data races: all of these are undefined behavior
error[E0133]: call to unsafe function `std::ptr::const_ptr::<impl *const T>::add` is unsafe and requires unsafe block
--> unsafe_deref_err.rs:4:21
|
4 | println!("{}", *p.add(1));
| ^^^^^^^^ call to unsafe function
|
= note: consult the function's documentation for information on how to avoid undefined behavior
error: aborting due to 2 previous errors
For more information about this error, try `rustc --explain E0133`.
[exit code 1]
That is the pattern to aim for: a small unsafe core with a stated invariant ("the two halves never overlap"), wrapped in a safe API that cannot be used to break it (split_at_mut docs: it panics if mid > len). Because unsafe is a keyword, every such place can be found with a text search and reviewed.
Breaking an invariant is undefined behaviour, exactly as in C++: the program may do anything, including appear to work. This program reads one element past the end of a vector, and then reads a freed vector:
// Undefined behaviour that compiles and "works": reading one element past the end // through a raw pointer, and using a pointer after its Vec was freed. fn main() { let v = vec![10u32, 20, 30]; let p = v.as_ptr(); let past_end = unsafe { *p.add(3) }; // out of bounds: UB println!("read past the end: {past_end}"); let q = { let w = vec![1u32, 2, 3]; w.as_ptr() }; // w freed here; q dangles let after_free = unsafe { *q }; // use after free: UB println!("read after free: {after_free}"); }
Miri is an interpreter for Rust's intermediate representation that checks every memory access against the rules. Same program, two ways of running it:
$ cargo run -q --release
read past the end: 0
read after free: 0
Two zeros, exit code 0: nothing says anything went wrong.
$ cargo +nightly miri run -q 2>&1 | grep -v "^Preparing a sysroot"
error: Undefined Behavior: memory access failed: attempting to access 4 bytes, but got alloc291+0xc which is at or beyond the end of the allocation of size 12 bytes
--> src/main.rs:6:29
|
6 | let past_end = unsafe { *p.add(3) }; // out of bounds: UB
| ^^^^^^^^^ Undefined Behavior occurred here
|
= help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
= help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
help: alloc291 was allocated here:
--> src/main.rs:4:13
|
4 | let v = vec![10u32, 20, 30];
| ^^^^^^^^^^^^^^^^^^^
note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace
error: aborting due to 1 previous errorMiri stops at the first violation, names it (at or beyond the end of the allocation of size 12 bytes: three u32s) and points at where the memory was allocated. It runs on the nightly toolchain (here rustc 1.101.0-nightly of 2026-10-04) and is much slower than native code, so you run your tests under it, not production. If you write unsafe, run cargo +nightly miri test in CI.
| Miri catches (its README, read 2026-10-26) | Miri cannot |
|---|---|
out-of-bounds accesses and use after free (shown above); uninitialised data; misaligned accesses; invalid values (a bool that is not 0 or 1, a bad enum tag); data races; memory still allocated at exit (section 2's leak); aliasing violations under the experimental Stacked Borrows or Tree Borrows models | see executions you do not run ("Miri tests one of many possible executions"); call most C libraries or platform APIs, or use the network; prove code sound ("Miri fundamentally cannot ensure that your code is sound") |
Only the out-of-bounds read above was run here (2026-10-05); the other rows are the README's list, not run here because the nightly toolchain with Miri was not installed for this rebuild. The C++ equivalents are the sanitizers, on C++: the essentials.
unsafe to silence a borrow error. If safe code cannot express it, the design usually needs an index, a RefCell or a different owner.Links checked 2026-10-26. Times for outside sources are rough reading times.
Send, Sync and 'static bounds are written with.Send rules on Python objects.tokio::spawn needs Send + 'static.unique_ptr and shared_ptr, the C++ side of Box and Rc/Arc.Box::new and a dropped Rc cost underneath.T: 'static, elision and more, with examples. 45 minBox, Rc, RefCell and unsafe on one data structure, with Miri. about 4 hSend, Sync, atomics, memory ordering, building your own locks. about 6 hunsafe code must uphold: Send and Sync, variance, aliasing. about 3 h