Skip to main content

impl_display_enum

Macro impl_display_enum 

Source
macro_rules! impl_display_enum {
    (
        $ty:ty:
        $(
            $variant:ident
            $( ( $($tuple:tt)* ) )?
            $( { $($named:tt)* } )?
            => $output:tt
        ),+
        $(,)?
    ) => { ... };
    (
        @write $fmt:ident
        []
        $text:literal
    ) => { ... };
    (
        @write $fmt:ident
        [ $($fields:tt)* ]
        $format:literal
    ) => { ... };
    (
        @write $fmt:ident
        [ $($fields:tt)* ]
        ( $format:literal $($args:tt)* )
    ) => { ... };
}
Expand description

Implements Display for enums using a static string or format args for each variant.

Unit, tuple, and named-field variants can be mixed. Field patterns use Rust syntax, including renamed fields, _, and ... The patterns must cover every variant.

Data variants accept format strings with captured fields and explicit positional or named arguments. Put the format string and explicit arguments in parentheses. Bare strings on unit variants are written verbatim; braces are not interpreted. Use parentheses to format a unit variant’s output, including captured values.

Outer width, precision, and alignment are not applied to the complete output. Generic parameter declarations and match guards are not supported.

§Examples

use impl_more::impl_display_enum;

enum Foo {
    Bar,
    Qux,
}

impl_display_enum!(Foo: Bar => "bar", Qux => "qux");

assert_eq!(Foo::Bar.to_string(), "bar");
assert_eq!(Foo::Qux.to_string(), "qux");

enum CoordOrMsg {
    Coord(i64, i64),
    Msg(&'static str),
}

impl_display_enum!(CoordOrMsg: Coord(x, y) => "{x}, {y}", Msg(msg) => "message: {msg}");

assert_eq!(CoordOrMsg::Coord(4, 2).to_string(), "4, 2");
assert_eq!(CoordOrMsg::Msg("hi").to_string(), "message: hi");

Mix variant shapes and compute format arguments:

use impl_more::impl_display_enum;

enum Event {
    Idle,
    Items(Vec<u8>),
    Progress { completed: usize, total: usize },
}

impl_display_enum! {
    Event:
    Idle => "idle",
    Items(items) => ("{} items", items.len()),
    Progress { completed: count, .. } => "{count} complete",
}

assert_eq!(Event::Items(vec![1, 2]).to_string(), "2 items");
assert_eq!(Event::Progress { completed: 2, total: 3 }.to_string(), "2 complete");

Explicit format arguments must be inside the parentheses:

ⓘ
enum Event { Items(Vec<u8>) }
impl_more::impl_display_enum!(Event: Items(items) => "{} items", items.len());