Does this error message mean I can use pattern matching in for loops?

  • A+

I do not expect the following code to work, but as part of grammar exploration, I tried in playground:

fn main() {     struct EOF {};     let lines = vec![Ok("line 1"), Ok("line 2"), Err(EOF {})];     for Ok(line) in lines {         println!("{}", line);     } } 

The error message is

error[E0005]: refutable pattern in `for` loop binding: `Err(_)` not covered  --> src/   | 4 |     for Ok(line) in lines {   |         ^^^^^^^^ pattern `Err(_)` not covered 

According to the message above it looks like I only need to add a match arm for the Err case. But what is the right grammar to do so?


Yes, you can use patterns in many places, but not all of them allow you to conditionally branch when there are multiple possible patterns.

A for loop is one place where you cannot add conditions. That's what the error is telling you with "refutable pattern": there's a pattern that will not be handled. Instead, you mostly use the pattern to perform destructuring of the loop variable:

struct Thing {     foo: u8, }  fn main() {     let things = vec![Thing { foo: 1 }, Thing { foo: 2 }, Thing { foo: 3 }];     for Thing { foo } in things {         println!("{}", foo);     } } 


  • match
  • if let
  • while let


  • for
  • let
  • function parameters


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: