rust
14 lines · 1 tab
Marcus Chen
Jan 2026
1 tab
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert("Alice", 10);
scores.insert("Bob", 20);
if let Some(score) = scores.get("Alice") {
println!("Alice's score: {}", score);
}
scores.entry("Charlie").or_insert(30);
println!("{:?}", scores);
}
1 file · rust
Explain with highlit
HashMap<K, V> provides O(1) average-case lookups, inserts, and deletes. Keys must implement Hash + Eq. I use it for caches, indexing, and associative data. Common methods: .insert(k, v) adds/updates, .get(&k) returns Option<&V>, .remove(&k) deletes. For iteration, .iter() yields (&K, &V) pairs. The .entry() API is powerful for conditional insert/update: .or_insert() inserts if missing. HashMap uses a randomized hasher by default to prevent DoS attacks. For ordered iteration, use BTreeMap. For small maps (< 10 entries), a Vec<(K, V)> can be faster due to cache locality. HashMap is versatile and efficient for most use cases.
Related snips
rust
struct Config<'a> {
name: &'a str,
value: &'a str,
}
fn parse_config(line: &str) -> Config {
Lifetime annotations for flexible borrowing in structs
rust
lifetimes
borrowing
by Marcus Chen
1 tab
rust
use crossbeam::channel::unbounded;
use std::thread;
fn main() {
let (tx, rx) = unbounded();
Crossbeam for advanced concurrent data structures
rust
concurrency
lock-free
by Marcus Chen
1 tab
rust
use tracing::{info, instrument};
#[instrument]
fn process_request(user_id: u64) {
info!(user_id, "Processing request");
// Work happens here
tracing for structured logging and distributed tracing
rust
observability
tracing
by Marcus Chen
1 tab
rust
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
Channels (mpsc) for message passing between threads
rust
concurrency
channels
by Marcus Chen
1 tab
rust
use clap::Parser;
#[derive(Parser, Debug)]
#[command(author, version, about)]
struct Args {
#[arg(short, long)]
clap for CLI argument parsing with derive macros
rust
cli
clap
by Marcus Chen
1 tab
rust
macro_rules! create_function {
($func_name:ident) => {
fn $func_name() {
println!("Called {}", stringify!($func_name));
}
};
Declarative macros (macro_rules!) for code generation
rust
macros
metaprogramming
by Marcus Chen
1 tab
Share this code
Here's the card — post it anywhere.