Elide the enum name on match

The related topic is here Eliding type in matching an enum

So, I don't think completely eliding the type prefix is a good idea since there could be name conflicts etc. However, Rust traditionally use _ to mean a derivable type. So why not just write

    match future.pull(ctx) {
          _::Pending => ...
          _::Ready(v) => ...
    }

To the language user the above can be understood as:

The result to match is an enum and it has certain variants. I want to match them accordingly. Compiler please find the enum type for me, let me know if I am wrong or missed something.

Related: [Pre-RFC] Inferred Enum Type

Reactions were mixed.

1 Like

When I brought this up before, people seemed comfortable with using _::Variant in pattern matching, just not construction. It's not at the top of my list (there are much larger things first), but I hope to write an RFC to this effect.

I frequently use the fact that you can import the variant names at any statement position:

fn poll(self: Pin<&mut Self>, ctx: &mut Context) -> Poll<Self::Output> {
    use Poll::*;
    match future.pull(ctx) {
        Pending => ...
        Ready(v) => ...
    }
}

How about

fn poll(self: Pin<&mut Self>, ctx: &mut Context) -> Poll<Self::Output> {
    match future.pull(ctx) as Poll {
        Pending => ...
        Ready(v) => ...
    }
}

Basically at the match site, I can opt-in to having each element of the match statement only be an enum member. This avoids the namespace-pollution of use Poll::*; style approaches.

(Bikeshed syntax here, maybe match Poll @ future.pull(ctx) or match future.pull(ctx)::Poll or something else; I am not an expert on the grammar and what would work best here; the point is that there's a small extension to match)

3 Likes

What if we could have something like this on Cargo.toml?:

[language-features]
inferred-variants = true

Then allow SomeVariant where SomeEnum is expected. Since this is an optional feature, it'd be backwards-compatible.

// inferred variant
some_fn(PersonalVariant("foo"));
// fully-qualified variant
some_fn(PersonalEnum::PersonalVariant("foo"));

And maybe use the edition year? Based on edition (like beyond 2022), this feature could be true by default, to make life easier.


Just made a pre-RFC: [Pre-RFC] Optional language feature for inferred variants

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.