Skip to content

Instantly share code, notes, and snippets.

@peterschwarz
Forked from rust-play/playground.rs
Last active March 2, 2019 20:27
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 peterschwarz/035db7f9fa8af748563bca52e61e5184 to your computer and use it in GitHub Desktop.
Save peterschwarz/035db7f9fa8af748563bca52e61e5184 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use std::cell::{Ref, RefCell};
use std::collections::HashMap;
use std::rc::Rc;
#[derive(Debug)]
struct Key<'b> {
k: Ref<'b, String>,
}
impl<'b> Key<'b> {
fn wrap(k: Ref<'b, String>) -> Self {
Key { k }
}
fn from_ref_cell(ref_cell: &'b Rc<RefCell<String>>) -> Self {
Self::wrap(ref_cell.borrow())
}
}
impl<'b> PartialEq for Key<'b> {
fn eq(&self, other: &Key<'b>) -> bool {
self.k.as_bytes().eq(other.k.as_bytes())
}
}
impl<'b> Eq for Key<'b> {}
impl<'b> std::hash::Hash for Key<'b> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
state.write(self.k.as_bytes())
}
}
fn main() {
let x = Rc::new(RefCell::new("Hello".to_string()));
let y = Rc::new(RefCell::new("Goodbye".to_string()));
let mut m = HashMap::new();
{
m.insert(Key::from_ref_cell(&x), x.clone());
m.insert(Key::from_ref_cell(&y), y.clone());
}
println!("m = {:?}", m);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment