Mutable iterator over field in self + mutable call


#1

So i’m trying to iterate over a dictionary in a struct, and at the same time mutably call other methods in the same struct:

while let Some((_address, client)) = self.clients.iter_mut().next() {
        let packets = client.connection.get_packets();

        if packets.len() == 0 { continue; }

        for packet in packets {
            let data_str = str::from_utf8(&packet.data).unwrap_or("");

            match serde_json::from_str::<serde_json::Value>(data_str) {
                Ok(data) => {
                    self.handle_command(client, data);
                },
                Err(_e) => {
                    warn!("[{:?}] Can't decode JSON: {}", packet.address, data_str);
                }
            }
        }
    }

I know what I’m doing is wrong, since I’m trying to borrow self two times mutable. But I cant seem to come up with a correct way to implement this. I tried using Rc on the client in the dictionary and got to somewhere, but It didn’t feel like this was the rust way to do it. Any help will be much appreciated!


#2

Some ideas on handling this type of situation are in Borrowing issue, trying to avoid redundancy. Then a particular case is looked at in Approach to modify a struct using helpers within the struct?.


#3

Thank you for the quick response. This is exactly what I needed.