How to have a HashMap in the State

I have a nested Map structure in my state. I would like to implement the first level of the structure as HashMap, because I am having some lifetime problems when using a nested StateMap. I cannot get an iterator for the second level StateMap because I need to use .deref() to move the second level statemap out of the reference, which causes lifetime errors (cannot return value created in current function).

Therefore I would like to use a HashMap for the first level and a StateMap for the second level. But HashMap does not have the corresponding traits.

Is there an example somewhere how to use a Hashmap<T, Statemap<U,V,S>> in the state?

That would typically be a bad idea since the HashMap does not support incremental updates. Sometimes it can make sense to use a HashMap inside a StateMap, but it depends on the nature of updates of the state.

Can you explain in more detail, perhaps a simplified example,of what your problem is with a nested statemap? I’m fairly confident it can be resolved even with the nested statemap.

Regarding my original problem: please see a minimal example here:

Because I need to deref the contents of the upper level StateMap, I cannot return the iterator and get an error like cannot return value referencing local variable 'collection'

You can run cargo build on the example to see what I mean. I do not see how I can get the iterator here. That is why I want to use a structure like

HashMap<u8, StateMap<u8, Vec<u8>, S>>

instead of

StateMap<u8, StateMap<u8, Vec<u8>, S>, S>

There will be max 10 entries in the HashMap anyway.

Do you want an iterator out, or can you collect?

The only way you could get an iterator out is to make a new struct

struct Return {
   collectIon: StateMap<...>,
   iter: Iterator<...>,

and then implement Iterator for Return. This way you would keep alive the relevant structures for the duration of the iterator. Alternatively don’t return an interator, and collect, although this will be less efficient.

You cannot really nest a statemap inside a hashmap without manually implementing complex traits, which is not something we encourage.

I tried to return a struct but run into the same error. I cannot return an owned version of the collection. Could you have a look at the latest commit in the repo please?