Rust 保持插入顺序的 Map

在 Rust 的标准库中,HashMap 默认不保证维持插入顺序。当你向 HashMap 中插入键值对时,它们的存储位置是根据键的哈希值决定的,这意味着数据的物理存储顺序可能与插入顺序不同。

IndexMap 类型在提供哈希表的常规功能同时,能保持元素的插入顺序。

1
2
3
4
5
6
7
8
9
10
use indexmap::IndexMap;

let mut map = IndexMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);

for (key, value) in &map {
println!("{}: {}", key, value);
}

这样,map 中的元素将按照插入顺序 "a", "b", "c" 进行迭代。