我想在迭代器上使用 take_while
,然后计算结果迭代器中有多少个项目。这是一个简单的玩具程序,演示了我正在尝试做的事情:
fn main() {
let v = vec![1, 2, 3, 4, 5, 4, 3];
let num_before_five = v.iter().take_while(|&&x| x != 5).len();
println!("There are {} items before 5 occurs.", num_before_five);
}
(Rust playground)
当我尝试对此进行编译时,出现以下错误:
error[E0599]: no method named `len` found for type `std::iter::TakeWhile<std::slice::Iter<'_, {integer}>, [closure@src/main.rs:3:47: 3:59]>` in the current scope
--> src/main.rs:3:61
|
3 | let num_before_five = v.iter().take_while(|&&x| x != 5).len();
| ^^^ method not found in `std::iter::TakeWhile<std::slice::Iter<'_, {integer}>, [closure@src/main.rs:3:47: 3:59]>`
该错误表明
std::iter::TakeWhile
没有.len()
方法,这是正确的。尽管任意迭代器可能永远不会终止,但由于它来自Vec
,所以我知道它是有限的。我可以通过在for
循环中进行计数来获得长度,但是似乎必须在Rust中使用一种更惯用的方式来做到这一点。如何获得此
TakeWhile
的长度?
最佳答案
您想要 Iterator::count
:
fn main() {
let v = vec![1, 2, 3, 4, 5, 4, 3];
let num_before_five = v.iter().take_while(|&&x| x != 5).count();
println!("There are {} items before 5 occurs.", num_before_five);
}
请注意,这是
O(n)
。 OTOH, len
仅可用于ExactSizeIterator
,而 TakeWhile
不可使用。
关于rust - 获取TakeWhile的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59874405/