Created
December 29, 2024 14:54
-
-
Save Rahix/455d6cdd7063387d7de78cbed34b701d to your computer and use it in GitHub Desktop.
Reference non-trivial keys for 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
#[derive(Hash, Debug, PartialEq, Eq, Clone)] | |
struct KeyOwned { | |
s1: String, | |
s2: String, | |
} | |
#[derive(Hash, Debug, PartialEq, Eq)] | |
struct KeyRef<'a> { | |
s1: &'a str, | |
s2: &'a str, | |
} | |
impl hashbrown::Equivalent<KeyOwned> for KeyRef<'_> { | |
fn equivalent(&self, key: &KeyOwned) -> bool { | |
self.s1 == key.s1 && self.s2 == key.s2 | |
} | |
} | |
fn main() { | |
let mut map: hashbrown::HashMap<KeyOwned, usize> = Default::default(); | |
map.insert( | |
KeyOwned { | |
s1: "Hello".into(), | |
s2: "World".into(), | |
}, | |
42, | |
); | |
map.insert( | |
KeyOwned { | |
s1: "Foo".into(), | |
s2: "Bar".into(), | |
}.into(), | |
23, | |
); | |
dbg!(&map); | |
let r = map.get(&KeyRef { | |
s1: "Hello", | |
s2: "World", | |
}).unwrap(); | |
dbg!(r); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment