Answer#
If the old program printed entries in a stable order and the port does not, the old program was relying on an ordering guarantee that its language gave and Rust's HashMap does not. Look up what the old container promised, then pick the Rust container that promises the same.
| Container | Order of iteration |
|---|---|
| JavaScript object | Integer-like keys in ascending order first, then the other string keys in the order they were added |
JavaScript Map | Insertion order |
Python dict | Insertion order (a language guarantee since Python 3.7) |
Rust HashMap | Not specified; can change between runs and versions |
Rust BTreeMap | Sorted by key |
Rust Vec<(K, V)> | The order you push |
The same four keys in JavaScript (Node.js v22.19.0) show the object rule and the Map rule:
const o = { b: 1, a: 2, "2": 3, "1": 4 };
console.log(Object.keys(o));
const m = new Map([["b", 1], ["a", 2], ["2", 3], ["1", 4]]);
console.log([...m.keys()]);[ '1', '2', 'b', 'a' ]
[ 'b', 'a', '2', '1' ]In Rust (rustc 1.93.0), the program below ran twice. The HashMap printed a different order in the two runs; BTreeMap and the Vec printed the same both times:
use std::collections::{BTreeMap, HashMap};
fn main() {
let pairs = [("b", 1), ("a", 2), ("2", 3), ("1", 4)];
let h: HashMap<_, _> = pairs.into_iter().collect();
println!("HashMap : {:?}", h.keys().collect::<Vec<_>>());
let b: BTreeMap<_, _> = pairs.into_iter().collect();
println!("BTreeMap : {:?}", b.keys().collect::<Vec<_>>());
let v: Vec<_> = pairs.to_vec();
println!("Vec pairs: {:?}", v.iter().map(|p| p.0).collect::<Vec<_>>());
}(first run)
HashMap : ["2", "b", "1", "a"]
BTreeMap : ["1", "2", "a", "b"]
Vec pairs: ["b", "a", "2", "1"]
(second run)
HashMap : ["1", "2", "b", "a"]
BTreeMap : ["1", "2", "a", "b"]
Vec pairs: ["b", "a", "2", "1"]The HashMap order differs between the runs because the standard HashMap seeds its hash function randomly for each map, as a defence against attacks that craft colliding keys. Your own run will print yet another order, so treat these two as examples of "not stable", not as values to expect.
How to do it#
- Find where the old code iterates over a map to produce output (a report, JSON, a log, a test expectation).
- If the old order was insertion order and it matters, port the container as a
Vec<(K, V)>(small maps) or use an insertion-ordered map crate such asindexmap; that crate was not run for this thread. - If sorted order is acceptable or required, use
BTreeMap, or collect the keys into aVecandsort()before printing. - If order never mattered and only tests broke, fix the tests so that they sort or compare as sets.
- Check the golden files from the old program (see the thread on golden files): a test that compares text including map order will fail on every other run if you leave
HashMapin.
Common mistakes#
- Taking the order of the first run as the truth and writing it into a test.
- Switching to
BTreeMapfor order when the old order was insertion order: sorted order is different from insertion order. - Forgetting that JavaScript objects reorder integer-like keys: a port that reads JSON objects and writes them back may reorder keys even in JavaScript.
Related questions#
Can I make HashMap deterministic?#
You can supply a hasher with a fixed seed, but even then the order is still unspecified. Do not rely on it.
Is BTreeMap slower than HashMap?#
They have different costs for different operations (hashing against comparing and tree walking). This thread did not measure them.
Sources#
std::collections::HashMap: https://doc.rust-lang.org/std/collections/struct.HashMap.htmlstd::collections::BTreeMap: https://doc.rust-lang.org/std/collections/struct.BTreeMap.html