type_enum

Macro type_enum 

Source
type_enum!() { /* proc-macro */ }
Expand description

Function-like macro for converting enums to traits with struct variants. It supports optional type indexing per variant and method definitions with pattern/body arms and existential return types.

ยงExample

Lift an enum definition into a trait with struct variants.

โ“˜
type_enum! {
    pub enum Either<A, E> {
        Right(A),
        Left(E),
    }
}

Or with indexed types. It is a feature similar to GADTs in other languages, where each variant can refine the overall type with specific type arguments.

โ“˜
type_enum! {
   enum Expr<T> {
      LitInt(i32) : Expr<i32>,
      LitBool(bool) : Expr<bool>,
      Add(Box<Expr<i32>>, Box<Expr<i32>>) : Expr<i32>,
      Or(Box<Expr<bool>>, Box<Expr<bool>>) : Expr<bool>,
   }
}

Or with functions using existential return types

โ“˜
type_enum! {
   enum Expr<T> { ... }

   fn eval(&self) -> T {
      LitInt(i) => *i,
      LitBool(b) => *b,
      Add(lhs, rhs) => lhs.eval() + rhs.eval(),
      Or(lhs, rhs) => lhs.eval() || rhs.eval(),
   }
}