Idiomatic way to count occurrences in a collection of Options
问题 I want to count number of occurrences of a value in a collection of Options. let v = vec![Some(1), Some(1), Some(3), None]; v.iter() .filter(|Some(x)| x == &1) .count(); Doing this gives refutable pattern not covered error which makes sense. I got around this by doing v.iter() .filter(|x| x.is_some() && x.unwrap() == &1) .count() What's the idiomatic way to do this in rust? 回答1: You can use flatten to get rid of None and unwrap the Some(...) values. Code: let one_count = v.iter().flatten()