0

I am trying to implement a struct called EventManager that establishes a channel and listens to sends on that channel to add to an internal queue.

The EventManager-

pub enum Event {
    Queued(String),
    Immediate(String, String)
}

pub struct EventManager {
    events: Vec<String>,
    receiver: Option<Receiver<Event>>,
}

impl EventManager {
    pub fn new() -> EventManager {
        let ev = EventManager {
            events: Vec::new(),
            receiver: None
        };

        ev
    }

    pub fn open_channel(&mut self) -> Sender<Event> {
        let (tx, rx) = mpsc::channel();
        self.receiver = Some(rx);

        tx
    }

    pub fn listen(&mut self) {
        let r = self.receiver.as_ref().unwrap();

        loop {
            match r.recv() {
                Ok(Event::Queued(event_string)) => { self.queue(event_string); },
                _ => {},
            }
        }
    }

    fn queue(&mut self, event_string: String) {
        self.events.push(event_string);
    }
}

Implementation-

fn main() {
    let mut ev = EventManager::new();
    let publisher = ev.open_channel();

    thread::spawn(move || {
        ev.listen();
    });

    publisher.send(Event::Queued(String::from("Hello")));
}

But this is giving me the compile error-

error[E0502]: cannot borrow `*self` as mutable because it is also borrowed as immutable
  --> src\event_manager.rs:34:54
   |
30 |         let r = self.receiver.as_ref().unwrap();
   |                 ------------- immutable borrow occurs here
...
33 |             match r.recv() {
   |                   - immutable borrow later used here
34 |                 Ok(Event::Queued(event_string)) => { self.queue(event_string); },
   |                                                      ^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here

It appears that self.receiver is causing an immutable borrow of self. And later I am trying to make a mutable borrow of self when calling the queue method.

My confusion is why the immutable borrow still exists after I've pulled a field off of it. By the time it gets to self.queue, shouldn't there be no borrowers of self besides the mutable borrow of the method itself?

micah
  • 7,596
  • 10
  • 49
  • 90
  • Does this answer your question? [cannot borrow \`self.x\` as immutable because \`\*self\` is also borrowed as mutable](https://stackoverflow.com/questions/31093841/cannot-borrow-self-x-as-immutable-because-self-is-also-borrowed-as-mutable) – harmic Jul 13 '20 at 04:23
  • Key sentence of dupe's answer: `fn queue(&mut self, event_string: String)` -> This function indicates that **all** of self will be borrowed mutably – harmic Jul 13 '20 at 04:25

0 Answers0