Here is the code (playground here) for a hypothetical socket that would write data back (as defined in a closure) when some data is received.
pub struct Socket {
on_message_received: Box<dyn FnMut(&Vec<u8>, &mut Socket)>,
}
impl Socket {
pub fn new(on_message_received: Box<dyn FnMut(&Vec<u8>, &mut Socket)>) -> Self {
Self {
on_message_received,
}
}
pub fn read(&mut self, fake_data: &Vec<u8>) {
(self.on_message_received)(fake_data, self);
}
pub fn write(&mut self, data: Vec<u8>) {
println!(
"Pretend this requires a mutable reference to self {:?}",
data
);
}
}
fn main() {
let mut socket = Socket::new(Box::new(|data, socket| {
socket.write(data.clone());
}));
socket.read(&vec![1, 2, 3]);
}
The line (self.on_message_received)(fake_data, self);
fails to compile because we cannot borrow
*self as mutable more than once at a time
. I understand this but cannot think of a workaround.
I’ve also tried (other playground) to define the closure in a setter (instead of in the constructor) and make the closure capture a reference to the socket (instead of letting the closure be invoked with a reference to the socket).
But in the end, I always face the same issue where a double borrow of mutable reference occurs. 🤔
2