Manipulating an object from inside a loop that borrows it

后端 未结 3 1426
再見小時候
再見小時候 2020-12-20 11:13

I\'m writing some code in Rust that connects to a remote server, and depending on the messages sent by that server, computes some statistics or executes actions based on the

3条回答
  •  孤城傲影
    2020-12-20 11:41

    In order to allow mutability in an Iterator, you should use iter_mut() and work on mutable references (&mut message). Then, to avoid the additional borrow, you could just perform the addition in the body of the loop:

    for &mut message in self.server.iter_mut() {
        println!("Received {}", message);
        *self.counters.entry(message).or_insert(0) += 1;
    }
    

提交回复
热议问题