Medium
Calling RwLock::write in a match arm on a read() lookup
This is a single-threaded read-through cache: look the key up under a read lock, and on a miss, compute the value and insert it under a write lock. What happens when the program runs?
main.rs
use std::collections::HashMap;
use std::sync::RwLock;
fn main() {
let cache: RwLock<HashMap<u32, String>> = RwLock::new(HashMap::new());
let key = 7;
let value = match cache.read().unwrap().get(&key) {
Some(v) => v.clone(),
None => {
let v = format!("computed-{}", key);
cache.write().unwrap().insert(key, v.clone());
v
}
};
println!("{}", value);
}48 of 53 in Rust