Created
February 20, 2023 03:59
-
-
Save navicore/60f5d2e17f939c9bc7d8d959cc4b6903 to your computer and use it in GitHub Desktop.
rust get entry and async update entry if not found
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; | |
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