Skip to content

Add IsVariantAnd derive - #561

Open
ChrisJr404 wants to merge 2 commits into
JelteF:masterfrom
ChrisJr404:is-variant-and
Open

Add IsVariantAnd derive#561
ChrisJr404 wants to merge 2 commits into
JelteF:masterfrom
ChrisJr404:is-variant-and

Conversation

@ChrisJr404

Copy link
Copy Markdown

Closes #365.

This adds an IsVariantAnd derive: for each enum variant foo it generates an is_foo_and(&self, f) -> bool method that returns true only when the value is that variant and the given closure returns true for its contents. It's the Option::is_some_and pattern generalised to any enum, which is handy for matching on a variant and checking something about its payload in a single expression instead of a matches! or a match arm.

I modelled the API on the existing IsVariant and Unwrap derives:

  • The method takes &self (like IsVariant), so it's non-consuming and works on borrowed enums.
  • The closure receives the variant's fields by reference as a tuple, in declaration order, the same way Unwrap returns them. A single-field variant collapses to a plain reference, so Just(T) gives is_just_and(|x: &T| ...), exactly mirroring Option::is_some_and.
  • Field-less variants (unit, empty tuple () or empty record {}) take a FnOnce() -> bool closure instead.
  • #[is_variant_and(ignore)] skips a variant, consistent with #[is_variant(ignore)].

It's behind a new is_variant_and feature flag (added to full), with docs in impl/doc/is_variant_and.md, a CHANGELOG entry, and integration tests in tests/is_variant_and.rs covering tuple/struct/unit variants, references, generics with bounds, ignore, a single-variant enum, and the nightly/deprecated cases the IsVariant tests exercise.

One thing worth a look during review: I went with references-in-a-tuple for the closure argument rather than consuming self like Option::is_some_and does, since a consuming derive felt surprising here and IsVariant already established &self. Happy to change the shape if you'd prefer something else.

Stable no longer prints the 'see issue #48214' help line, so the
non_eq_field trybuild snapshot no longer matched.
@ChrisJr404

Copy link
Copy Markdown
Author

The failing stable check was the eq/non_eq_field compile_fail snapshot, not this derive. Newer stable rustc dropped the 'see issue #48214' help line, so I reblessed that .stderr to match. Passes locally now with --features full.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

IsVariantAnd for enums

1 participant