Skip to content

Instantly share code, notes, and snippets.

@cambiata
Created June 27, 2023 08:10
Show Gist options
  • Save cambiata/20bc6a1b782d8c261e1a4ecab965b201 to your computer and use it in GitHub Desktop.
Save cambiata/20bc6a1b782d8c261e1a4ecab965b201 to your computer and use it in GitHub Desktop.
use std::collections::HashMap;
static GLOBAL_COUNTER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
#[derive(Hash, Eq, PartialEq, Debug)]
struct TypeA {
a: usize,
id: usize,
}
impl TypeA {
fn new(a: usize) -> Self {
let id:usize = {
GLOBAL_COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
GLOBAL_COUNTER
.load(std::sync::atomic::Ordering::SeqCst)
.into()
};
Self { id, a }
}
}
#[derive(Hash, Eq, PartialEq, Debug)]
struct TypeB {
b: usize,
}
fn main() {
let mut map: HashMap<&TypeA, &TypeB> = HashMap::new();
let a0 = TypeA::new(1);
let b0 = TypeB { b: 111 };
map.insert(&a0, &b0);
let a1 = TypeA::new(1);
let b1 = TypeB { b: 222 };
map.insert(&a1, &b1);
let b_for_a0 = map.get(&a0);
println!("{:?}", b_for_a0); // gives Some(TypeB { b: 222 }) - not the expected Some(TypeB { b: 111 })...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment