Last active
October 24, 2021 23:08
-
-
Save archer884/db017a388508a82ae511 to your computer and use it in GitHub Desktop.
"Extension Methods" in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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