10 ms·
The linked thread is good, but the short answer: Box<Foo> If Foo is a struct, this is a single pointer to the heap. If Foo is a trait, this is a double po
by steveklabnik 8y ago
The linked thread is good, but the short answer:
Box<Foo>
If Foo is a struct, this is a single pointer to the heap. If Foo is a trait, this is a double pointer: a pointer to the data on the heap, and a pointer to a vtable for its methods. These two things are very different, but look similar. That's the mistake.
This change separates the two. Now:
Box<dyn Foo>
is always the latter, a "trait object". We have to keep the old syntax working for stability reasons, but can lint against it, so that it nudges you into the better syntax. So in this world,
// always a single pointer to a struct (or enum)
Box<Foo>
// always a double pointer
Box<dyn Foo>
This is more clear for humans. The compiler can tell with 100% fidelity, of course. But humans aren't compilers. Different things with different costs look different.
As an addendum, the parent mentions another feature, "impl Trait", which can be used with traits. Their point was, originally, Box<Trait> was the only thing that existed like this. With "impl Trait", it was "impl Trait" vs "Trait", and is now "impl Trait" vs "dyn Trait", which is much more clear, at least in many people's opinions. :)
- KwanEsq 8y ago>We have to keep the old syntax working for stability reasons Will Rust 2018 enable you to remove the old syntax? Or is that a bigger change than the opt-in is allowed to cover?
- db48x 8y agoYes, the next edition will allow breaking changes, while still allowing you to use crates written in the older edition.
- steveklabnik 8y agosome forms of breaking changes. This is of that kind, though we cannot make arbitrary ones.
- steveklabnik 8y agoThis kind of change is the kind an edition can make, though I’m not 100% sure if the plan for 2018 is to warn or error on the older syntax.
- lewisinc 8y agoI feel like a warning for one edition and error on the next would make it straightforward as to how much time is left to update the code.
- steveklabnik 8y agoThat’s generally true, the question is, do you warn in 2015 or 2018? That being said, this particular fix is 100% automatable, and rustfix can already do it, so the time to update is “a few seconds”.
- dikaiosune 8y agoRust's built-in lints are configurable with compiler directives, so you'll be able to add #![deny(bare_trait_objects)] To the top of your crate and cause a compiler warning if someone uses the old syntax on your project. EDIT: just realized I mis-parsed "you" in parent. Oh well.
- littlestymaar 8y agoIIRC, it will take two editions before removing something: at the first edition the compiler will lint against it (which is already quite a big change: you get tons of new warnings you need to fix) and one edition later, it's an error. Edit: I didn't see the answer from steveklabnik below. Apparently, it's not clearly decided yet.