使用“or_insert_with”对 HashMap 进行 rust 异步更新

nav*_*ore 1 rust rust-tokio

当映射还没有条目时,我尝试使用异步调用从数据库延迟填充 HashMap。

Rust 编译器警告异步闭包不稳定,但我应该尝试async {

我正在尝试遵循该建议,但我在评论中收到expected a FnOnce<()>错误: closure

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();

    let key = String::from("key1");

    // the compiler advised async closures were unstable and...
    // to use an async block, remove the `||`: `async {` (rustc E0658)
    map.entry(key.clone())
        .or_insert_with(async { get_from_store(key) }.await);

    // the above now gives the error:
    //expected a `FnOnce<()>` closure, found `impl Future<Output = String>...xpected an `FnOnce<()>` closure, found `impl Future<Output = String>`

    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) {
        _ => {}
    }
}
Run Code Online (Sandbox Code Playgroud)

可能有原因不通过异步更新 HashMap,但上面的错误给了我希望我只是做错了......

Pet*_*all 5

您将无法.await在该位置使用。这是因为它要求闭包的返回类型是 a Future,但 的签名or_insert_with并不期望这样。

我会做得更简单,保留您已有的功能.awaitasync

use std::collections::hash_map::Entry;

async fn do_work() {
    let mut map: HashMap<String, String> = HashMap::new();
    let key = String::from("key1");

    if let Entry::Vacant(entry) = map.entry(key.clone()) {
        entry.insert(get_from_store(key).await);
    }

    for (key, value) in &map {
        println!("{}: {}", key, value);
    }
}
Run Code Online (Sandbox Code Playgroud)