#declarative-macro #match #macro #enums #dispatch #any

no-std match_any

Provides a declarative macro, that matches an expression to any of the patterns and executes the same expression arm for any match

3 releases (stable)

1.0.1 Jan 9, 2021
1.0.0 Nov 8, 2020
0.1.0-dev Nov 8, 2020

#1272 in Rust patterns

Download history 13/week @ 2024-03-11 7/week @ 2024-03-18 21/week @ 2024-03-25 73/week @ 2024-04-01 11/week @ 2024-04-08 10/week @ 2024-04-15 9/week @ 2024-04-22 30/week @ 2024-04-29 10/week @ 2024-05-06 22/week @ 2024-05-13 33/week @ 2024-05-20 16/week @ 2024-05-27 25/week @ 2024-06-03 13/week @ 2024-06-10 12/week @ 2024-06-17 8/week @ 2024-06-24

59 downloads per month
Used in 2 crates (via clashctl-tui)

MIT/Apache

8KB

match_any

Provides a declarative macro, that matches an expression to any of the patterns and executes the same expression arm for any match.

This macro allows you to use the same expression arm for different types by creating the same match arm for each of the patterns separated by |. A standard match statement only allows such patterns for the same type:

let result: Result<i64, i32> = Err(42);
let int: i64 = match result { Ok(i) | Err(i) => i.into() }; // does not compile!
let result: Result<i64, i32> = Err(42);
let int: i64 = match_any!(result, Ok(i) | Err(i) => i.into()); // compiles just fine
assert_eq!(int, 42);

Install

[dependencies]
match_any = "1"

Examples

use match_any::match_any;

enum Id { U8(u8), I16(i16), I32(i32) }
use Id::*;

let id = Id::I16(-2);
let id: i32 = match_any!(id, U8(x) | I16(x) | I32(x) => x.into());
assert_eq!(id, -2);

Enum Dispatch

Similarly to the enum_dispatch crate, this macro can be used to implement "enum dispatch" as an alternative to dynamic dispatch. The major difference between the enum_dispatch crate and this macro is, that enum_dispatch provides a procedural macro, while this is a declarative macro. This allows enum_dispatch to reduce the boilerplate code a lot more than match_any. However IDE support should be a bit better with match_any.

Enum Dispatch Example

use match_any::match_any;

trait IntId {
    fn int_id(&self) -> i32;
}

impl IntId for u64 {
    fn int_id(&self) -> i32 { 64 }
}

impl IntId for u32 {
    fn int_id(&self) -> i32 { 32 }
}

enum IntIdKind { U64(u64), U32(u32) }

impl IntId for IntIdKind {
    fn int_id(&self) -> i32 {
        use IntIdKind::*;
        match_any!(self, U64(i) | U32(i) => i.int_id())
    }
}

let int_id_kind = IntIdKind::U32(0);
assert_eq!(int_id_kind.int_id(), 32); // enum dispatch
let int_id_box: Box<dyn IntId> = Box::new(0_u32);
assert_eq!(int_id_box.int_id(), 32); // dynamic dispatch

License

This project is licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in match_any by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

No runtime deps