lotsoftools

Understanding Rust Error E0321

Introduction to Rust Error E0321

Rust Error E0321 occurs when a cross-crate opt-out trait is implemented on something that is not a struct or enum type. In Rust, only structs and enums are allowed to implement certain opt-out traits such as Send and Sync, and the struct or enum must be local to the current crate.

Example of Erroneous Code

#![allow(unused)]
#![feature(auto_traits)]

fn main() {
    struct Foo;

    impl !Sync for Foo {}

    unsafe impl Send for &'static Foo {}
    // error: cross-crate traits with a default impl, like `core::marker::Send`,
    //        can only be implemented for a struct/enum type, not
    //        `&'static Foo`
}

In the example above, the unsafe implementation of Send for &'static Foo results in Rust Error E0321 because the trait is being implemented on a reference type rather than a struct or enum type.

How to Fix Rust Error E0321

To fix Rust Error E0321, you should only implement opt-out traits for structs and enums that are local to the current crate. For example, if you have a struct named Foo, you can implement Send and Sync for this struct safely:

struct Foo;

impl !Sync for Foo {}

unsafe impl Send for Foo {}

In the corrected example, Send is implemented for the struct Foo instead of a reference type, resolving the error.

Conclusion

To avoid Rust Error E0321, always ensure that you implement opt-out traits such as Send and Sync for structs and enums that exist within the current crate. By adhering to this rule, your Rust code will compile without any issues related to this specific error.

Recommended Reading