获取 TakeWhile 的长度?

jar*_*ll0 0 rust

我想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);
}
Run Code Online (Sandbox Code Playgroud)

(铁锈游乐场)

当我尝试编译它时,出现以下错误:

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]>`
Run Code Online (Sandbox Code Playgroud)

该错误表明 astd::iter::TakeWhile没有.len()方法,这是事实。虽然任意迭代器可能永远不会终止,但由于这个迭代器来自 a Vec,所以我知道它是有限的。我可以通过在循环中计算长度来获得长度for,但似乎在 Rust 中必须有一种更惯用的方法来做到这一点。

我怎样才能得到这个的长度TakeWhile

edw*_*rdw 5

你要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);
}
Run Code Online (Sandbox Code Playgroud)

请注意,这是O(n). OTOH,len仅适用于ExactSizeIterator,但TakeWhile不适用于。