Ho due mie classi A e B e voglio usare una HashMap. Ho un codice come questo:Come implementare Eq e Hash per le mie proprie strutture per usarli in HashMap?
use std::collections::HashMap;
pub struct A
{
x: i32,
y: i32,
title: String,
b_obj: B,
}
pub struct B
{
a: u32,
b: u32,
a_obj: A,
}
fn main()
{
let map = HashMap::new();
map.insert(A{x: 10, y: 20, title: "test".to_string()}, B{a: 1, b: 2});
}
Ma il compilatore mi da questi errori:
error: the trait
core::cmp::Eq
is not implemented for the typeA
[E0277]
error: the traitcore::hash::Hash
is not implemented for the typeA
[E0277]
So che devo implementare queste caratteristiche, ma dopo ore di ricerca internet ho trovato nulla di attuazione loro.
Per favore, dammi un esempio su come farlo.
Modifica: In realtà, il mio codice è più complicato e le mie strutture contengono altre strutture (ho modificato il codice). E il compilatore si lamenta che non ho implementato l'Eq.
Il tratto di hash che ho implementato. Sembra così adesso. La mia applicazione è come questo:
impl Hash for Application {
fn hash<H>(&self, state: &mut H) where H: Hasher {
state.write_u32(self.pid);
state.finish();
}
}
ho fatto un impl per PartialEq anche:
impl PartialEq for Application {
fn eq(&self, other: &Application) -> bool {
self.pid == other.pid
}
}
Ma il compilatore si lamenta Eq:
error: the trait
core::cmp::Eq
is not implemented for the typeapp::Application
Come posso implementare Eq? ?? Perché non c'è implementazione nei documenti?
Le tue strutture sono reciprocamente ricorsive, ognuna contiene un campo dell'altro tipo in base al valore. Questo non può essere compilato così com'è. – barjak
Penso che il tuo impl di 'Hash' dovrebbe semplicemente essere 'self.pid.hash (stato)'. Per me è un errore chiamare "finish". – barjak