-1

I want to have a very generic top-level HashMap.

static mut cache: HashMap<std::hash::Hash + Eq, MyBox<_>> = HashMap::new();

MyBox is a smart pointer.

I get all these errors:

the placeholder _ is not allowed within types on item signatures for static variables

only auto traits can be used as additional traits in a trait object
help: consider creating a new trait with all of these as supertraits and using that trait here instead: trait NewTrait: Hash + Eq {}

the trait Eq cannot be made into an object

And also a warning "trait objects without an explicit dyn are deprecated"

How can I create a static mut HashMap that allows any keys and any boxed values?

theonlygusti
  • 11,032
  • 11
  • 64
  • 119

1 Answers1

2

The entire thing seems like a very dubious xy problem, mutable statics are frowned upon to start with. What are you actually trying to achieve here?

How can I create a static mut HashMap that allows any keys and any boxed values?

You can't create a hashmap which allows "any key". As the last error message indicates, Eq is not object-safe, so you can't create a trait object anywhere near Eq, which means you can't create a "dyn any" key which is equatable.

By comparison the placeholder issue can be solved relatively easily, by making the values Box<dyn Any>, though what you'd do with that I can't tell you.

Masklinn
  • 34,759
  • 3
  • 38
  • 57
  • Very possible, I'm still struggling to think as a rustacean should. Thanks for the feedback. I want to make a caching smart pointer, so all `MyBox::new(thing)` return the same value if `thing` has been seen before. – theonlygusti Nov 29 '22 at 14:04
  • I asked a question about the X of this question's XY problem: https://stackoverflow.com/q/74617570/3310334 – theonlygusti Nov 29 '22 at 16:58