skip to content

In Rust, what do the `Send` and `Sync` marker traits each promise, and who implements them for your own structs?

level: juniorimportance: must knowfreq 70%

answer

  1. two separate thread-safety promises
  2. moving ownership versus sharing a reference
  3. T: Sync exactly when &T: Send
  4. derived from the fields, not written

basics

~20 s

Send means a value may be moved to another thread; Sync means &T may be shared across threads, so T: Sync exactly when &T: Send. Both are auto traits that rustc implements for a struct whose fields all implement them.

solid answer

~50 s

`Send` says ownership of a value can move to another thread; `Sync` says it is safe to share `&T` between threads, and std defines it precisely: `T` is `Sync` if and only if `&T` is `Send`. Both are **auto traits**: rustc implements them for a struct, enum or tuple when every field implements them, and for a closure when every capture does. So you almost never write an impl. The exceptions come from a few building blocks std marks as opting out, mainly raw pointers and `NonNull` (neither trait), `UnsafeCell` (not `Sync`), `Rc` (neither), lock guards (not `Send`) and `mpsc::Receiver` (not `Sync`); one such field removes the trait from the whole type. `thread::spawn` requires its closure to be `Send + 'static`, which is where you meet the E0277 error "cannot be sent between threads safely". A trait object is `Send` only if you write it: `Box<dyn Fn() + Send>`.

code

rust · 13 lines
rust
use std::thread;

struct Job {
    name: String,
    // Without `+ Send`, the trait object is not Send and spawn rejects the closure.
    run: Box<dyn Fn() -> u32 + Send>,
}

fn main() {
    let job = Job { name: "compact".into(), run: Box::new(|| 1) };
    let t = thread::spawn(move || (job.run)() + job.name.len() as u32);
    println!("{}", t.join().unwrap());
}

go deeper

for a junior

Recall the two definitions: Send moves a value to another thread, Sync shares &T. Say that rustc derives both from the fields, so you rarely implement them.

for a middle

Explain the exact link T: Sync iff &T: Send, the structural rules for structs and closures, and why a trait object needs + Send written out.

for a senior

Read an E0277 chain to the field that broke it and fix the field or the design rather than reaching for unsafe impl Send.

for a principal

Treat Send and Sync as part of a type's public contract: a field added later can silently remove them and break callers that spawn it.

