In stable Rust, how do you stop a struct holding only a `u32` index into a per-thread registry from being `Send` and `Sync`?
answer
- auto traits see only the fields
- negative impls are not stable
- a zero-sized marker field
- PhantomData of a raw pointer
basics
~20 sAdd a zero-sized PhantomData<*const ()> field. PhantomData<T> carries T's auto traits, and raw pointers are neither Send nor Sync, so the struct loses both; impl !Send is a negative impl, which stable rustc rejects with E0658.
solid answer
~40 sA struct whose fields are all `Send` and `Sync` gets both automatically, so a bare `u32` index would be movable to any thread even though it is only meaningful on the thread whose registry issued it. On stable Rust you cannot write `impl !Send for ThreadSlot {}`: negative impls are unstable, and rustc 1.99.1 reports E0658 "negative impls are experimental" with the hint "use marker types for now". The marker is a `PhantomData` field: `PhantomData<T>` is zero-sized but has the auto traits `T` has, so `PhantomData<*const ()>` removes both `Send` and `Sync`. Pick the marker for the half you need: `PhantomData<Cell<()>>` keeps `Send` and drops `Sync`; `PhantomData<MutexGuard<'static, ()>>` keeps `Sync` and drops `Send`.
code
rust · 25 linesuse std::cell::Cell;
use std::marker::PhantomData;
use std::sync::MutexGuard;
fn assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}
// Only a u32, so without the marker it would be Send + Sync.
#[allow(dead_code)]
struct ThreadSlot {
index: u32,
_not_send_sync: PhantomData<*const ()>,
}
#[allow(dead_code)]
struct SendOnly(PhantomData<Cell<()>>);
#[allow(dead_code)]
struct SyncOnly(PhantomData<MutexGuard<'static, ()>>);
fn main() {
assert_send::<SendOnly>();
assert_sync::<SyncOnly>();
// assert_send::<ThreadSlot>(); // E0277: `*const ()` cannot be sent between threads safely
println!("markers checked");
}go deeper
Recall that a struct made of Send and Sync fields gets both traits automatically, and that a zero-sized PhantomData field is how you take them away.
Explain that PhantomData<T> mirrors T's auto traits, why negative impls fail on stable with E0658, and which marker removes only Send or only Sync.
Spot thread-bound handles whose data looks innocent, add the right marker early, and lock it in with a compile_fail doctest so a refactor cannot restore Send.
Decide auto traits at API design time, since removing Send or Sync from a published type later breaks every caller that spawned it.
## Why a plain index is too permissive `Send` and `Sync` are **auto traits**: rustc implements them for a struct whose fields all implement them. That is the right default almost always, but it can be wrong when a type's *meaning* is tied to one thread while its *data* is something innocent. Consider a handle into a per-thread registry: - The registry lives in a `thread_local!` and hands out `ThreadSlot { index: u32 }` values. - Unsafe code elsewhere uses `index` to reach into that thread's storage without bounds or ownership checks, trusting that the slot is only ever used where it was issued. - A `u32` is `Send` and `Sync`, so rustc would happily let safe code move a `ThreadSlot` to another thread, where the same index points into a different registry. The Nomicon calls this the rare case of a type that is "inappropriately automatically derived to be Send or Sync", and notes that it only matters when other unsafe code gives the type special meaning. ## The stable tool: a PhantomData marker The direct syntax is a **negative impl**, the form std itself uses (`impl<T> !Send for *const T {}`). On stable Rust it is rejected: ```plaintext error[E0658]: negative impls are experimental = help: use marker types for now ``` The marker-type technique works because of how `std::marker::PhantomData<T>` is defined: a zero-sized struct that the compiler treats as if it owned a `T`. Auto traits are computed through it, so `PhantomData<T>` is `Send` exactly when `T` is, and `Sync` exactly when `T` is. Adding a field costs nothing at run time: ```rust use std::marker::PhantomData; struct ThreadSlot { index: u32, _not_send_sync: PhantomData<*const ()>, } ``` Raw pointers carry std's negative impls for both traits, so `ThreadSlot` is now neither `Send` nor `Sync`. Moving one into `thread::spawn` fails with E0277: "`*const ()` cannot be sent between threads safely", followed by notes that it appears within `PhantomData<*const ()>` and within `ThreadSlot`. The struct literal now needs `_not_send_sync: PhantomData` wherever it is built, which a private field and a constructor keep inside the module. ## Choosing the marker for the half you need The marker's auto traits decide which half you remove: | Marker field | `Send` | `Sync` | Typical intent | |---|---|---|---| | `PhantomData<*const ()>` | no | no | thread-bound handle | | `PhantomData<Cell<()>>` | yes | no | movable, but not usable through `&` on several threads | | `PhantomData<MutexGuard<'static, ()>>` | no | yes | must stay on its thread, readable through `&` | `Cell<()>` and `MutexGuard<'static, ()>` are used here only for their auto traits; why `Cell` is not `Sync` is covered in the lesson on `Cell` and `RefCell`. A second route to a "Sync but not Send" type is the raw-pointer marker followed by `unsafe impl Sync`, which is exactly how the lock_api crate behind parking_lot spells its `GuardNoSend(*mut ())` marker. That re-adds a promise, so it needs the same justification as any other unsafe impl. ## Steps to apply it 1. Decide which promise is false for your type: transfer (`Send`), sharing (`Sync`) or both. 2. Add a private, zero-sized `PhantomData` field whose type has exactly the auto traits you want. 3. Construct the type only through functions in its module, so callers never write the marker. 4. Add a compile-time check, for example a doctest marked `compile_fail` that calls an `assert_send::<ThreadSlot>()` helper, so a later refactor cannot silently restore the trait. ## Things to keep in mind - The marker passes on **every** auto trait the inner type lacks, not only the one you were thinking of, so check the others (such as `Unpin` and `UnwindSafe`) when you pick an unusual marker type. - `PhantomData` also influences variance and drop checking; for a lifetime-carrying marker those effects belong to the lesson on variance. - Removing `Send` or `Sync` from a published type later is a breaking change for anyone who spawned it, which is why it is easier to opt out from the start. - Put a short comment beside the marker field saying which promise it removes and why, so a reviewer does not delete an apparently unused field. - Opting out is safe code: you can never cause undefined behaviour by making a type *less* thread-safe. Opting back in with `unsafe impl` is where the risk lives.
- Why not just write `impl !Send for ThreadSlot {}`?Negative impls are an unstable feature. On stable rustc 1.99.1 the line fails with E0658 "negative impls are experimental" and the hint "use marker types for now"; adding `#![feature(negative_impls)]` instead fails with E0554 because `#![feature]` is refused on the stable channel. Only std uses negative impls today.
- Does a `PhantomData<*const ()>` field cost memory or change the struct's layout?No. `PhantomData<T>` is a zero-sized type for every `T`, so the struct stays the size of its real fields. What changes is purely type-level: auto traits, variance and drop-check treat the struct as if it held a `*const ()`.
- Write impl !Send for the type; it works on stable Rust.
- A PhantomData field adds a pointer's worth of memory to the struct.
- Opting out of Send requires an unsafe block.
- Any PhantomData field removes both Send and Sync.