delegate-match

Crates.iodelegate-match
lib.rsdelegate-match
version0.2.0
created_at2025-06-29 03:32:55.182335+00
updated_at2025-09-10 16:19:02.002269+00
descriptionProc-macro for delegation of grouped match arms
homepage
repositoryhttps://github.com/chipnertkj/delegate-match
max_upload_size
id1730316
size54,652
Piotr Wyszomirski (chipnertkj)

documentation

https://docs.rs/delegate-match

README

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.

Commit count: 11

cargo fmt