HashMap keys & values iterators order


As said in the the the HashMap::keys and HashMap::values produce iterators in arbitrary order. But is the order the same between the two iterators ?

From what I tested, it looks like it is but I can't get the confirmation from the doc https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=063a3f197fc52a465125468127935ffc


I wouldn't necessarily rely on this because it's not a documented guarantee. However, in the current implementation, Keys and Values are both wrappers around hash_map::Iter, so they will both do whatever Iter does.

I guess I'll use a BTreeMap so, just to be sure it won't break in the future.

Also consider indexmap, a hashmap with deterministic (and fast!) iteration. As a bonus, it's implemented in 100% safe Rust.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.