How get my object into RwLock<HashMap<u32, RefCell<Client>>>


#1

My struct is defined like this :

struct MyStruct {
...
clients: RwLock<HashMap<u32, RefCell<Client>>>,
...
}

I would like to write a function “find_client_by_id(id)” where I could get the client object directly. This is my final goal. For now, here is what I have to do every time that I want to access a client :

let mut clients = self.clients.read().unwrap();
if let Some(client_ref) = clients.get(&client_id)  {
    let client = RefCell::borrow_mut(&client_ref);
    client.call_my_function_on_client_object(); // Here I can call client's functions
}

What I would like, is something like this :

let mut client = self.find_client_by_id(client_id);
if client.is_some() {
    client.unwrap().call_my_function_on_client_object();
}

Is it possible ? All my tries ended up with compilation error. Thanks


#2

What is the signature of call_my_function_on_client_object? What is your intended signature of find_client_by_id?

I suspect you are running into an issue when trying to return a reference to a Client while letting go of the RwLockReadGuard. Since the HashMap is protected by the RwLock, you can’t access the data stored in the map unless you are holding the lock.


#3

It doesn’t matter. But I want my object as mutable.

fn find_client_by_id(&mut self, id: u32) -> Option<&Client> {…}

I found help about how they build what they call a “guard” to keep object alive. Trying with that, but if you have idea, let me know. Thanks


#4

Right, as mentioned, you need to keep guard around in order to hold a reference. This is a little tricky. The namedlock crate does exactly what you want, I think.