pub trait Indexed: Sized + 'static {
    const VARIANTS: &'static [Self];

    // Provided methods
    fn discriminant(&self) -> usize { ... }
    fn from_discriminant_opt(discriminant: usize) -> Option<Self> { ... }
    fn from_discriminant(discriminant: usize) -> Self { ... }
}
Expand description

Allows to get a discriminant from an enum’s variant to an usize, and also get the same variant from said discriminant, for example, having the following implementation:

use indexed_valued_enums::indexed_enum::Indexed;


enum Number{ First, Second, Third }

impl Indexed for Number{
    const VARIANTS: &'static [Self] = &[Number::First, Number::Second, Number::Third];
}

Calling Indexed::discriminant on every enum produces [First->0, Second->1, Third->2].

Calling on Indexed::from_discriminant over the enums would produce [0->First, 1->Second, 2->Third].

Note this documentation it’s solely informational, it is dis-recommended to implement this trait manually, but using the derive macro crate::Valued or the declarative macro crate::create_indexed_valued_enum instead.

Required Associated Constants§

source

const VARIANTS: &'static [Self]

Array storing all the variants of the enum ordered by discriminant.

Provided Methods§

source

fn discriminant(&self) -> usize

Gets the discriminant of this variant, this operation is O(1).

source

fn from_discriminant_opt(discriminant: usize) -> Option<Self>

Gets the variant corresponding to said discriminant, this operation is O(1) as it just gets the discriminant as a read-copy from Indexed::VARIANTS.

This enum doesn’t need to implement the Clone trait as the array is treated as a raw pointer whose value is read without cloning through core::ptr::read.

source

fn from_discriminant(discriminant: usize) -> Self

Gets the variant corresponding to said discriminant, this operation is O(1) as it just gets the discriminant as a copy from Indexed::VARIANTS.

This operation will panic when the discriminant parameter is a number larger than Indexed::VARIANTS’s length.

This enum doesn’t need to implement the Clone trait as the array is treated as a raw pointer whose value is read without cloning through core::ptr::read.

Object Safety§

This trait is not object safe.

Implementors§