Skip to content

Instantly share code, notes, and snippets.

@harryscholes
Created June 7, 2021 11:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harryscholes/56d00c1673cb87f64bfd95d6469d95e4 to your computer and use it in GitHub Desktop.
Save harryscholes/56d00c1673cb87f64bfd95d6469d95e4 to your computer and use it in GitHub Desktop.
Rust Set
use std::{collections::HashMap, hash::Hash};
#[derive(Debug)]
struct Set<T> {
m: HashMap<T, ()>,
}
impl<T> Set<T>
where
T: Eq + Hash + Copy,
{
fn new() -> Self {
Set { m: HashMap::new() }
}
fn push(&mut self, item: &T) {
self.m.insert(*item, ());
}
fn contains(&self, item: &T) -> bool {
self.m.contains_key(item)
}
fn remove(&mut self, item: &T) -> Option<T> {
match self.m.remove(item) {
Some(_v) => Some(*item),
None => None,
}
}
}
fn main() {
let mut s = Set::new();
for i in 0..10 {
s.push(&i);
}
let item = 5;
println!("{} in set: {}", item, s.contains(&item));
s.remove(&item);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment