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
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 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.