Let we have the server that processes various messages. The code is
struct Server {
clients: HashMap<u32, ClientData>
}
impl Server {
fn handle(client_id: u32, msg: Message) {
// Check that client exists
let mut client = &mut self.clients.get_mut(&id).unwrap_or_else(||{
panic!("Non-existing client id: {}!", id);
});
match msg {
msg1 => {
client.info = "got msg 1".into();
// -- snip -- (inform other clients about new message)
},
}
}
}
Since there are a lot of message types, I want to extract type processing into a function:
fn handle(&mut self, client_id: u32, msg: Message) {
// Check that client exists
let mut client = &mut self.clients.get_mut(&id).unwrap_or_else(||{
panic!("Non-existing client id: {}!", id);
});
match msg {
msg1 => self.handle_msg1(&mut client)
}
}
fn handle_msg1(&self, client: mut& ClientData) {
client.info = "got msg 1".into();
// -- snip -- (inform other clients about new message)
}
However I got borrow checker error since I make reference to self twice: when refer to client and when call using "self.".
How to make this code works?
As you understand, I do not want to duplicate client check in every handling function. I also do not want to use unwrap() in production code. How can I modify the code above to make this code good?