Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created July 17, 2018 20:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/5aac63fed8def7ae744c0ea783ab6883 to your computer and use it in GitHub Desktop.
Save rust-play/5aac63fed8def7ae744c0ea783ab6883 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use std::collections::HashMap;
use std::hash::Hash;
pub struct CacheMap<F, T, V>
where F: Fn(&T) -> V, T: Hash + Eq + Copy, V: Copy
{
operation: F,
results: HashMap<T, V>,
}
impl<F, T, V> CacheMap<F, T, V>
where F: Fn(&T) -> V, T: Hash + Eq + Copy, V: Copy
{
pub fn new(f: F) -> CacheMap<F, T, V> {
CacheMap {
operation: f,
results: HashMap::new(),
}
}
pub fn value (&mut self, arg: &T) -> V {
match self.results.get(arg) {
Some(val) => *val,
None => {
let val = (self.operation)(arg);
self.results.insert(*arg, val);
val
}
}
}
}
fn main() {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment