Skip to content

Instantly share code, notes, and snippets.

@navicore
Last active February 23, 2023 13:30
Show Gist options
  • Save navicore/c3eca2ff58b88d6e5e12ec1e0ffefd13 to your computer and use it in GitHub Desktop.
Save navicore/c3eca2ff58b88d6e5e12ec1e0ffefd13 to your computer and use it in GitHub Desktop.
rust async hashmap map update
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use tokio::runtime::Runtime;
async fn get_from_store(key: String) -> String {
// pretend to get this from an async sqlx db call
String::from(format!("value-for-{key}"))
}
async fn do_work() {
let mut map: HashMap<String, String> = HashMap::new();
async fn run(key: String, mut map: HashMap<String, String>) -> HashMap<String, String> {
let val = match map.entry(key.clone()) {
Entry::Vacant(entry) => {
println!("insert");
let v = get_from_store(key.clone()).await;
entry.insert(v.clone());
v
}
Entry::Occupied(entry) => String::from(entry.get()),
};
println!("processed val {val}");
map
}
map = run(String::from("one"), map).await;
map = run(String::from("two"), map).await;
map = run(String::from("two"), map).await;
map = run(String::from("three"), map).await;
map = run(String::from("one"), map).await;
for (key, value) in &map {
println!("{}: {}", key, value);
}
}
fn main() {
let runtime = Runtime::new().unwrap_or_else(|e| panic!("Haha: {e}"));
let result = do_work();
match runtime.block_on(result) {
_ => {}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment