| Crates.io | type_enum |
| lib.rs | type_enum |
| version | 0.1.6 |
| created_at | 2023-10-29 19:57:40.391516+00 |
| updated_at | 2024-02-25 02:16:08.755091+00 |
| description | Create tagged unions consisting of different types. |
| homepage | |
| repository | https://github.com/DouglasDwyer/type_enum |
| max_upload_size | |
| id | 1017711 |
| size | 37,204 |
type_enum provides an ergonomic and non-intrusive way to:
This crate requires nightly Rust.
use type_enum::*;
type Good = type_list! { u8, i32, String };
let val = TypeEnum::<Good>::new(-23);
// Enums may be cast to any trait common among all enum variants.
println!("{}", val.cast::<dyn ToString>().to_string());
// Enums may be matched to obtain the original type.
let abs = type_match(val)
.with::<u8>(|x| x as i32)
.with::<i32>(|x| x.abs())
.otherwise(|| 0)
.get();
println!("{abs}");
While Rust's enum types are incredibly powerful, they place the burden of extending functionality and implementing new traits on the enum definition. For instance, consider the following code snippet:
pub enum Bad { U8(u8), U16(u16), String(String) }
pub trait NewBehavior {}
impl NewBehavior for u8 {}
impl NewBehavior for u16 {}
impl NewBehavior for String {}
Even though all three constituent types implement NewBehavior, the enum does not. Adding functionality to the enum requires modifying its definition; it does not inherit behavior from its variants. If Bad and NewBehavior were defined in separate crates, implementing NewBehavior on Bad might even be impossible. type_enum reverses this - the traits usable on a TypeEnum are inherited from the variants. This allows for extending code by modifying and maintaining the type variants alone.
serde - Allows for the serialization of TypeEnum instances when all variants are serializable.