pretzelhammer / rust-blog

Educational blog posts for Rust beginners
Apache License 2.0
7.53k stars 396 forks source link

Sized is not an auto trait #28

Closed whatisaphone closed 3 years ago

whatisaphone commented 3 years ago

This section starts with "The Sized trait in Rust is an auto trait". However, the compiler disagrees.

Code:

trait Foo {}

fn foo(_: Box<dyn Foo + Sized>) {}

Output:

error[E0225]: only auto traits can be used as additional traits in a trait object
 --> src/lib.rs:3:25
  |
3 | fn foo(_: Box<dyn Foo + Sized>) {}
  |                   ---   ^^^^^ additional non-auto trait
  |                   |
  |                   first non-auto trait
  |
  = help: consider creating a new trait with all of these as super-traits and using that trait here instead: `trait NewTrait: Foo + Sized {}`
  = note: auto-traits like `Send` and `Sync` are traits that have special properties; for more information on them, visit <https://doc.rust-lang.org/reference/special-types-and-traits.html#auto-traits>
pretzelhammer commented 3 years ago

That code example is very contrived. All trait objects are unsized so writing dyn Trait + Sized would never compile in any context, even if Sized was an auto trait. It's the kind of example someone would only pull out if they were trying to win an argument on the internet by being pedantic.

That section you linked ends with:

Also, to be super pedantic Sized is not technically an auto trait since it's not defined using the auto keyword but the special treatment it gets from the compiler makes it behave very similarly to auto traits so in practice it's okay to think of it as an auto trait.

Key Takeaways

  • Sized is an "auto" marker trait

Occasionally, for teaching purposes, it's more effective to introduce slight inaccuracies which are then corrected later in the text than to be 100% accurate from the beginning because it gives you more time to shape the reader's mental model from a high-level and at a comfortable pace without overloading them or bogging them down with distracting technical minutiae.

Also, I love getting feedback, but I love it even more when it comes from someone who read the entire article first. I noticed that reading the entire article also significantly raises the quality of the feedback as well. Please consider that for next time. Thank you.