Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::collections::HashMap;
- use std::hash::Hash;
- // you can also change the default hashing algo
- struct KVStore<K, V>(HashMap<K, V>);
- impl<K, V> KVStore<K, V>
- where
- K: Eq + Hash,
- {
- fn new(vals: Vec<(K, V)>) -> Self {
- let mut inner = HashMap::new();
- for (k, v) in vals {
- inner.insert(k, v);
- }
- KVStore(inner)
- }
- fn get(&self, key: &K) -> Option<&V> {
- self.0.get(key)
- }
- fn update<F: Fn(&mut V)>(&mut self, key: &K, f: &F) {
- // just to update or you could use entries api
- if let Some(mut val) = self.0.get_mut(key) {
- f(&mut val)
- }
- }
- }
- fn main() {
- // or make new load key value pairs from some restricted source.
- let mut kv_store = KVStore::new(vec![(1, 1), (2, 2), (3, 3)]);
- kv_store.update(&2, &|v| *v += 1);
- println!("{:?}", kv_store.get(&2));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement