macro_rules! assert_variant { ($test:expr, $variant:pat_param $( | $others:pat)* => $e:expr, $fmt:expr $(, $args:tt)* $(,)?) => { ... }; ($test:expr, $variant:pat_param $( | $others:pat)* => $e:expr $(,)?) => { ... }; ($test:expr, $variant:pat_param $( | $others:pat)* , $fmt:expr $(, $args:tt)* $(,)?) => { ... }; ($test:expr, $variant:pat_param $( | $others:pat)* $(,)?) => { ... }; }
Expand description
Macro to assert a value matches a variant. This macro is particularly useful when partially matching a variant.
Example:
// Basic matching:
let foo = Foo::B(42);
assert_variant!(foo, Foo::B(_)); // Success
assert_variant!(foo, Foo::A); // Panics: "unexpected variant: B(42)"
// Multiple variants matching:
let foo = Foo::B(42);
assert_variant!(foo, Foo::A | Foo::B(_)); // Success
assert_variant!(foo, Foo::A | Foo::C); // Panics: "unexpected variant: B(42)"
// Advanced matching:
let foo: Result<Option<u8>, u8> = Result::Ok(Some(5));
assert_variant!(foo, Result::Ok(Some(1...5))); // Success
assert_variant!(foo, Result::Ok(Some(1...4))); // Panics: "unexpected variant: Ok(Some(5))"
// Custom message
let foo = Foo::B(42);
// Panics: "expected Foo::A, actual: B(42)"
assert_variant!(foo, Foo::A, "expected Foo::A, actual: {:?}", foo);
// Optional expression:
let foo = Foo::B(...);
assert_variant!(foo, Foo::B(v) => {
assert_eq!(v.id, 5);
...
});
// Unwrapping partially matched variant:
let foo = Foo::B(...);
let bar = assert_variant!(foo, Foo::B(bar) => bar);
let xyz = bar.foo_bar(...);
assert_eq!(xyz, ...);