Just released enum_downcast: safe downcasting of enums

As its name, it's the downcast version of enum_dispatch. While not using the Any trait, this provides a safe and static way to downcast an enum to its variant type in a generic style API like Any's one. Examples are here: enum_downcast/examples at main · ryo33/enum_downcast · GitHub

Let there be data types, A and B, if we want to need them to put together and, after that, need concrete types for them, there are two straightforward ways, and enum_downcast takes both benefits. One is storing them as dyn Any and using the downcast APIs. It's simple but loses the advantage in concrete type, not only for static dispatching but also for easy deserialization from JSON or something. Another way is defining an enum for them and implementing downcast_a and downcast_b manually, but, since it's not generalized, we need to manually implement variant-agnostic functions for all variants (imagine iter_a and iter_b).

c.f. rust - Generic downcast of enum variant - Stack Overflow

Basic example:

enum Enum {
    Items { vec: Vec<Item> },

let container = Enum::Player(Player { name: "Ryo".to_string() });
let _player_ref: &Player = container.downcast_ref::<Player>().unwrap();
let _player_mut: &mut Player = container.downcast_mut::<Player>().unwrap();
let player: Player = container.downcast::<Player>().unwrap();

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.