1

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:

  1. Organize code differently e.g. use one struct for immutable data and one for keeping own state and pass everything as parameters to method.

  2. Apply interior mutability and wrap counter in Cell.

  3. Replace for s in self.senders.iter() with for i in 0..self.senders.len() and get a reference to a particular sender inside the loop.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Maxim Schepelin
  • 451
  • 5
  • 9
  • 3
    It looks like your question might be answered by the answers of [Why does refactoring by extracting a method trigger a borrow checker error?](https://stackoverflow.com/q/57017747/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster May 26 '21 at 20:20
  • See also [Efficiently mutate a vector while also iterating over the same vector](https://stackoverflow.com/q/49143770/155423); [Mutating one field while iterating over another immutable field](https://stackoverflow.com/q/35936995/155423); [How can you iterate and change the values in a mutable array in Rust?](https://stackoverflow.com/q/56963011/155423); – Shepmaster May 26 '21 at 20:22
  • [How to change value inside an array while iterating over it in Rust](https://stackoverflow.com/q/48492204/155423); [How to mutate another item in a vector, but not the vector itself, while iterating over the vector?](https://stackoverflow.com/q/35823029/155423) – Shepmaster May 26 '21 at 20:22

0 Answers0