러스트의 해시맵은 키 타입에 Hash트레잇과 Eq(==연산자 재정의)트레잇을 구현해야 할 것을 명시해.

따라서 키로 써야 하는 타입은 아래처럼 3개를 구현해줘야 함.

use std::hash::{Hash, Hasher};
struct Point{
x:i32,
y:i32
}
impl Hash for Point {
// add code here
fn hash<H: Hasher>(&self, state:&mut H){
self.x.hash(state);
self.y.hash(state);
}
}
impl Eq for Point {}
impl PartialEq for Point{
fn eq(&self, obj:&Self)->bool{
return self.x == obj.x && self.y == obj.y;
}
}


일단 문서에 나온대로 대충 구현해줌.

fn main() {
  let map;
{
let mut new_map = std::collections::HashMap::new();
new_map.insert(Point::new(0,0), 1);
new_map.insert(Point::new(0,1), 2);
new_map.insert(Point::new(1,0), 3);
map = new_map;
}
if let Some(e) = map.get(&Point::new(0,0)){
println!("{}",e);
}
else{
println!("그런 거 없다.");
}
}


해시맵에 키를 찾을 때 필요한 것은 소유권이 아니라 평범한 레퍼런스인 것을 주의해야 해.


해시맵은 가장 단순한 키밸류DB잖아. 유용하게 쓸 수 있겠지.