Can I iterate in order on `HashMap<usize, MyStruct>`?

Solution 1:

HashMap is an unoredered container, and keeps the items in an arbitrary order. You cannot define an order.

If you want sorted iteration, use BTreeMap. If you need insertion order, you can use the IndexMap type from the indexmap crate.

Solution 2:

Not the best way, but if you really need to do it (using plain HashMap), you can collect the keys and sort them yourself:

let mut keys: Vec<usize> = my_hash_map.keys().collect();
keys.sort_unstable();
for k in &keys {
    ... // do your stuff
}