Crates.io | tyenum |
lib.rs | tyenum |
version | 0.5.0 |
source | src |
created_at | 2019-04-13 18:56:22.666734 |
updated_at | 2019-04-19 13:48:34.474158 |
description | Attribute macro for type enums. |
homepage | |
repository | https://gitlab.com/XBagon/tyenum |
max_upload_size | |
id | 127711 |
size | 5,690 |
Attribute macro for less verbose creation of enums having different types as variants.
Also automatically implements From
, TryFrom
and fn is<T>() -> bool
to check if its inner item is of type T
and is able to give you trait objects depending on which arguments you specify.
use tyenum::tyenum;
struct A;
struct B;
struct C;
#[tyenum]
enum Test {
A,
BB(B),
C(C),
}
results in:
enum Test {
A(A),
BB(B),
C(C),
}
and allows for:
assert_eq!(Test::A(A), A.into());
assert!(Test::A(A).is::<A>());
assert_eq!(Test::A(A).try_into(), Ok(A));
tyenum
also takes 2 optional arguments:
#[tyenum(derive=[Display])]
enum Test {
A,
BB(B),
}
trait Name {
fn name(&self) -> String;
}
impl Name for A {
fn name(&self) -> String {
String::from("A")
}
}
impl Name for B {
fn name(&self) -> String {
String::from("B")
}
}
This implements std::ops::Deref
and std::ops::DerefMut
to a trait object of the derived trait for the enum, which allows you to easily call trait methods, which will be redirected to the variant:
assert_eq!("A", Test::A(A).name());
Requires nightly and #![feature(specialization)] and pollutes your namespace, a trait named "
#[tyenum(trait_obj=[Name])]
enum Test {
A,
BB(B),
}
trait Name {
fn name(&self) -> String;
}
impl Name for A {
fn name(&self) -> String {
String::from("A")
}
}
allows you to do this:
fn try_print_name(test: Test) {
if let Some(named) = test.trait_obj() {
println!("{}",named.name());
}
}