Course contentsShow
← Rust
Lesson 533 of 1,9105. Type System and TraitsFree lesson

Auto Traits and Send/Sync Concurrency

Master thread-safety marker traits to safely share data across concurrency primitives.

In this lesson, you will learn how Rust uses the marker traits Send and Sync to enforce memory safety when sharing data across threads.

In Rust, concurrency safety isn't just a convention—it is enforced by the compiler. To manage this, Rust uses two special "Auto Traits": Send and Sync. These traits have no methods; they are marker traits that tell the compiler whether it is safe to move or share a type across thread boundaries.

Understanding Send and Sync

  • Send: A type is Send if it is safe to transfer ownership of a value from one thread to another. Most types in Rust are Send by default (like i32 or String). However, types that hold non-thread-safe resources—like Rc<T>—are not Send because they cannot guarantee that the reference count remains accurate when accessed across threads.
  • Sync: A type is Sync if it is safe to be accessed by multiple threads simultaneously through a shared reference (&T). A type T is Sync if and only if &T is Send. This ensures that shared data cannot cause a data race.

Why Auto Traits?

These traits are called "Auto Traits" because the compiler automatically derives them for you. If a struct consists entirely of Send and Sync types, the compiler automatically marks your struct as Send and Sync as well. You don’t need to implement them manually!

Consider this example:

struct MyData {
    value: i32,
    name: String,
}

// Because both i32 and String are Send/Sync,
// MyData is automatically Send and Sync.

If you add a field that is not Send (like Rc<T>) to MyData, the compiler will automatically realize that MyData is no longer Send and will trigger a compile-time error if you attempt to move that struct into a thread. This prevents data races before your program even runs. You are leveraging the type system to guarantee thread safety without manual bookkeeping.

Key Takeaway: Send and Sync are marker traits that the compiler automatically applies to your types to prove they are safe for concurrent access, preventing data races at compile time.