Sub topic 17
Marker traits: Copy, Send, Sync, and Sized
This chapter assumes you can define and implement traits, write trait bounds, and use Box, Rc, and Arc at a basic level. You also need to know what a thread is and what ownership means for moves and borrows.
What a marker trait is
A marker trait has no methods. Implementing it states a fact about a type, and the compiler or library code relies on that fact. Four of them shape everyday Rust:
Copy: values can be duplicated with a bitwise copy.Send: values can be moved to another thread.Sync: references to values can be shared between threads.Sized: the size of the type is known at compile time.
You can write your own marker trait, and bounds can then require it:
trait Verified {}
struct Email(String);
struct Unchecked(String);
impl Verified for Email {}
fn send_mail<T: Verified>(_to: &T) {
println!("sent");
}
fn main() {
send_mail(&Email(String::from("[email protected]")));
// send_mail(&Unchecked(String::from("x"))); // error: Verified is not implemented
let _ = Unchecked(String::new());
}The standard library markers differ from this one in a few ways. Send, Sync, and Sized are implemented automatically by the compiler. Copy is opt-in, but it changes how the language treats moves.
Copy
By default, assigning a value moves it, and the old binding becomes unusable. A type that implements Copy is duplicated instead, so both bindings stay valid.
#[derive(Debug, Clone, Copy)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let a = Point { x: 1, y: 2 };
let b = a; // copied, not moved
println!("{a:?} {b:?}");
}The rules for Copy:
CopyhasCloneas a supertrait, so you must derive or implement both.- Every field must be
Copy. A struct holding aStringorVeccannot beCopy, because duplicating it bitwise would create two owners of one heap allocation. - A type that implements
Dropcannot beCopy. - Shared references
&TareCopy. Mutable references&mut Tare not. - Integers, floats,
bool,char, raw pointers, and tuples or arrays ofCopytypes areCopy.
Implementing Copy is a promise you cannot easily take back. If you later add a String field, every place that relied on implicit copying stops compiling. Derive Copy for small value types such as points, ids, and flags. Leave it off for anything that owns resources.
Send and Sync
These two traits are how Rust prevents data races at compile time.
T: Sendmeans ownership of aTcan be transferred to another thread.T: Syncmeans&Tcan be shared between threads. Formally,TisSyncexactly when&TisSend.
They are auto traits. The compiler implements them for a struct when all of its fields implement them, so you rarely write them by hand. The standard library marks the exceptions:
| Type | Send | Sync | Reason |
|---|---|---|---|
| `i32`, `String`, `Vec<i32>` | yes | yes | Plain owned data |
| `Rc<T>` | no | no | Reference count is not atomic |
| `Arc<T>` | if `T: Send + Sync` | if `T: Send + Sync` | Atomic reference count |
| `Cell<T>`, `RefCell<T>` | if `T: Send` | no | Interior mutability without locking |
| `Mutex<T>` | if `T: Send` | if `T: Send` | The lock serializes access |
| `*const T`, `*mut T` | no | no | The compiler assumes nothing about raw pointers |
| `MutexGuard<T>` | no | if `T: Sync` | A lock must be released on the thread that took it |
thread::spawn requires its closure to be Send + 'static, so these traits are checked every time you spawn a thread:
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = Vec::new();
for _ in 0..4 {
let counter = Arc::clone(&counter);
handles.push(thread::spawn(move || {
*counter.lock().unwrap() += 1;
}));
}
for h in handles {
h.join().unwrap();
}
println!("{}", *counter.lock().unwrap());
}If you replace Arc with Rc, the compiler rejects the program with an error such as "Rc<Mutex<i32>> cannot be sent between threads safely". The error points at the missing Send implementation, not at the line where the data race would have happened.
Checking a type with a helper function
You can test whether a type has these traits by calling an empty generic function that demands them:
use std::sync::Arc;
fn assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}
struct Handle(*mut i32);
// SAFETY: the pointer is only used by one thread at a time.
unsafe impl Send for Handle {}
fn main() {
assert_send::<String>();
assert_sync::<Vec<i32>>();
assert_send::<Arc<i32>>();
assert_send::<Handle>();
// assert_send::<std::rc::Rc<i32>>(); // does not compile
println!("all checks passed");
}Handle contains a raw pointer, so it is not Send automatically. The unsafe impl is the programmer's promise that moving it between threads is sound. The compiler does not verify that promise. A wrong unsafe impl Send or Sync reintroduces data races, so use it only when you can state the invariant that makes it true.
Sized and ?Sized
A type is Sized if the compiler knows its size at compile time. Local variables, function arguments, and return values must have a known size, so every generic parameter has an implicit T: Sized bound.
Some types have no compile-time size. These are dynamically sized types (DSTs):
str- slices such as
[i32] - trait objects such as
dyn Display
You can only use a DST behind a pointer, such as &str, Box<[i32]>, or Box<dyn Shape>. The pointer is "fat": it stores an address plus extra data, which is the length for slices and strings or the vtable pointer for trait objects.
To accept a DST in generic code, relax the implicit bound with ?Sized:
use std::fmt::Debug;
fn show<T: ?Sized + Debug>(value: &T) {
println!("{value:?}");
}
fn main() {
show("hello"); // T = str
show(&[1, 2, 3][..]); // T = [i32]
show(&42); // T = i32
}Without ?Sized, the first two calls fail because str and [i32] do not satisfy T: Sized. ?Sized is the only "maybe" bound in Rust. It means "may or may not be Sized", which widens what the function accepts.
Sized also connects to dyn compatibility from the earlier chapter. A trait method with a where Self: Sized bound is excluded from the vtable, so the trait can still be used as a trait object while that method stays callable only on concrete types.
Common errors
- Using
Rcacross threads. The error mentionsSend. Switch toArc, and addMutexorRwLockif you need mutation. - Deriving
Copyon a type with aStringfield. The compiler reports that the field does not implementCopy. RemoveCopy, or change the field type. - Deriving
CopywithoutClone.CopyrequiresClone, so derive both. - Sharing a
RefCellbetween threads.RefCellis notSync. UseMutexinstead. - Holding a
MutexGuardacross an.await. In async code that may move between threads, the guard is notSend, so the future is notSendeither. Drop the guard before awaiting. - Writing
unsafe impl Sendto silence an error. The error usually reflects a real problem. Fix the data design first. - Writing
fn f<T: Debug>(x: &T)and then passing&str.Tmust beSized. Add?Sized.
Exercise
A struct holds a Vec<i32> and a std::cell::Cell<u8>. Is it Send? Is it Sync? Explain using the field rules.
Show answer
It is Send, because Vec<i32> is Send and Cell<u8> is Send when u8 is Send. It is not Sync, because Cell is not Sync: it allows mutation through a shared reference without any locking, and the struct inherits that restriction from its field. Wrapping the whole struct in a Mutex makes it shareable between threads.
Exercise
Why does this declaration fail, and what is the smallest change that fixes it?
#[derive(Clone, Copy)] struct Config { name: String }
Show answer
String owns a heap allocation and is not Copy, so Config cannot be Copy either. The smallest fix is to remove Copy from the derive list and keep Clone, so callers duplicate with .clone(). Alternatively, change name to &'static str, which is Copy.
Exercise
Write the signature of a function byte_len that accepts a reference to any type implementing AsRef<[u8]>, including str and [u8] themselves, and returns its length in bytes.
Show answer
fn byte_len<T: AsRef<[u8]> + ?Sized>(value: &T) -> usize { value.as_ref().len() }. The ?Sized bound is required so that T can be str or [u8]. Without it, only String, Vec<u8>, and other sized types would be accepted.