Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I reverse an iterator twice to get the last two numbers of a vector?

I want to take the last two numbers of a vector. Why can't I reverse the iterator twice?

fn main() {
    let double_reversed = &vec![1, 2, 3, 4, 5, 6, 7, 8, 9]
        .into_iter()
        .rev()
        .take(2)
        .rev()
        .collect();

    println!("{}", double_reversed); // expected 8, 9
}

playground

The error messages are:

error[E0277]: the trait bound `std::iter::Take<std::iter::Rev<std::vec::IntoIter<{integer}>>>: std::iter::DoubleEndedIterator` is not satisfied
 --> src/main.rs:6:10
  |
6 |         .rev()
  |          ^^^ the trait `std::iter::DoubleEndedIterator` is not implemented for `std::iter::Take<std::iter::Rev<std::vec::IntoIter<{integer}>>>`

error[E0599]: no method named `collect` found for type `std::iter::Rev<std::iter::Take<std::iter::Rev<std::vec::IntoIter<{integer}>>>>` in the current scope
 --> src/main.rs:7:10
  |
7 |         .collect();
  |          ^^^^^^^
  |
  = note: the method `collect` exists but the following trait bounds were not satisfied:
          `std::iter::Rev<std::iter::Take<std::iter::Rev<std::vec::IntoIter<{integer}>>>> : std::iter::Iterator`
          `&mut std::iter::Rev<std::iter::Take<std::iter::Rev<std::vec::IntoIter<{integer}>>>> : std::iter::Iterator`
like image 335
Tom Avatar asked Mar 04 '23 21:03

Tom


1 Answers

As the compiler tells you (cleaned up):

the trait bound Take<...>: DoubleEndedIterator is not satisfied

Iterator::Rev is only implemented when the underlying type implements DoubleEndedIterator:

fn rev(self) -> Rev<Self>
where
    Self: DoubleEndedIterator, 

Take does not implement DoubleEndedIterator, so you cannot call rev on it.


I'd just slice it:

let items = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let last_2 = &items[items.len() - 2..];
assert_eq!(last_2, [8, 9]);
like image 179
Shepmaster Avatar answered Apr 13 '23 00:04

Shepmaster