Rust•HashMaps
Rust HashMap: Key-Value Hash Tables and the Entry API
Learn HashMap in Rust, safe lookup with get(), and inserting default values with entry().or_insert().
Syntax
use std::collections::HashMap;
let mut map = HashMap::new();
map.entry("key").or_insert(10);
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| entry().or_insert() | Entry API | Inserts default value only if key does not exist. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Rust locally:
use std::collections::HashMap;
fn main() {
let mut port_registry = HashMap::new();
port_registry.insert(String::from("HTTP"), 80);
port_registry.insert(String::from("HTTPS"), 443);
port_registry.insert(String::from("SSH"), 22);
// Entry API: Insert default if not present
port_registry.entry(String::from("REDIS")).or_insert(6379);
// Safe lookup with .get() returning Option<&V>
let protocol = "HTTPS";
match port_registry.get(protocol) {
Some(port) => println!("{} is bound to port {}", protocol, port),
None => println!("Protocol not found"),
}
println!("\nAll Ports:");
for (k, v) in &port_registry {
println!(" {} -> {}", k, v);
}
}Expected Output:
HTTPS is bound to port 443 All Ports: HTTP -> 80 HTTPS -> 443 SSH -> 22 REDIS -> 6379
How It Works: Step-by-Step
- Lines 4-8: Initializes HashMap and inserts key-value pairs.
- Line 11: Entry API inserts "REDIS" -> 6379 in a single lookup.
- Lines 15-18: .get() returns Option<&i32>.
Key Concepts
- HashMap requires keys to implement Eq and Hash traits.
- The Entry API provides safe, single-lookup upsert semantics.
Common Mistake: Trying to look up with &String when &str works directly
HashMap<String, V>.get() takes &str directly due to Deref coercion. No need to allocate String::from.
❌ Incorrect
map.get(&String::from("key")) // Unnecessary heap allocation!✅ Correct
map.get("key") // Clean &str lookupRelated Rust Tutorials & Compiler
Rust Vectors (Vec<T>): Dynamic Heap Arrays and Slices
Master dynamic Vec<T> collections using vec! macro, push, pop, and indexing.
Rust Tuples, Enums, and the Option & Result Types
Master algebraic enums, Option<T> (null replacement), and Result<T, E> in Rust.
Rust Strings: String vs &str and UTF-8 Slicing
Master String (growable heap string) vs &str (string slice) in Rust.
Rust Online Compiler
Open in Compilra IDE
Run and test Rust on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.