Skip to main content

closed_enum

Macro closed_enum 

Source
macro_rules! closed_enum {
    (
        #[named]
        $(#[$meta:meta])*
        $vis:vis enum $name:ident {
            $( $(#[$vmeta:meta])* $variant:ident ),+ $(,)?
        }
    ) => { ... };
    (
        $(#[$meta:meta])*
        $vis:vis enum $name:ident {
            $( $(#[$vmeta:meta])* $variant:ident ),+ $(,)?
        }
    ) => { ... };
}
Expand description

Declare a fieldless enum together with pub const ALL: &[Self], every variant in declaration order, generated from the enum’s own variant list.

engenho_substrate_core::closed_enum! {
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub enum Colour { Red, Green }
}
assert_eq!(Colour::ALL, &[Colour::Red, Colour::Green]);

Lead the invocation with #[named] to also generate pub const fn name(self) -> &'static str, each variant’s name taken from its own spelling, so the enum, its list and its identifiers are one list:

engenho_substrate_core::closed_enum! {
    #[named]
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub enum Plugin { NodeReady, TaintToleration }
}
assert_eq!(Plugin::NodeReady.name(), "NodeReady");

#[named] must come first. Written after a derive, it is consumed as an ordinary attribute and rustc rejects it (cannot find attribute 'named'), so a misplaced marker is a compile error rather than an enum that silently has no name.