What is an auto trait in Rust?

An auto trait is the new name for the terribly named1 opt-in, built-in trait (OIBIT).

These are an unstable feature where a trait is automatically implemented for every type unless they opt-out or contain a value that does not implement the trait:

#![feature(optin_builtin_traits)]

auto trait IsCool {}

// Everyone knows that `String`s just aren't cool
impl !IsCool for String {}

struct MyStruct;
struct HasAString(String);

fn check_cool<C: IsCool>(_: C) {}

fn main() {
    check_cool(42);
    check_cool(false);
    check_cool(MyStruct);
    
    // the trait bound `std::string::String: IsCool` is not satisfied
    // check_cool(String::new());
    
    // the trait bound `std::string::String: IsCool` is not satisfied in `HasAString`
    // check_cool(HasAString(String::new()));
}

Familiar examples include Send and Sync:

pub unsafe auto trait Send { }
pub unsafe auto trait Sync { }

Further information is available in the Unstable Book.


1 These traits are neither opt-in (they are opt-out) nor necessarily built-in (user code using nightly may use them). Of the 5 words in their name, 4 were outright lies.

Leave a Comment