Sub topic 17
Marker traits: Copy, Send, Sync, and Sized
This chapter assumes you know how to define and implement traits, how trait bounds work, and how ownership moves values. A marker trait has no methods. Implementing it is a promise about a type, and the compiler uses that promise to accept or reject code.
The four markers
| Trait | What it promises | Implemented how |
|---|---|---|
| `Copy` | Assigning the value copies its bits instead of moving it | `#[derive(Clone, Copy)]` |
| `Send` | Ownership of the value can move to another thread | Automatic |
| `Sync` | `&T` can be shared between threads | Automatic |
| `Sized` | The size is known at compile time | Automatic |
Copy
Copy changes how assignment behaves. A Copy type is duplicated on assignment, and the original stays usable. Copy requires Clone, so you derive both. A type can be Copy only if all its fields are Copy. A String field rules it out, because copying would duplicate ownership of a heap buffer.
#[derive(Clone, Copy, Debug)]
struct Meters(f64);
fn main() {
let a = Meters(2.5);
let b = a;
println!("{a:?} {b:?}");
}Without Copy, the println! would fail with a "borrow of moved value" error.
Send and Sync
The compiler implements Send and Sync automatically for any type whose fields are all Send or Sync. These are called auto traits. Sync is defined in terms of Send: T is Sync exactly when &T is Send.
Rc<T> is neither. Its reference count is not atomic, so two threads could corrupt it. Arc<T> uses an atomic count and works across threads.
use std::sync::Arc;
use std::thread;
fn main() {
let shared = Arc::new(vec![1, 2, 3]);
let worker = Arc::clone(&shared);
let handle = thread::spawn(move || worker.iter().sum::<i32>());
println!("{}", handle.join().unwrap());
}thread::spawn requires its closure to be Send. If you replace Arc with Rc, the compiler rejects the program with "Rc<Vec<i32>> cannot be sent between threads safely". The error appears at compile time, so a data race never reaches runtime.
Sized
Every generic parameter T has an implicit T: Sized bound. Types like str, [i32], and dyn Trait have no size known at compile time, so they cannot be stored in a local variable or passed by value. You opt out with ?Sized, which means "may or may not be sized". The type is then used behind a pointer.
use std::fmt::Display;
fn show<T: ?Sized + Display>(value: &T) {
println!("{value}");
}
fn main() {
show("a string slice");
show(&42);
}Without ?Sized, show("a string slice") would fail, because T would be str.
Common errors
- Deriving
Copyon a struct with aStringorVecfield. - Moving an
Rcor aRefCellreference intothread::spawn. UseArc, andMutexfor mutation. - Forgetting
?Sizedon a generic function that should acceptstrordyn Trait.
Exercise
Why does thread::spawn(move || println!("{}", rc_value)) fail to compile when rc_value is an Rc<i32>, and what is the usual fix?
Show answer
The closure captures an Rc<i32>, which is not Send because its reference count is not atomic. thread::spawn requires a Send closure. Replace Rc with Arc, which uses an atomic count and is Send and Sync when its contents are.
Exercise
Can #[derive(Clone, Copy)] be applied to struct Label { text: String }? Explain.
Show answer
No. Copy requires every field to be Copy, and String owns a heap allocation, so it is only Clone. The compiler reports that Copy cannot be implemented for this type.