I’ve published match-variants, a small procedural macro crate for applying the same expression to heterogeneous enum variants without requiring their payload types to implement a common trait.
The problem I wanted to solve is code like this:
match value {
Value::Foo(x) => x.value(),
Value::Bar(x) => x.value(),
}
where Foo and Bar are unrelated concrete types, but the same expression happens to be valid for both.
With match-variants:
#[derive(MatchVariants)]
enum Value {
Foo(Foo),
Bar(Bar),
}
let result = match_variants!(Value, value, (x), {
x.value()
});
The macro expands to an ordinary Rust match, so every arm is independently type-checked against its concrete payload type.
There is no common trait requirement, trait-object dispatch, runtime type inspection, or allocation introduced by the crate.
It also supports struct-like variants and enums used across modules and external crates.
I originally built this while working with enum-based static dispatch and wanting to avoid introducing traits whose only purpose was to remove repetitive match arms.
Crate: crates.io: Rust Package Registry
This is the first 0.1.0 release, so API/design feedback is very welcome.