在方法中使用结构字段会导致不可变的自借?

时间:2020-07-12 19:20:08

标签: rust

我正在尝试实现一个名为EventManager的结构,该结构建立一个通道并侦听该通道上的发送以添加到内部队列中。

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);
    }
}

实施-

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

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

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

但这给了我编译错误-

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

看来self.receiver导致self的借用是不变的。后来我试图在调用self方法时借用queue的可变借用。

我的困惑是为什么在我从中取出一个字段后仍然存在不可变的借用。在到达self.queue时,除了方法本身的可变借用之外,是否应该没有self的借用者?

0 个答案:

没有答案