-
-
Save berkus/bb588bd20b92c29df6ec0605ad0cbfd5 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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