8
我想在迭代器上定義一個.unique()
方法,使我能夠不重複地進行迭代。如何向Iterator添加新方法?
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
}
}
這個編譯。然而,當我嘗試在同一文件中使用:
fn main() {
let foo = vec!["a", "b", "a", "cc", "cc", "d"];
for s in foo.iter().unique() {
println!("{}", s);
}
}
我得到以下錯誤:
src/main.rs:34:25: 34:33 error: no method named `unique` found for type `core::slice::Iter<'_, &str>` in the current scope
src/main.rs:34 for s in foo.iter().unique() {
^~~~~~~~
note: in expansion of for loop expansion
src/main.rs:34:5: 36:6 note: expansion site
src/main.rs:34:25: 34:33 help: items from traits can only be used if the trait is implemented and in scope; the following trait defines an item `unique`, perhaps you need to implement it:
src/main.rs:34:25: 34:33 help: candidate #1: `Unique`
我在做什麼錯?我將如何擴展這個任意可排序類型?
完美,謝謝!我打算把它放在crates.io上,我希望沒問題。 –
@WilfredHughes這很好,但你可能希望將它貢獻給[itertools crate](http://bluss.github.io/rust-itertools/doc/itertools/index.html),這是一個偉大的存儲庫添加類型。 – Shepmaster
好主意! https://github.com/bluss/rust-itertools/pull/30 –