How to try_fold over (key,value) iterator of hashmap?

Iḿ trying to iterate over the tuple of key,value of a HasMap, but in async mode; Someting liike this:

use tokio::sync::Mutex;
use std::collections::HashMap;

struct A{
    
}

#[tokio::main]
async fn main() {
    let x: Mutex<HashMap<String, A>> = Mutex::new(HashMap::new());
    let mut bind = x.lock().await;
    let i = bind.iter_mut();
    let ii = futures::stream::iter(i);
    ii.try_fold(None, |acc, x| None);
}

First of all, even if itś possible the way I did, it would still leave the mutex blocked the entire time. Is there a way to block just for a moment?

I changed your triple quotes, which were not ascii, to ascii backquotes and added rs after the opening triple quote to get syntax highlighting to work.

The map mustn’t be modified during iteration so the lock must be held, but you can use an RwLock instead to get shared access.

1 Like