Is there any way to look up in HashSet by only the value the type is hashed on?

落花浮王杯 提交于 2019-12-06 03:19:31

When you check out the signature for HashSet::get, you'll note that it's slightly more complicated than you might expect:

fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T> 
where
    T: Borrow<Q>,
    Q: Hash + Eq, 

This is done precisely to solve your problem. get accepts a reference to any type (&Q) that can be borrowed from the type in the set (T: Borrow<Q>). T should be read as "my type" and Q should be read as "the query type".

Thus, you need to implement Borrow for your type:

use std::borrow::Borrow;
use std::collections::HashSet;
use std::hash::{Hash, Hasher};

type Id = u32;

#[derive(Debug, Eq)]
struct Foo {
    id: Id,
    other_data: u32,
}

impl PartialEq for Foo {
    fn eq(&self, other: &Foo) -> bool {
        self.id == other.id
    }
}

impl Hash for Foo {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.id.hash(state);
    }
}

impl Borrow<Id> for Foo {
    fn borrow(&self) -> &Id {
        &self.id
    }
}

fn main() {
    let mut baz = HashSet::new();
    baz.insert(Foo {
        id: 1,
        other_data: 2,
    });

    let other_data = baz.get(&1).unwrap().other_data;
    println!("other_data: {}", other_data);
}

See also:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!