← All notes

Rust HashMap: lookup by key

Answer: A HashMap stores values by key rather than by a numeric index. Create an empty map with HashMap::new and add entries with insert. Keys must implement Eq and Hash.

Lookup by key

Look up data by a key that can be of any type, not by an index.

One way to start is HashMap::new, then insert to add elements.

HashMap is not in the prelude, so you first use it from the collections portion of the standard library.

Keys and capacity

Vectors store values by an integer index. HashMaps store values by key instead.

A key may be a boolean, an integer, a string, or another type that implements the Eq and Hash traits.

HashMap::new() gives a default initial capacity, which the example book recommends.

See also

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: The Rust Programming Language, Storing Keys with Associated Values in Hash Maps; Rust by Example, HashMap. MIT OR Apache-2.0 (https://raw.githubusercontent.com/rust-lang/book/main/LICENSE-MIT). Copyright the Rust Project Developers. MIT OR Apache-2.0 (https://raw.githubusercontent.com/rust-lang/rust-by-example/master/LICENSE-MIT). Copyright the Rust Project Developers. Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: The Rust Programming Language, Storing Keys with Associated Values in Hash Maps; Rust by Example, HashMap. MIT OR Apache-2.0 (https://raw.githubusercontent.com/rust-lang/book/main/LICENSE-MIT). Copyright the Rust Project Developers. MIT OR Apache-2.0 (https://raw.githubusercontent.com/rust-lang/rust-by-example/master/LICENSE-MIT). Copyright the Rust Project Developers.

Cite this

Permanent ID: iil:note:pkpskcfb

iinventedlight. 2026. "Rust HashMap: lookup by key." iinventedlight Library, iil:note:pkpskcfb, version of 2026-11-23. https://iinventedlight.com/library/notes/rust-hashmap/. License: CC-BY-4.0.

@misc{iil_note_pkpskcfb,
  author = {{iinventedlight}},
  title = {{Rust HashMap: lookup by key}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-23},
  url = {https://iinventedlight.com/library/notes/rust-hashmap/},
  note = {Permanent ID iil:note:pkpskcfb. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).

Extra files beside this note

These files use this note's license, shown below. Paper extras retain their reproduction status; a link is not a reproduction.

All artifact files (JSON index)

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/rust-hashmap.md.