Created
July 16, 2019 08:55
-
-
Save irevoire/c821713c95aecf78853006a3e1f85aa4 to your computer and use it in GitHub Desktop.
hashmap with float 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
use std::hash::{Hash, Hasher}; | |
use std::collections::HashMap; | |
#[derive(Debug, Clone)] | |
struct Lala { | |
a: u32, | |
b: f64, | |
} | |
impl PartialEq for Lala { | |
fn eq(&self, other: &Self) -> bool { | |
(self.a == other.a) && (self.b == other.b) | |
} | |
} | |
impl Eq for Lala {} | |
impl Hash for Lala { | |
fn hash<H: Hasher>(&self, state: &mut H) { | |
self.a.hash(state); | |
unsafe { // ici on converti le float64 en unsigned64 comme si on avait | |
// forcé un cast sans modifier son contenu en mémoire | |
std::mem::transmute::<f64, u64>(self.b).hash(state); | |
} | |
} | |
} | |
impl Lala { | |
pub fn new() -> Self { | |
Lala { | |
a: 32, | |
b: 2.2, | |
} | |
} | |
} | |
fn main() { | |
let mut test = HashMap::new(); | |
let el = Lala::new(); | |
test.insert( | |
el.clone(), | |
"caca".to_string(), | |
); | |
let el = test.get(&el).unwrap(); | |
println!("{:?}", el); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment