I'm trying to create a database that fetches data asynchronously from http when there is no data, and retrieves a reference to that data.
I wrote the following code, but I get an error that I can't take temporary values outside the function.
use std::collections::HashMap;
type Data = std::sync::Arc<tokio::sync::RwLock<HashMap<String, String>>>;
async fn get_data<'a>(data: &'a Data, key: &str) -> &'a str {
let mut data = data.write().await;
if let Some(d) = data.get(key) {
return d;
}
// Actually, get data by http request or something like that
data.insert(key.to_string(), "new_data".to_string());
data.get(key).unwrap()
}
Yes, tokio::RwLock has a read lock and cannot take the value out of scope.
I searched for some useful sites, but I couldn't find a solution.
Does anyone know how to define a function that can retrieve a reference when a key is specified and initialize the data asynchronously as needed?
Sounds like you're looking for some kind of arena instead of HashMap, so that you can insert a new value into it without invalidating existing references. Is that right, or I'm looking in a wrong direction?