profile
viewpoint

Ask questionsAllow `_ @ CONST` in match arms

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.

rust-lang/rfcs

Answer questions scottmcm

I raised the const { CONST } version on IRLO about two months back: https://internals.rust-lang.org/t/bring-enum-variants-in-scope-for-patterns/12104/51?u=scottmcm

There are two interesting replies that suggest the extra noise from requiring the keyword in the pattern would be too annoying for the value.

We're very good at emitting at least one warning in the mistaken cases here; is there maybe a subset that we could upgrade to be deny-by-default because it's so unlikely to be correct?

useful!

Related questions

Unify closure and block hot 1
Naming arguments in Fn traits hot 1
Test timeouts hot 1
Add hashmap, hashset, treemap, and treeset macros hot 1
Arrays should impl the bitwise operations hot 1
Allow omission of unsatisfiable members in trait impls hot 1
Add impl TryFrom<T> for E where E is a C-like #[repr(T)] enum hot 1
Add impl TryFrom<T> for E where E is a C-like #[repr(T)] enum hot 1
Should lossy conversions be compiler warning hot 1
Consider adding Linux targets that don't depend on libc hot 1
Arrays should impl the bitwise operations hot 1
source:https://uonfu.com/
Github User Rank List