Clarify the Syntax of Match Expressions

Now, according to the reference manual, the syntax of match expressions is:

match_expr : "match" no_struct_literal_expr '{' match_arm * '}' ;
match_arm : attribute * match_pat "=>" [ expr "," | '{' block '}' ] ;
match_pat : pat [ '|' pat ] * [ "if" expr ] ? ;
  • Is there any example of match expressions with no match arms?
  • Is '{' block '}' really necessary? Doesn’t expr contain block_expr?
  • According to this syntax, a comma is required after an expression in match_arm but current rustc accepts the last arm with or without a comma. Is this behavior a bug, or the syntax is?

Yes: an empty enum (e.g., enum Foo {}) can be matched with a match with no arms.

It is necessary because blocks in match arms don’t need commas after them (althouth they are allowed). That’s why it’s '{' block '}' instead of '{' block '}' ",".

The fact that rustc can accept the last arm without a comma is intentional. The syntax specification in the reference manual is wrong.

Thank you for your answer!

Oh, I've never thought about that...

OK, I got it. (I doubt that such elision is worth adding a little complexity to the syntax, though.)

OK.

Personally I think that should be removed.

1 Like

In my opinion it's nice that you can consistently put the last comma or not in Rust – the new C++ standard has adopted this for enums too.

This way you can write let short_array = [1,2,3]; but also

let long_array = [
    loremipsumdolorsitamet1,
    loremipsumdolorsitamet2,
    loremipsumdolorsitamet3,
    loremipsumdolorsitamet4,
]

Of course one could make this special for arrays only, but I don't really see why one should special case it.

Oh no, perhaps I mis-understood. I meant:

match foo {
    _ => (),
    _ => {}
    _ => (),
}

Should have to be:

match foo {
    _ => (),
    _ => {},
    _ => (),
}

ie, only expressions would be allowed in the rhs of match arms. I find the exception for blocks a cognitive burden and ugly. :confused:

My doubt in the 3rd post of this topic is the same as yours.

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