Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created August 2, 2019 15:18
Show Gist options
  • Save rust-play/ea1127c492a17adeab404700baacf99d to your computer and use it in GitHub Desktop.
Save rust-play/ea1127c492a17adeab404700baacf99d to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use std::collections::hash_map::Entry;
use std::collections::HashMap;
trait EntryExt<'a, K, V>: 'a {
fn or_insert_with2<F: FnOnce(&K) -> V>(self, f: F) -> &'a mut V;
}
impl<'a, K, V> EntryExt<'a, K, V> for Entry<'a, K, V> {
fn or_insert_with2<F: FnOnce(&K) -> V>(self, f: F) -> &'a mut V {
match self {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => {
let v = f(entry.key());
entry.insert(v)
}
}
}
}
fn main() {
let mut map: HashMap<i32, i32> = HashMap::new();
println!("{}", map.entry(10).or_insert_with2(|i| i * i));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment