1

I have these variables and I want to count how many times c appears in s.

let c = 2;
let s = vec![1, 2, 5, 2, 4, 2, 7];

Folding with a closure that uses an if expression compiles and works fine:

let r1 = s.iter().fold(0, |a, &x| a + if x == c { 1 } else { 0 });

However, if I want to use a match like

let r2 = s.iter().fold(0, |a, &x| a + match x { c => 1, _ => 0 });

the compiler complains with an unreachable pattern error message:

22 |     let r2 = s.iter().fold(0, |a, &x| a + match x { c => 1, _ => 0 });
   |                                                                 ^ this is an unreachable pattern

Is it really impossible to do it this way?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
matthias
  • 2,161
  • 15
  • 22

0 Answers0