Update: I have submitted this as an RFC!
Hello everyone, i recently drafted an RFC for an addition to trait declaration syntax which would allow users to explicitly mark that a trait must always be trait object safe.
You can find a completed draft version of the RFC here
The TLDR of the proposal is that a very common design pattern observed is using a trait as a trait object, then having a private function to make sure it is always object-safe, this is used in libcore for iterators for example:
fn _assert_is_object_safe(_: &dyn MyTrait) {}
This works, but it is a bit ugly and kind of a hack, moreover, if the trait is not object safe and you try to use it as a trait object, you get errors with multiple labels. This can be confusing because the ranges are not in the impl block, they are just on the usage. To solve both of these issues, this RFC proposes a simple addition to trait declaration syntax:
dyn trait MyTrait { /* */ }
marking a trait declaration as dyn
would enforce at compile time that the trait must be object safe, and if it is not, then errors with accurate ranges are thrown. This is more explicit and easier to see if a trait is explicitly meant to be used as a trait object.
Users would be encouraged to use this syntax through help messages in the current trait object unsafety error, as well as lints which will be upgraded to errors in edition 2024.
I'd love to hear any feedback or complaints about the proposal!