rust
37 lines · 6 steps
A generic memoizer in Rust
A reusable struct that caches the results of any pure function, keyed by its input.
Explained by
highlit
1use std::collections::HashMap;
2
3pub struct Memoizer<K, V, F> {
4 cache: HashMap<K, V>,
5 compute: F,
6}
7
8impl<K, V, F> Memoizer<K, V, F>
9where
10 K: std::hash::Hash + Eq + Clone,
11 V: Clone,
12 F: Fn(&K) -> V,
13{
14 pub fn new(compute: F) -> Self {
15 Self {
16 cache: HashMap::new(),
17 compute,
18 }
19 }
20
21 pub fn get(&mut self, key: K) -> V {
22 if let Some(value) = self.cache.get(&key) {
23 return value.clone();
24 }
25 let value = (self.compute)(&key);
26 self.cache.insert(key, value.clone());
27 value
28 }
29
30 pub fn len(&self) -> usize {
31 self.cache.len()
32 }
33
34 pub fn invalidate(&mut self, key: &K) -> Option<V> {
35 self.cache.remove(key)
36 }
37}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Storing a closure in a generic field lets one struct memoize any compatible function.
- 2Trait bounds like Hash, Eq, and Clone express exactly what the cache needs from its types.
- 3Checking the cache before computing turns repeated work into a single hash lookup.
Related explainers
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
rust
use axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
rust
use std::net::Ipv4Addr; use std::str::FromStr; #[derive(Debug, Clone, Copy)]
Parsing and matching IPv4 CIDR ranges in Rust
bitwise-operations
parsing
error-handling
Intermediate
8 steps
typescript
type CsvColumn<T> = { header: string; value: (row: T) => string | number | boolean | null | undefined; };
Building a type-safe CSV writer in TypeScript
generics
serialization
escaping
Intermediate
7 steps
rust
use std::sync::OnceLock; static CRC_TABLE: OnceLock<[u32; 256]> = OnceLock::new();
Table-driven CRC32 with lazy init in Rust
checksums
lazy-initialization
lookup-tables
Intermediate
8 steps
rust
use axum::{ body::Body, extract::Path, http::{header, HeaderMap, HeaderValue, StatusCode},
HTTP range requests for video streaming in Axum
http-range-requests
streaming
async-io
Advanced
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-generic-memoizer-in-rust-explained-rust-7c22/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.