HashMaps in Rust

Contents
HashMap::new
Entry API
Iterate
Word counter

HashMap::new

A HashMap stores key value pairs with fast lookup by key. Import it from the collections module, then insert owned keys with their scores, counts, or settings.

Key and value types come from use, so an explicit annotation is rarely needed for small maps.

use std::collections::HashMap; fn main() { let mut scores = HashMap::new(); scores.insert(String::from("blue"), 10); }

The map starts empty and gains one team score. Later inserts with the same key replace the old value in place.

Entry API

The entry API updates a key whether or not it exists yet. It looks up the slot once, inserts a default on absence, and hands back a mutable view of the value.

This removes the classic check then insert dance and keeps counters and caches short.

use std::collections::HashMap; fn main() { let mut m = HashMap::new(); m.entry(String::from("a")).or_insert(0); }

The key a appears with 0 on first touch. Repeating the line leaves the stored value unchanged since the slot already exists.

Iterate

Loops over a map yield one key value pair per step. Borrow the map to keep ownership, and each pair arrives as references to the stored key and value.

Order is not promised, so sort keys first when output must look stable across runs.

use std::collections::HashMap; fn main() { let mut m = HashMap::new(); m.insert(String::from("a"), 1); for (k, v) in &m { println!("pair"); } }

The loop borrows m and visits each pair once. The map stays fully usable after the loop because nothing moved out.

Word counter

Counters combine splitting and the entry API. Split text into words, look up each word slot, and bump the stored number through the mutable view.

The whole histogram fits in a few lines with no manual branch for first sightings.

use std::collections::HashMap; fn main() { let mut count = HashMap::new(); for w in "a b a".split_whitespace() { *count.entry(w).or_insert(0) += 1; } }

The sample text yields two for a and one for b. Each new word starts at 0 and the star writes the bumped total back.

Next: Modules

Article author: Arthur Isaev

Related articles
Rust
Rust course: zero to hero in 50 lessons
What is Rust and where it runs
Install Rust
cargo new
Your first program
Variables
Numbers
Strings
Booleans
Tuples
Arrays
Vectors
Slices
if and else
match
Loops
Ownership
Borrowing
Lifetimes
Functions
Structs
Enums in Rust
Advanced match in Rust
Option combinators in Rust
Result and the question mark in Rust
Advanced strings in Rust
Vec methods in Rust
HashMaps in Rust
Modules in Rust
Crates and workspaces in Rust
Testing in Rust
Error handling
Traits
Generics
Trait bounds
Closures
Iterators
Smart pointers
Threads
Mutex and Arc
Files
CLI arguments
Environment variables
Diagnostics
Time
Parsing strings
TCP networking
Capstone: wordfreq CLI
Capstone: tiny HTTP server
Modern Rust tour
Hero roadmap: the whole course on one page
Install Rust on Windows 11
Install Rust on Ubuntu
Install Rust on Rocky Linux
Install Rust on macOS
Install Rust on FreeBSD
Rust in Docker

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: