Skip to content

Instantly share code, notes, and snippets.

@berkus
Forked from rust-play/playground.rs
Created August 2, 2019 15:24
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 berkus/bb588bd20b92c29df6ec0605ad0cbfd5 to your computer and use it in GitHub Desktop.
Save berkus/bb588bd20b92c29df6ec0605ad0cbfd5 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