rust-unofficial / patterns

A catalogue of Rust design patterns, anti-patterns and idioms
https://rust-unofficial.github.io/patterns/
Mozilla Public License 2.0
7.85k stars 354 forks source link

Add example for static dispatch with enums to Command pattern #252

Open simonsan opened 3 years ago

simonsan commented 3 years ago

Enum is a one way to address the delegation (to commands). I think enums should be added too. I might add it too a bit later. However, there is also a simple trade off between dyn traits and enums. If delegation occurs externally (crates for example), then trait objects would suit better, since we don't know in advance what kind of type a user may come up with. Like in actix. But if we are going to use it in our own application then since we control the enum variants and if add new variants not too frequently, we could use enum.

Originally posted by @fade2black in https://github.com/rust-unofficial/patterns/issues/247#issuecomment-809739896

pickfire commented 3 years ago

Note that actix-web uses HashMap<Any, ...> for data extractor which trades off type safety (it will error out on runtime rather than compile time for the wrong type) for ergonomic, if we want to do something like this that allows users to use any type but with Any type (not sure if there are any other methods) we would want to state the downsides beforehand.