0

I have the following code:

use std::collections::HashMap;
use std::hash::{Hash, Hasher}; 
#[test]
fn test_hash() {
    trait LetMeHashed: Hash{}
    struct TraitTry{
        val: usize
    }
    impl Hash for TraitTry {
        fn hash<H: Hasher>(&self, state: &mut H) {
            self.val.hash(state);
        }
    }
    impl LetMeHashed for TraitTry{}
    let new = Box::new(TraitTry{val:1}) as Box<dyn LetMeHashed>;
    let mut new_hash = HashMap::new();
    new_hash.insert(new, 1);
    assert!(new_hash.contains(new.clone()))
}

I got the trait LetMeHashed cannot be made into an object error. Can I somehow implement a HashMap or HashSet while using Arc<dyn SomeTrait> as the key?

  • Your code does not produce the error you claim: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=45c703a50c23711caaa920e5cba691f8. Please [edit] your code so it is a proper [MRE]. – Finomnis Dec 25 '22 at 17:58
  • 2
    You can type-erase `Hash`, but [`Eq`] is going to be harder. See [this question](https://stackoverflow.com/questions/25339603/how-to-test-for-equality-between-trait-objects). – Chayim Friedman Dec 25 '22 at 22:24
  • @Finomnis I missed a dependency. https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=db059a1836e38113e43b05899d38d5ea – Metehan Yıldırım Dec 26 '22 at 06:58
  • @MetehanYıldırım Your `assert_eq` doesn't make much sense without a second parameter either, but yes, now it does give your error :) – Finomnis Dec 26 '22 at 09:50
  • The problem, however, is already exactly what @ChayimFriedman says ... HashMap requires `Hash` and `Eq`. How do you intend to `Eq` compare different types of `dyn SomeTrait`? I think that one might be a deal breaker. – Finomnis Dec 26 '22 at 09:51

0 Answers0