Skip to content

Instantly share code, notes, and snippets.

@archer884
Last active October 24, 2021 23:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save archer884/db017a388508a82ae511 to your computer and use it in GitHub Desktop.
Save archer884/db017a388508a82ae511 to your computer and use it in GitHub Desktop.
"Extension Methods" in Rust
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use std::collections::hash_state::HashState;
fn main() {
if let Some(content) = {
let args = std::os::args();
if args.len() == 2 {
Some(args[1].to_string())
} else {
None
}
} {
let mut set = HashSet::new();
let mut dup = Vec::new();
for c in content.chars().filter(|&c| c != ' ') {
if !set.add_unique(c) {
dup.add_unique(c.to_string());
}
}
println!("{}", dup.concat());
}
}
trait UniqueCollection<T> {
fn add_unique(&mut self, item: T) -> bool;
}
impl<T, S, H> UniqueCollection<T> for HashSet<T, S>
where T: Eq + Hash<H>,
S: HashState<Hasher=H>,
H: Hasher<Output=u64>
{
fn add_unique(&mut self, item: T) -> bool {
if !self.contains(&item) {
self.insert(item);
true
} else {
false
}
}
}
impl<T> UniqueCollection<T> for Vec<T>
where T: Eq
{
fn add_unique(&mut self, item: T) -> bool {
if !self.iter().any(|i| *i == item) {
self.push(item);
true
} else {
false
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment