Sub topic 6
Auto traits: how the compiler derives Send and Sync
This chapter assumes you know the following:
- What
SendandSyncpromise. The earlier chapters covered this. - Trait bounds and generics.
- Closures and
move.
It explains how types get these traits without anyone writing impl Send for ....
Most traits are opt-in, auto traits are opt-out
Normally a type has a trait only if someone writes an impl block for it. You write #[derive(Clone)] or impl Display for Point, and without that the type does not implement the trait.
Send and Sync work the other way around. They are auto traits. The compiler implements them for a type automatically, based on the type's contents. The rule is:
- A struct, enum, union, tuple or array is
Sendif all of its fields areSend. - It is
Syncif all of its fields areSync.
The check is structural and recursive. A struct holding a Vec<String> is Send because Vec<String> is Send. That is true because String is Send, and so on down to primitives.
Seeing derivation in action
The assert_send and assert_sync helper functions are a cheap way to ask the compiler about a type. They have no body. A call only compiles if the bound holds.
use std::cell::Cell;
use std::marker::PhantomData;
fn assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}
struct Config {
name: String,
retries: u32,
}
struct Stats {
hits: Cell<u32>,
}
struct Wrapper<T> {
value: T,
}
enum Message {
Text(String),
Number(i64),
Pair(Vec<u8>, Box<Config>),
}
struct Tagged {
id: u32,
_not_thread_safe: PhantomData<*const ()>,
}
fn main() {
// Every field is Send and Sync, so the struct is both.
assert_send::<Config>();
assert_sync::<Config>();
// Cell<u32> is Send but not Sync, so Stats inherits exactly that.
assert_send::<Stats>();
// Generic structs depend on their parameter.
assert_send::<Wrapper<String>>();
assert_sync::<Wrapper<Vec<i32>>>();
// Enums need every variant's payload to qualify.
assert_send::<Message>();
assert_sync::<Message>();
// Tuples and arrays work the same way.
assert_send::<(u8, String, [i32; 4])>();
// These lines would fail to compile if uncommented:
// assert_sync::<Stats>();
// assert_send::<Wrapper<std::rc::Rc<i32>>>();
// assert_send::<Tagged>();
// assert_sync::<Tagged>();
let _ = Config { name: String::new(), retries: 0 };
let _ = Message::Text(String::new());
let _ = Message::Number(0);
let _ = Message::Pair(Vec::new(), Box::new(Config { name: String::new(), retries: 0 }));
let _ = Stats { hits: Cell::new(0) };
let _ = Wrapper { value: 1 };
let _ = Tagged { id: 1, _not_thread_safe: PhantomData };
}The program compiles and prints nothing. The commented lines show where it would stop compiling.
Stats shows the key point. Its only field is Cell<u32>, which is Send and not Sync. The compiler gives Stats the same pair of results without any attribute or impl.
Generic types get conditional impls
For Wrapper<T>, the compiler effectively writes this:
// What the compiler derives, conceptually (you cannot write this on stable for auto traits):
// impl<T: Send> Send for Wrapper<T> {}
// impl<T: Sync> Sync for Wrapper<T> {}The bound is inferred from the fields. You never state it, and it follows the type parameter. Wrapper<String> is Send, and Wrapper<Rc<i32>> is not.
Closures follow the same rule. A closure is a compiler-generated struct whose fields are its captures. A closure that captures an Rc is not Send. This is why a move closure that moves an Rc into thread::spawn fails to compile. The closure is not Send, so it cannot satisfy the bound on spawn.
Where the leaf cases come from
Structural derivation needs base cases. Those come from the standard library, which declares a few explicit impls that override the automatic rule. The important ones are:
| Type | Send | Sync | Reason |
|---|---|---|---|
| `*const T`, `*mut T` | no | no | Explicit negative impls. The compiler cannot know what the pointer means. |
| `Rc<T>` | no | no | Non-atomic reference count. |
| `Cell<T>`, `RefCell<T>` | if `T: Send` | no | Unsynchronized interior mutability. |
| `&T` | if `T: Sync` | if `T: Sync` | Explicit impl in `core`. |
| `&mut T` | if `T: Send` | if `T: Sync` | Explicit impl in `core`. |
| `Arc<T>` | if `T: Send + Sync` | if `T: Send + Sync` | Explicit `unsafe impl` with bounds. |
| `Mutex<T>` | if `T: Send` | if `T: Send` | Explicit `unsafe impl`. |
Two kinds of override exist. A negative impl, written impl !Send for Rc<T>, removes an auto trait. A positive unsafe impl adds it back where the field structure would say no. Arc and Mutex need this because they contain raw pointers or UnsafeCell, which would otherwise rule them out. Their authors have checked the code and take responsibility for it.
Negative impls and the auto trait keyword are unstable. On stable Rust you cannot define your own auto traits or write impl !Send. You can only use the existing ones and opt out through a field, as shown next.
How the decision is made
An explicit impl always wins over the structural rule. If there is none, one failing field is enough to make the whole type fail.
Opting out without unstable features
Suppose your type is not thread-safe for reasons the compiler cannot see. It might wrap a handle to a thread-local resource, or a C library that must be called from one thread. On stable Rust you add a marker field. PhantomData<*const ()> takes no space at runtime and holds a raw pointer type in its signature, so it makes the whole struct neither Send nor Sync. The Tagged struct in the example above does this. A later chapter covers this technique in more detail.
Trait objects do not carry the traits automatically
The structural rule works on concrete types. A trait object such as dyn Fn() hides its concrete type, so the compiler cannot look at its fields. It only knows what you wrote in the type. Box<dyn Fn()> is therefore not Send, even if the closure inside is. You have to add the bound yourself:
use std::thread;
fn main() {
let jobs: Vec<Box<dyn FnOnce() -> i32 + Send>> = vec![
Box::new(|| 1),
Box::new(|| 2),
Box::new(|| 3),
];
let handles: Vec<_> = jobs
.into_iter()
.map(|job| thread::spawn(move || job()))
.collect();
let total: i32 = handles.into_iter().map(|h| h.join().unwrap()).sum();
println!("total = {}", total);
}This prints total = 6. If you remove + Send from the dyn type, the thread::spawn call fails, because Box<dyn FnOnce() -> i32> is not Send. The error is raised where the box is moved into the spawned closure, not where the vector is built. Adding + Send there is the fix.
Gotchas
- Private fields count. Auto traits look at all fields, public or not. Adding an
Rcto a private field of a public struct silently removesSendandSyncfrom it. Downstream code that moves the struct across threads then breaks, even though no public signature changed. Library authors treat auto-trait status as part of the public API, and many add compile-time assertions such asassert_send::<MyType>()in their tests to catch regressions. - Auto traits leak through return types. A function returning
impl Traithides the concrete type from callers, but the compiler still knows whether it isSend, and callers can rely on that. This matters for async functions later in the tutorial. - Explicit impls bypass the check. An
unsafe impl Send for X {}tells the compiler to stop looking at the fields. If the claim is wrong, data races become possible in code that has no otherunsafe. This is why those impls need bounds likeT: Send, covered in a later chapter. - Derivation is all-or-nothing per trait.
SendandSyncare computed separately. A type can have one without the other, asStatsdoes.
Exercise
Given the struct below, is Job Send? Is it Sync? Name the field that decides each answer.
struct Job {
id: u64,
log: std::sync::Arc<std::sync::Mutex<Vec<String>>>,
cache: std::cell::RefCell<Vec<u8>>,
}
Show answer
Job is Send and not Sync. u64 is both. Arc<Mutex<Vec<String>>> is both, because Vec<String> is Send and Mutex<T> is Sync when T: Send. RefCell<Vec<u8>> is Send because Vec<u8> is Send, but it is not Sync. That one field removes Sync from the whole struct, while Send survives.
Exercise
A library publishes pub struct Client { /* private fields */ } that is Send and Sync. In a patch release, the author adds a private field last_seen: Rc<str> to cache a string. No public function signature changes. Why is this still a breaking change for users?
Show answer
The auto traits are derived from all fields, including private ones. Rc<str> is neither Send nor Sync, so Client loses both. Any user code that moved a Client into thread::spawn, or shared it through Arc, stops compiling. Auto-trait status is therefore part of the public API.