What is an auto trait in Rust?

后端 未结 1 1065
伪装坚强ぢ
伪装坚强ぢ 2020-12-09 16:32

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 Size         


        
相关标签:
1条回答
  • 2020-12-09 16:57

    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.

    0 讨论(0)
提交回复
热议问题