[][src]Trait enum_vec::EnumValues

pub trait EnumValues: EnumLike {
    fn values() -> Values<Self> { ... }
}

Helper trait to iterate over all the possible values of an enum. Note: you don't need to implement this trait, it is provided by EnumLike.

Common usage: for i in T::values() {}

Example 1

You first need to impl EnumLike to get access to this trait.

use enum_like::{EnumLike, EnumValues};

#[derive(Copy, Clone, Debug)]
enum ABC { A, B, C }

unsafe impl EnumLike for ABC {
    const NUM_VARIANTS: usize = 3;
    fn to_discr(self) -> usize {
        match self {
            ABC::A => 0,
            ABC::B => 1,
            ABC::C => 2,
        }
    }
    fn from_discr(x: usize) -> Self {
        match x {
            0 => ABC::A,
            1 => ABC::B,
            2 => ABC::C,
            _ => unreachable!(),
        }
    }
}

fn main() {
    for i in ABC::values() {
        println!("{:?}", i);
    }
}

Output:

A
B
C

Example 2

The EnumLike trait is implemented by default for bool and Option types, so you can do stuff like:

use enum_like::EnumValues;
type NestedOptionBool = Option<Option<Option<bool>>>;

fn main() {
    for (idx, i) in NestedOptionBool::values().enumerate() {
        println!("{}: {:?}", idx, i);
    }
}

Output:

0: None
1: Some(None)
2: Some(Some(None))
3: Some(Some(Some(false)))
4: Some(Some(Some(true)))

The index can then be used to create an instance of the type using NestedOptionBool::from_discr(x)

Provided Methods

Important traits for Values<T>

Returns an iterator over the values of Self

Implementors

impl<T> EnumValues for T where
    T: EnumLike
[src]

Important traits for Values<T>