Crate delegate_match

Crate delegate_match 

Source
Expand description

§delegate-match

Crates.io Docs.rs Rust Version Build

Convenience macro for writing grouped match arms for different underlying types.

Writing repetitive match arms for enumerations (or other pattern-matching constructs) — especially when types, but not the API, differ — can quickly become boilerplate. delegate_match! lets you list several patterns up-front once and then re-uses a single body for each of them, automatically expanding into equivalent ordinary Rust code.

§Examples

§Delegating to the same code for multiple enum variants

use delegate_match::delegate_match;

enum MouseEvent { Scroll(i16, i16), Position(i32, i32) }
let ev = MouseEvent::Scroll(10, 20);

delegate_match! {
    match ev {
        // This expands to two individual arms.
        MouseEvent::{ Scroll, Position }(x, y) => {
            println!("mouse event: $entry_pat -> ({x}, {y})")
        }
    }
}

§Using placeholders

use delegate_match::delegate_match;

enum Msg { Ping, Log }
let msg = Msg::Log;

delegate_match! {
    match msg {
        // Outputs "🏓 Ping" or "📝 Log" depending on the variant.
        Msg::{ Ping: "🏓", Log: "📝" } => {
            // `$assoc_ts` and `$entry_pat` are placeholders substituted at compile time.
            // They are substituted for every entry *before the code is type-checked*,
            // and they may appear in the following places:
            //   - inside the delegate arm pattern (if present),
            //   - inside the match arm guard expression (if present),
            //   - inside the arm body expression.
            println!("{} {}", $assoc_ts, stringify!($entry_pat))
        }
    }
}

§Examples in tests/

See tests/ for more usage examples. These are verified by the CI to compile and execute successfully.

§License

Licensed under either of

at your option.

See COPYRIGHT for more details.

Macros§

delegate_match
Convenience macro for writing grouped match arms for different underlying types.