None of the standard library collections maintain insertion order. You can instead use IndexMap
from the indexmap
crate, which preserves insertion order as long as you don’t call remove
.
use indexmap::indexmap;
let map = indexmap! {
"Z" => 1,
"T" => 2,
"R" => 3,
"P" => 4,
"K" => 5,
"W" => 6,
};
for (k, v) in map {
println!("{}: {}", k, v);
}
// Z: 1
// T: 2
// R: 3
// P: 4
// K: 5
// W: 6
It accomplishes this by storing a hash table where the iteration order of the key-value pairs is independent of the hash values of the keys. This mean that lookups may be slower than the standard HashMap
, but iteration and removal is very fast.