Hi all,
I'm trying to build an OrderedHashMap
. OrderedHashMap
is really just a hash map that can be iterated in the same order of the insertion. In programming language with garbage collection, it's quite easy to implement, we just need a hash map and a linked list. Everytime we insert an entry, we put it into a hash map and append the linked list. Iterating through all the entries is easy as well, we just need to iterate the linked list.
In rust it's quite challenging. Currently, I can make it work by using Rc
or Arc
to store the key. So, I have something like this:
struct OrderedHashMap<K,V> {
keys: Vec<Rc<K>>,
map: HashMap<Rc<K>, V>,
}
Note: here I'm using Vec
because in my case there is no update or remove. We can only insert values. And inserting an existiing key is noop.
My questions are:
- Is there a better way to do this? Using
Rc<K>
in theHashMap
prevents me to callself.map.get(k)
wherek
is a borrowed version ofK
. So If I haveOrderedHashMap<String,i32>
, I can't callget
with&str
. - Is there existing rust library that can do this?