Created
June 7, 2021 11:37
-
-
Save harryscholes/56d00c1673cb87f64bfd95d6469d95e4 to your computer and use it in GitHub Desktop.
Rust Set
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::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