Why does Iter<'_, K, V> say "It's in an arbitrary order"?

https://doc.rust-lang.org/stable/std/collections/struct.HashMap.html#method.iter
mentions that the Iter visits all KVs in arbitrary order. What does arbitrary mean, why is this order so indeterministic, and/or is this really the case, what is the possible reason for this?

PS: Does this have something to do with random/sequential read? I need clarity over the working of Iter.
Thanks.

It's a HashMap, so the order in which things come out will depend on the hasher, the random state of the hasher (if you're using the default one), and the current capacity of the hashmap.

So while if you iterate the same thing twice without changing it the things will come out in the same order, you should not expect any particular order.

If you need a predictable order, consider something like

6 Likes

It might be deterministic, in fact. The point is that standard library makes no guarantee for this, so you should not rely on this order for your program to be correct. The only thing it guarantees is that every key-value pair will be visited exactly once.

3 Likes

And, if I understand correctly, the order in which you performed the insertion operations (and, possibly, removal or other operations).

2 Likes

The lack of a meaningful iteration order is a property of hashmaps in general, not just in Rust. If you haven't looked into how hashmaps work, doing so might help clarify.

5 Likes

Often, in programming, when people say “arbitrary order” they mean that they can change the order, that you shouldn't rely on the order. You may, or may not, get the same results back every time. If they said “in random order”, then people might expect that the results would be randomized. There are cases where you might want that.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.