3 ms·
Responding to your updated question: > What I really meant was that you can't have Vec<T> where T is a trait without also wrapping that in a box, which for me
by oconnor663 9y ago
Responding to your updated question:
> What I really meant was that you can't have Vec<T> where T is a trait without also wrapping that in a box, which for me in turn doesn't work for a bunch of other reasons.
You can use any type of pointer to refer to a trait object, not just Box. In particular, you can use &T where T is a trait. The vtable work happening at runtime is the same, but the object can live e.g. on the stack or in a vec somewhere. Of course, if you're using references, you have to convince the compiler that the object is going to stay put for as long as the reference exists, as usual for Rust. When that's not practical, usually a Box or Rc/Arc is the go-to solution. Could you tell me more about what makes Box not work for your use case?
Aside: Trait objects are one of the more complicated features of Rust, and they run into tricky limitations (like "object safety"). It's often people's first instinct to use trait object anywhere they would've used a shared base class in some other language, but that's not usually the best pattern. Using concrete types with trait bounds (`&T .. where T: MyTrait` rather than `&MyTrait`), or inventing a new enum to hold all the types you expect, or even just trying to make ordinary composition work, is usually both easier and more performant.
- kibwen 9y ago> You can use any type of pointer to refer to a trait object, not just Box. In particular, you can use &T where T is a trait. You can, though due to the extra annotations required I don't suggest that people new to the language try to use trait objects with references. (Hell, I try to keep people new to the language away from trait objects entirely, they're pretty restrictive.)
- oconnor663 9y agoYeah I added a followup bit probably after you wrote your comment. My suspicion now is that parent is running into the "C++ inheritance -> Rust trait objects" mismatch, and that they should probably try to use something else.