Skip to content

Print a HashMap in Rust

Use {:?} to print a HashMap for debugging. With a captured variable, write println!("{scores:?}"). Use {:#?} when a multi-line representation is easier to scan.

EXAMPLE: CI-CHECKEDTEST ASSERTED · examples/format-output/src/print_values_pages.rs#debug-print-hashmap
let scores = HashMap::from([("Blue", 10), ("Red", 20)]);
println!("{scores:?}");
println!("{scores:#?}");

RustPrint executes this example in the Rust test suite. The test checks that the formatted map contains the expected keys and values without asserting their order.

HashMap supports Debug when its keys and values do

Section titled “HashMap supports Debug when its keys and values do”

The standard library implements Debug for HashMap<K, V> when both K and V implement Debug. That is why collections such as HashMap<&str, i32> can be inspected directly with {:?}.

If a custom key or value type does not implement Debug, derive or implement Debug for that type first. See E0277: type doesn’t implement Debug for the checked failure case.

A HashMap does not promise a stable iteration order. The standard library uses randomized hashing by default, and Rust documentation explicitly treats map iteration as arbitrary order.

That means these two outputs can represent the same logical map:

{"Blue": 10, "Red": 20}
{"Red": 20, "Blue": 10}

For debugging, that is normally fine. For tests, files, snapshots, generated text, or any output where order matters, do not compare the raw Debug string.

{:#?} asks the Debug implementation for its alternate pretty representation. This usually makes larger maps easier to read by placing entries across multiple indented lines.

Pretty Debug is still inspection output. Rust does not guarantee its exact textual representation as a serialization format or stable interface.

If the order is part of the output contract, choose it explicitly. One option is to collect the entries or keys, sort them, and print them in that order. Another is to use an ordered map type when ordered traversal is part of the data-structure requirement.

If you only need quick inspection, keep it simple and use {:?} or {:#?}. For the broader representation choice, see Debug vs Display.