0

I am trying to mutate VecDeque inside a struct. I want to receive an event and delete it from VecDeque.

pub struct Timeline {
    pub event_loop: Option<VecDeque<Events>>
}

impl Timeline {
    pub fn get_event(&mut self)-> Option<Events> {
        if let Some(mut sequence) = self.event_loop {
           sequence.pop_front()
        } else {
            None
        }
    }
}

got this error

  --> src/timeline.rs:33:37
   |
33 |         if let Some(mut sequence) = self.event_loop {
   |                     ------------    ^^^^^^^^^^^^^^^ help: consider borrowing here: `&self.event_loop`
   |                     |
   |                     data moved here
   |                     move occurs because `sequence` has type `VecDeque<Events>`, which does not implement the `Copy` trait`

I can fix this error by taking ownership of entire object get_event(&mut self) change to get_event(self), but this is not an option because after getting 1 event from get_event(), the whole object is gone and I am receiving "value used after move"

user3840170
  • 26,597
  • 4
  • 30
  • 62
alpinemomo
  • 13
  • 1
  • Is the compiler message that unclear? It tells you "consider borrowing here" the transfer to a mutable borrow if you want mutable access shouldn't be too hard. – cafce25 Jan 09 '23 at 23:27
  • If you make it like compiler suggests, there will be more errors, it looks like fix but in reality it is not. I thought that it is enough to take object as mutable in argument and it always will be mutable inside this method. – alpinemomo Jan 10 '23 at 13:09

1 Answers1

0

Add &mut and remove the mut:

if let Some(sequence) = &mut self.event_loop {

Or replace the mut with ref mut:

if let Some(ref mut sequence) = self.event_loop {
Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77