ある条件を満たす要素の数を求めたい場合、filterとcountを組み合わせます。
例: 3の倍数の数を数える
fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let count = numbers.iter()
.filter(|&&x| x % 3 == 0)
.count();
println!("{}", count); //=> 3
}
環境情報
$ rustc -V
rustc 1.76.0 (07dca489a 2024-02-04)