Created
February 19, 2019 21:02
-
-
Save rust-play/337df67f6e28d7e7352c652b33a70666 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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::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