简体   繁体   中英

What is an auto trait in Rust?

Trying to solve the problem described in Trait bound Sized is not satisfied for Sized trait , I found the following code gives the following error:

trait SizedTrait: Sized {
    fn me() -> Self;
}

trait AnotherTrait: Sized {
    fn another_me() -> Self;
}

impl AnotherTrait for SizedTrait + Sized {
    fn another_me() {
        Self::me()
    }
}
error[E0225]: only auto traits can be used as additional traits in a trait object
 --> src/main.rs:9:36
  |
9 | impl AnotherTrait for SizedTrait + Sized {
  |                                    ^^^^^ non-auto additional trait

But the Rust Book does not mention auto trait at all.

What is an auto trait in Rust and how does it differ from a non-auto trait?

An auto trait is the new name for the terribly named 1 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM