3 ms·
> The best way to get around this is to use something like `Vec<Box<dyn EventHandler>>`. That's exactly the right solution to your problem. It's not a workarou
by kccqzy 6y ago
> The best way to get around this is to use something like `Vec<Box<dyn EventHandler>>`.
That's exactly the right solution to your problem. It's not a workaround. It is what you need.
What you need is a heterogenous collection of objects that implement a common interface. And the exact type isn't available to you because it's provided by the client. So you need to go through virtual (or dynamic) dispatch.
Just imagine how you might write this in C++: you just define an EventHandler abstract class and ask that clients inherit from it. Then you take pointers to EventHandler and store them.
Or imagine how you might write it in Haskell: simple existential types. The type class dicts are stored by the compiler into your data type to enable dynamic dispatching.
This is object-oriented polymorphism 101. I think Rust's anti-OO pendulum has swung so far that people can't even see that what they need is basic OO.
- gpderetta 6y agoIt is not even OO, as the Haskell example shows. But I understand completely the mindset. If you think that you can implement your solution with full static dispatching and no pointer indirection, having to add these "ugly workarounds" feels like surrendering. But there is a continuum between full static dispatch and boxing and indirection everywhere. Adding a few carefully chosen "dynamic joints" can add a lot of runtime flexibility at a minimal cost.
- saghm 6y ago> That's exactly the right solution to your problem. It's not a workaround. It is what you need Yep, I agree! To clarify, the issue for me isn't having to use trait objects like this, it's the ergonomic issues that my parent comment brought up, e.g. not being able to require `EventHandler: Clone`. I'm not opposed to trait objects themselves; I just wish they were easier to use.