How to Implement Unsafe Traits (Send, Sync)

You cannot manually implement `Send` or `Sync` for types containing interior mutability or unsafe code without using `unsafe` blocks, as these are marker traits that the compiler enforces automatically. To opt-in a custom type to these traits, you must declare an `unsafe impl` block asserting that y

How to Implement Unsafe Traits (Send, Sync)

You cannot manually implement Send or Sync for types containing interior mutability or unsafe code without using unsafe blocks, as these are marker traits that the compiler enforces automatically. To opt-in a custom type to these traits, you must declare an unsafe impl block asserting that your type satisfies the safety guarantees, which requires you to verify that the type can be safely transferred between threads (Send) or shared between threads (Sync).

struct MyCustomType {
    // Example: A field that is thread-safe, like an Arc<Mutex<...>>
    // or a raw pointer managed with strict invariants.
    data: std::sync::Mutex<i32>,
}

// SAFETY: MyCustomType is Send because Mutex<T> is Send.
// The data can be moved to another thread.
unsafe impl Send for MyCustomType {}

// SAFETY: MyCustomType is Sync because Mutex<T> is Sync.
// References to MyCustomType can be shared between threads,
// and the internal Mutex ensures safe concurrent access.
unsafe impl Sync for MyCustomType {}

fn main() {
    let my_type = MyCustomType {
        data: std::sync::Mutex::new(42),
    };
    
    // This compiles because we implemented Send and Sync
    println!("MyCustomType is Send and Sync");
}

Use this only when you have proven that your type's internal logic prevents data races, such as when using UnsafeCell correctly or wrapping FFI pointers.