Tôi muốn xác định phương thức .unique()
trên trình vòng lặp cho phép tôi lặp lại mà không trùng lặp.Làm cách nào để thêm các phương thức mới vào 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
}
}
Biên dịch này. Tuy nhiên, khi tôi cố gắng để sử dụng trong cùng một tập tin:
fn main() {
let foo = vec!["a", "b", "a", "cc", "cc", "d"];
for s in foo.iter().unique() {
println!("{}", s);
}
}
tôi nhận được lỗi sau:
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`
Tôi đang làm gì sai? Làm thế nào tôi sẽ mở rộng các loại hashable tùy ý này?
Perfect, cảm ơn! Tôi sẽ ném cái này lên crates.io, tôi hy vọng điều đó là ổn. –
@WilfredHughes Tốt thôi, nhưng bạn có thể muốn đóng góp nó vào thùng [itertools crate] (http://bluss.github.io/rust-itertools/doc/itertools/index.html), đây là một kho lưu trữ tuyệt vời cho những các loại bổ sung. – Shepmaster
Ý tưởng tuyệt vời! https://github.com/bluss/rust-itertools/pull/30 –