我想.unique()在迭代器上定义一个方法,使我能够迭代而不重复.
use std::collections::HashSet;
struct UniqueState<'a> {
seen: HashSet<String>,
underlying: &'a mut Iterator<Item = String>,
}
trait Unique {
fn unique(&mut self) -> UniqueState;
}
impl Unique for Iterator<Item = String> {
fn unique(&mut self) -> UniqueState {
UniqueState {
seen: HashSet::new(),
underlying: self,
}
}
}
impl<'a> Iterator for UniqueState<'a> {
type Item = String;
fn next(&mut self) -> Option<String> {
while let Some(x) = self.underlying.next() {
if !self.seen.contains(&x) {
self.seen.insert(x.clone());
return Some(x);
}
}
None
}
} …Run Code Online (Sandbox Code Playgroud) 我有let my_vec = (0..25).collect::<Vec<_>>(),我想分成my_vec10组的迭代器:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19];
[20, 21, 22, 23, 24, None, None, None, None, None];
Run Code Online (Sandbox Code Playgroud)
在Rust中使用迭代器可以做到这一点吗?
我有一个过滤的迭代器,如下所示:
let filt_it = a_vector.iter().filter(|x| condition_on_x);
Run Code Online (Sandbox Code Playgroud)
有没有办法找出它是否为空?
我需要迭代器保持迭代器以备后用,而且似乎无法克隆过滤的迭代器。