7

How do I create a static mutable hashmap? I am ok with unsafe code.

The normal static does not allow globals with constructors.

As an example, I want what is at https://gist.github.com/Kimundi/8782487 but HASHMAP to be mutable.

I understand that global shared mutable state is not what very rust-ish but I just want to know if such a thing is possible.

Jack
  • 101
  • 1
  • 4
  • As it's currently written, it’s hard to tell exactly what you're asking. See the [How to Ask page](http://stackoverflow.com/help/how-to-ask) for help clarifying this question. – carlodurso Jan 02 '15 at 19:56
  • You may also want to add some background to your question. It really sounds like you are asking how to have global mutable shared data, which is pretty against-the-grain for Rust. – Shepmaster Jan 02 '15 at 19:59
  • 1
    You might be able to adapt Kimundi's gist be having it implement DerefMut instead of Deref. – wingedsubmariner Jan 03 '15 at 05:32

1 Answers1

11

For maintained answers, see How do I create a global, mutable singleton?, as this question should have been marked as a duplicate.


Seeing as how you already have a solution for a global object that is non-mutable, perhaps you can use one of the cell containers to add interior mutability?

Realistically, this sounds like a a bad idea. Global mutable state is problematic. Why can't you pass in a mutable hashmap to the methods / objects that need it?

You may also what to check out the implementation of stdin, which provides safe access to a true global singleton.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 1
    Thank you. Your link to stdin is exactly what I'm looking for and also a great example of when this is appropriate. – Jack Jan 03 '15 at 01:54