36

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?

Martin
  • 967
  • 1
  • 6
  • 17
  • I think it would be any trait that is automatically implemented, it's certainly the case for `Sized`, but I wonder if this would apply to `Send` and `Sync`... – Matthieu M. Apr 07 '18 at 19:01
  • @MatthieuM. I think `Sized` might be even more special than `Send` and `Sync`... – Shepmaster Apr 07 '18 at 19:15

1 Answers1

47

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.

rustyhu
  • 1,912
  • 19
  • 28
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • I totally agree that the name of this feature is confusing. It's just caught me out (I was trying to opt *out* of `Send`). Thanks for the explanation. – Edd Barrett May 23 '18 at 14:48
  • what is the current state of this feature? I have a trait `Render` which should be implemented by everything which implements `Display`. – nuiun Jul 20 '21 at 07:29
  • @nuiun: I found out how to do this: `impl Render for D {...}` – nuiun Jul 20 '21 at 07:39