Skip to content

Compiler suggesting unstable or-pattern in for loop #79357

Closed
@ritobanrc

Description

@ritobanrc

When forgetting to include parenthesis around a tuple pattern in a for loop, the compiler gives a suggestion to use an or pattern. I would expect this, a. because it's not what most would expect if you use a comma to separate two values in a pattern, and b. because or patterns in for loops are still an unstable feature.

I tried this code:

    let a = vec![1, 2, 3];
    let b = vec![3, 4, 5];
    
    for foo, bar in a.into_iter().zip(b) {    }

As expected, the compiler gives an unexpected , in pattern error, because I forgot the parenthesis around (foo, bar). However, the compiler also suggests that I add a "vertical bar to match on multiple alternatives".

error: unexpected `,` in pattern
 --> src/main.rs:5:13
  |
5 |     for foo, bar in a.into_iter().zip(b) {
  |             ^
  |
help: try adding parentheses to match on a tuple...
  |
5 |     for (foo, bar) in a.into_iter().zip(b) {
  |         ^^^^^^^^^^^
help: ...or a vertical bar to match on multiple alternatives
  |
5 |     for foo | bar in a.into_iter().zip(b) {
  |         ^^^^^^^^^^

Playground Link

While it does provide the correct answer (adding parenthesis), it also provides the vertical bar option, which is an unstable feature in this RFC.

While the RFC does not explicitly single out for loops as a situation where this is necessary, I believe it does apply here, because in this situation (credit /u/ehuss for the example, which is a situation where the or pattern syntax is being used correctly, I get a or-patterns syntax is experimental error, as expected, and including #![feature(or_patterns)] resolves the error.

Meta

I tested this on stable, beta, and nightly in the rust playground. The output is identical for all 3 of them.

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`C-bugCategory: This is a bug.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions