union_type!() { /* proc-macro */ }
Expand description
To make a enum a “union type”
Assume there exists an A type and a B type,
both of them has implemented fn
f
and g
union_type! {
#[derive(Debug, Clone)]
enum C {
A,
B
}
impl C {
fn f(&self) -> i32;
fn g<T: Display>(&self, t: T) -> String;
}
}
Then type C becomes an union type, you can cast from and into C with A and B:
let a = A::new();
let mut c: C = a.into();
let b = c.try_into(); // cause an Err
let a: A = c.try_into().unwrap(); // successful
And will call its child type’s function when:
let a = A::new();
let mut c: C = a.into();
c.f(); // equivalent with call a.f()
let b = B::new();
c = b.into();
c.f(); // equivalent with call b.f()