Idiomatic way to count occurrences in a collection of Options

左心房为你撑大大i 提交于 2020-06-14 06:56:12

问题


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().filter(|x| **x == 1).count();

To count None s you can simply use this:

let none_count = v.len() - v.iter().flatten().count();

Playground

Why Flatten works for Options ?

From @E_net4 's comment: Since Option implements IntoIterator it can behave like an empty iterator or iterator with a single element .

  • Empty Iterator for None
  • Iterator with single element for Some(...)


来源:https://stackoverflow.com/questions/55969723/idiomatic-way-to-count-occurrences-in-a-collection-of-options

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!