rust-lang / rust-lang/rfcs

Allow `_ @ CONST` in match arms

Open
#2,941 5 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Markdown
Stars
6.6k
Forks
1.7k
Avg merge
16h 14m
Merged PRs (30d)
1

Description

The following is currently not valid:

const CONST: u32 = 1;

fn main() {
    let x = 2;
    match x {
	    _ @ CONST => { },
	    _ => { }
    }
}
error: pattern on wrong side of `@`
 --> src/main.rs:6:6
  |
6 |         _ @ CONST => { },
  |         -^^^-----
  |         |   |
  |         |   binding on the right, should be on the left
  |         pattern on the left, should be on the right
  |         help: switch the order: `CONST @ _`

Apparently because the grammar requires an identifier on the lhs of @. Replacing _ by _x makes the code compile.

Writing

    match x {
	    CONST => { },
	    _ => { }
    }

is ambiguous without a complete analysis of the surrounding module. CONST might be a variable name or a constant. The difference impacts which arm is taken.

On the other hand,

    match x {
	    _x @ CONST => { },
	    _ => { }
    }

is unambiguous but introduces the useless variable _x.

Therefore my proposal is as follows:

  • Make
    match x {
	    _ @ CONST => { },
	    _ => { }
    }

valid syntax.

  • Deprecate
    match x {
	    CONST => { },
	    _ => { }
    }

where CONST could either be a constant or a variable name in the next edition.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the match-arm examples in the issue and analyze the pattern grammar and the ambiguity between constants and variable names. A complete proposal should define the accepted _ @ CONST syntax and the next-edition treatment of the ambiguous CONST form, then document the resulting behavior through the RFC process.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.