API Reference

IndexMap

Hash table that preserves insertion order for Rust, also offering indexed access and stable ordering.

Official Documentation ↗
CompatibilityThis documentation covers version indexmap 2.x / Rust 1.63+. Check the official docs for the latest API surface.

Installation

cargocargo add indexmap

Methods

Overview

IndexMap is a hash map that remembers insertion order. Iteration follows the order keys were added, and entries are also accessible by index, which is useful for deterministic output and serialization.

Core Methods

Insert and look up like a HashMap, use get_index for positional access, and choose shift_remove to keep order or swap_remove for O(1) removal. IndexSet is the set counterpart.

Usage Notes

Use it when output order should be stable, such as config serialization or generated code. Prefer swap_remove when order does not matter to keep removal cheap.

Common Pitfalls

Assuming iteration order equals hash order is wrong; here it is insertion order but may change if using methods that reorder. swap_remove silently changes order, which can surprise serialization.

Errors

The following points are quoted verbatim from the official documentation. 来源:https://docs.rs/indexmap/latest/indexmap/ · 取证方式:HTTP GET 官方 README/文档页(HTML 去标签) · 抓取时间:2026-11-07T13:50:23.818Z. Any error type, throw condition or recovery step not stated there is left unspecified; this page does not infer exception classes or return values.

FAQ

Why not just use a Vec of pairs?
IndexMap keeps key lookup at hash speed while preserving order, so you get ordering and fast access together, unlike a vector that needs linear search by key.
What is the difference between shift_remove and swap_remove?
shift_remove preserves order but costs O(n) shifting, while swap_remove is O(1) but replaces the removed slot with the last entry, changing order.
Is IndexMap hash-order stable?
No. It hashes keys for lookup, but iteration follows insertion order, which is what makes it deterministic and serializable in a stable sequence.