#enums #traits #object #impl #wrapped #manage #deref

no-std trait_enum

Easy enum wrapper that implements all traits that the wrapped objects implement

6 releases (breaking)

0.5.0 Aug 31, 2020
0.4.0 Aug 31, 2020
0.3.0 Mar 15, 2019
0.2.0 Dec 20, 2018
0.1.0 Apr 6, 2018

#1802 in Rust patterns

Download history 669/week @ 2024-10-30 920/week @ 2024-11-06 853/week @ 2024-11-13 1286/week @ 2024-11-20 1000/week @ 2024-11-27 1629/week @ 2024-12-04 1969/week @ 2024-12-11 924/week @ 2024-12-18 590/week @ 2024-12-25 1139/week @ 2025-01-01 904/week @ 2025-01-08 879/week @ 2025-01-15 1087/week @ 2025-01-22 1212/week @ 2025-01-29 1034/week @ 2025-02-05 911/week @ 2025-02-12

4,467 downloads per month
Used in k8s-ares

MIT license

10KB
203 lines

Trait Enum

Build Status

An enum wrapper for types that implement the same trait

The trait_enum macro generates an enum that manages several objects.

These objects are expected to have the same trait impl

After which the enum will have a std::ops::Deref impl which returns a reference to that trait.

#[macro_use]
extern crate trait_enum;

pub trait CommonTrait {
    fn test(&self) -> u32;
}

pub struct InnerOne;
impl CommonTrait for InnerOne {
    fn test(&self) -> u32 {
        1
    }
}

pub struct InnerTwo;
impl CommonTrait for InnerTwo {
    fn test(&self) -> u32 {
        2
    }
}

trait_enum!{
    pub enum Combined: CommonTrait {
        InnerOne,
        InnerTwo,
    }
}

fn main() {
    use std::ops::Deref;

    let combined = Combined::InnerOne(InnerOne);
    let deref: &dyn CommonTrait = combined.deref();
    assert_eq!(deref.test(), 1);

    let combined = Combined::InnerTwo(InnerTwo);
    let deref: &dyn CommonTrait = combined.deref();
    assert_eq!(deref.test(), 2);
}

No runtime deps

Features