Send and Sync.// Example of auto traits: `Send` and `Sync`
// Any type that is safe to transfer across thread boundaries implements `Send`
// Any type that is safe to be referenced from multiple threads implements `Sync`
struct MyStruct;
// MyStruct automatically implements `Send` and `Sync` if all its fields do
fn main() {
let obj = MyStruct;
// `obj` can be safely sent to another thread if it implements `Send`
}
Auto traits in Rust, also known as automatically implemented traits, are a special category of traits that the compiler can automatically implement for types under certain conditions. They are used to represent certain properties of types rather than behaviors. Here’s what makes auto traits unique:
Send, Sync, Unpin, UnwindSafe, and RefUnwindSafe1.impl !AutoTrait for MyType {}1.Send) or can be safely shared across threads (Sync)1.Auto traits are a powerful feature in Rust because they allow the compiler to make certain guarantees about types without the programmer having to write boilerplate code. For example, if you have a type composed entirely of Send types, Rust can automatically determine that your type is also Send.
Here’s a simple example of how an auto trait works:
// `Send` is an auto trait
struct MyStruct {
data: Vec<u8>,
}
// `MyStruct` automatically implements `Send` because `Vec<u8>` is `Send`
In this case, MyStruct automatically implements Send because all of its fields do. If MyStruct had a field that did not implement Send, then MyStruct would not automatically implement Send, and you would have to explicitly opt out of Send for MyStruct if necessary.
Auto traits are a core part of Rust’s type system and concurrency model, helping to enforce thread safety and other properties at compile time.