poly_enum

Crates.iopoly_enum
lib.rspoly_enum
version0.1.0
created_at2025-06-03 06:52:38.465395+00
updated_at2025-06-03 06:52:38.465395+00
descriptionHierarchical polymorphism with enums
homepage
repositoryhttps://github.com/jesmaz/poly_enum
max_upload_size
id1698693
size9,622
Jesse Mazis (jesmaz)

documentation

README

Hierarchical polymorphism with enums

This crate provides an easy way to create complex polymorphic hierarchies powered by enums.

Examples

use poly_enum::PolyEnum;
#[derive(PolyEnum)]
enum Elements {
    #[poly_enum(NonMetal)]
    Carbon,
    #[poly_enum(Oxidizer, NonMetal)]
    Florine,
    #[poly_enum(Metal)]
    Iron,
    #[poly_enum(Alkali, Metal)]
    Lithium,
    #[poly_enum(Oxidizer, NonMetal)]
    Oxygen,
    #[poly_enum(Alkali, Metal)]
    Sodium,
}

impl Alkali {
    fn explodes_in_water(&self) -> bool {true}
}

let metal = Metal::Sodium;
let alkali: Alkali = metal.cast().unwrap();
assert!(alkali.explodes_in_water());

This will generate 4 enums in addition to the base Elements enum: NonMetal, Oxidizer, Metal, and Alkali.

enum Alkali {
    Sodium,
    Lithium,
}

enum Metal {
    Iron,
    Lithium,
    Sodium,
}

enum NonMetal {
    Carbon,
    Oxygen,
    Florine,
}

enum Oxidizer {
    Oxygen,
    Florine,
}

In addition it will implement PolyEnum to allow casting between these enums.

Limitations

  • No dynamic dispatch other than the match expression
  • Separate hierarchies are not cross compatible
Commit count: 13

cargo fmt