This non-working piece of code describes my problem:
use std::sync::mpsc::{Sender, channel};
struct Node {
counter: usize,
senders: Vec<Sender<usize>>,
}
impl Node {
fn inc_counter(&mut self) {
self.counter += 1;
}
fn send(&mut self) {
for s in self.senders.iter() {
self.inc_counter(); // <-- If just I put `self.counter += 1` here, the borrow checker is happy
s.send(self.counter);
}
}
}
fn main() {
let (tx, _) = channel();
let mut n = Node{
counter: 0,
senders: vec![tx],
};
n.send();
}
I'm trying to borrow self
mutable when it's already borrowed immutable.
Inlining inc_counter
body works fine for this simple case, but in general case it makes code harder to read and limits refactoring.
It's a pretty common thing to iterate over something and change internal state, isn't it?
There are a few things that I tried:
Organize code differently e.g. use one struct for immutable data and one for keeping own state and pass everything as parameters to method.
Apply interior mutability and wrap
counter
inCell
.Replace
for s in self.senders.iter()
withfor i in 0..self.senders.len()
and get a reference to a particular sender inside the loop.