## Two promises, two traits Rust splits thread safety into two separate questions, each answered by a marker trait in `std::marker` (re-exported from `core::marker`): - **`Send`** — a value of this type can be *transferred* to another thread. After the move, the receiving thread owns it, uses it and eventually drops it. - **`Sync`** — a value of this type can be *shared* between threads, meaning several threads may hold `&T` at the same time. The standard library's own definition is exact: a type `T` is `Sync` **if and only if** `&T` is `Send`. The two are independent. Most types are both, but a type can be one without the other: `std::sync::mpsc::Receiver<T>` is `Send` (you can hand the receiving end to a worker) but not `Sync` (two threads must not call `recv` through shared references), while `std::sync::MutexGuard<T>` is `Sync` when `T` is but never `Send`. Both are **marker traits**: they have no methods. Implementing one is a promise about behaviour, not code to write, and both are declared `unsafe trait`, so a hand-written impl needs `unsafe impl` — rustc reports E0200 if you leave out `unsafe`. ## Auto traits: the compiler writes the impl `Send` and `Sync` are **auto traits** (the Reference lists them alongside `Unpin`, `UnwindSafe` and `RefUnwindSafe`). When no explicit or negative impl exists, rustc implements them structurally: 1. Structs, enums, unions and tuples implement the trait if all of their fields do. 2. `&T`, `&mut T`, arrays and slices follow their element type, except where std writes a specific impl — for example `&T` is `Send` only when `T: Sync`. 3. Closures implement the trait if the types of all their captures do. 4. Function items and function pointers always implement it. So a `struct Report { title: String, rows: Vec<u64> }` is `Send` and `Sync` with no annotation at all, because `String`, `Vec<u64>` and `u64` are. You never write `impl Send for Report`. The flip side is that one non-`Send` field makes the whole type non-`Send`, and the error message walks the chain: "required because it appears within the type `Report`". ## Where the chain breaks A handful of std types opt out with a **negative impl** (`impl !Send for ...`), which only the standard library can write on stable Rust: | Type | `Send` | `Sync` | Why, briefly | |---|---|---|---| | `*const T`, `*mut T` | no | no | raw pointers carry no safety guarantees, so containing types do not auto-derive | | `NonNull<T>` | no | no | the data it points at may be aliased | | `MutexGuard<'_, T>` | no | if `T: Sync` | some platforms must unlock on the locking thread | | `mpsc::Receiver<T>` | if `T: Send` | no | one receiving end, not shareable | | `UnsafeCell<T>` | if `T: Send` | no | unsynchronised interior mutability; `Cell` and `RefCell` build on it | | `Rc<T>` | no | no | non-atomic reference count, covered with smart pointers | Types built on raw pointers internally — `Box<T>`, `Vec<T>`, `String`, `Arc<T>` — are thread-safe whenever their contents are because std writes `unsafe impl Send` and `unsafe impl Sync` with the right bounds inside them: on `Arc` itself, and on the internal pointer type that `Box` and `Vec` are built on. ## How the traits are enforced Nothing checks `Send` or `Sync` at run time. The enforcement is a plain trait bound on the APIs that cross threads: - `std::thread::spawn` requires `F: FnOnce() -> T + Send + 'static` and `T: Send` for the return value. - `std::thread::Scope::spawn` requires `F: Send` too, with a scope lifetime instead of `'static`. - `Arc<T>` is `Send` only when `T: Send + Sync`. When a bound fails, rustc reports **E0277** with a message std attaches to the trait: "`X` cannot be sent between threads safely" for `Send`, and "`X` cannot be shared between threads safely" for `Sync`. ## Trait objects must ask for it An auto trait cannot be inferred through a trait object, because the concrete type is erased. `Box<dyn Fn() -> u32>` is therefore **not** `Send`, even if the closure inside happens to be. You add the auto trait to the object type yourself — `Box<dyn Fn() -> u32 + Send>` or `Box<dyn Error + Send + Sync>` — and the compiler then checks every value you put in the box. Auto traits are the one kind of trait you may stack onto a `dyn` type this way. ## Day-to-day consequences - Most of your types are `Send` and `Sync` for free; you rarely think about them until a spawn fails. - Read an E0277 from the bottom up: the `note: required because it appears within the type` lines name the field that broke the chain. - Fix the field, not the trait: switch to a thread-safe building block, add `+ Send` to a trait object, or restructure so the non-`Send` value stays on one thread. - Writing `unsafe impl Send` yourself is reserved for types that wrap raw pointers or foreign handles, and it is a promise you must be able to justify.

  • Why is `&mut T` `Send` whenever `T` is `Send`, while `&T` needs `T: Sync`?
    A `&mut T` is exclusive: sending it to another thread is like lending the value out for a while, and only that thread can touch it, so `T: Send` suffices. A `&T` can be copied, so sending one means the original thread may still read through its own copy at the same time, which is shared access and needs `T: Sync`. std writes `unsafe impl<T: Sync> Send for &T` for exactly this link.
  • Can a type be `Sync` but not `Send`?
    Yes. `std::sync::MutexGuard<T>` is `Sync` when `T: Sync`, because `&MutexGuard` only gives out `&T`, but it is never `Send`, because some platforms require a mutex to be unlocked on the thread that locked it. Several threads may read through a borrowed guard; only the locking thread may own and drop it.
  • Why does a closure passed to `thread::spawn` sometimes fail to be `Send` even though you never wrote a type?
    A closure is an anonymous struct of its captures, and auto traits follow the captures. If it captures anything non-`Send` — a raw pointer, a lock guard, a `dyn Trait` without `+ Send` — the closure is not `Send` and the spawn fails with E0277, whose notes name the captured type.

Send is permission to hand a parcel to someone in another building; Sync is permission for people in several buildings to read the same notice board at once. A parcel made only of shippable items is shippable without paperwork, which is what the auto-trait rule says.

  • You must write impl Send for every struct you pass to a thread.
  • Send and Sync are checked at run time when a thread starts.
  • Sync means the type contains its own lock.
  • A Box<dyn Fn()> is Send if the closure inside it is.
  • Any type that owns heap memory cannot be Send.