我想取向量的最后两个数字。为什么不能两次反转迭代器?
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
}
错误消息是:
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`
答案 0 :(得分:6)
编译器告诉您(清理):
约束
Take<...>: DoubleEndedIterator
的特征不满足
Iterator::Rev
仅在基础类型实现DoubleEndedIterator
时实现:
fn rev(self) -> Rev<Self>
where
Self: DoubleEndedIterator,
Take
未实现DoubleEndedIterator
,因此无法在其上调用rev
。
我要切成薄片:
let items = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let last_2 = &items[items.len() - 2..];
assert_eq!(last_2, [8, 9]);