ryo33 / enum_downcast

Safe downcasting for enums
3 stars 0 forks source link

Trying to understand why this does what it does. #1

Open nain-F49FF806 opened 4 months ago

nain-F49FF806 commented 4 months ago

Hi, I saw your post on rust discourse, and ended up here. I have been looking at enum_dispatch and similar projects.

I am trying to understand if this does something different, than another approach I was thinking of using in my project.


// from readme 

#[derive(EnumDowncast)]
enum Enum {
    Player(Player),
    Enemy(Enemy),
    Items { vec: Vec<Item> },
    #[enum_downcast(skip)]
    Other,
}

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();

I was considering using macro to automatically implement TryFrom<_> trait

impl TryFrom<Player> for Enum {
...
}

impl TryFrom<Enemy> for Item {
...
}

// ..and so on

So you can do

let container = Enum::Player(Player { name: "Ryo".to_string() });
let player: Player = container.try_into().unwrap();

Does downcast solve a similar problem, or is it doing something else?

Also, this would be good for the readme: how does downcast handle the Items variant? That seems like an interesting case. :)

ryo33 commented 4 months ago

I'm glad that you reaching my obscure but favorite crate.

This crate generates AsVariant impl for each variant like your TryFrom one. A difference is that it emits 3 trait impls for each variant, AsVariant for downcast_ref, AsVariantMut for downcast_mut, and IntoVariant for downcast.

https://github.com/ryo33/enum_downcast/blob/2c44915065825991229d2aaf4dabf548a07bf53f/crates/enum_downcast_derive/src/variant.rs#L96-L137

Readme's Items { vec: Vec<Item> } is intended to show it does not distinguish a newtype variant and single field struct variant, but I need to update the README to explain it. now I updated it e492b55ca96cfca1b2a1e70ae866b29ced106cba