I'm trying to wrap a queue which internally contains two queues, so it behaves like normal_queue
is appended to favored_queue
.
pub struct FzDQueue {
favored_queue: VecDeque<QEntry>,
normal_queue: VecDeque<QEntry>,
}
And for get_mut(i)
, I would like to get reference of the entry firstly from favored_queue
and if failed from normal_queue
.
Option::or_else
seems an exact match
pub fn get_mut(&mut self, pos: usize) -> Option<&mut QEntry> {
let favored_len = self.favored_queue.len();
// let favored_entry = self.favored_queue.get_mut(pos);
// if favored_entry.is_some() {
// return favored_entry;
// } else {
// return self.normal_queue.get_mut(pos - favored_len);
// }
return self.favored_queue.get_mut(pos).or_else(|| self.normal_queue.get_mut(pos - favored_len));
}
However it emits an error:
error[E0373]: closure may outlive the current function, but it borrows
self
, which is owned by the current function
--> src/lib/queue/fzd_queue.rs:49:56
|
49 | return self.favored_queue.get_mut(pos).or_else(|| self.normal_queue.get_mut(pos - favored_len));
| ^^ ----self
is borrowed here
| |
| may outlive borrowed valueself
|
help: to force the closure to take ownership ofself
(and any other referenced variables), use themove
keyword
|
49 | return self.favored_queue.get_mut(pos).or_else(move || self.normal_queue.get_mut(pos - favored_len));
I guess it's something due to FnOnce
or_else takes (Option in std::option - Rust), which should be "static".
OTOH, the code below works fine.
fn pick_next_favored(&mut self) -> Option<QEntry> {
return self.favored_queue.pop_front();
}
fn pick_next_normal(&mut self) -> Option<QEntry> {
return self.normal_queue.pop_front();
}
pub fn pick_next(&mut self) -> Option<QEntry> {
return self.pick_next_favored().or_else(|| self.pick_next_normal());
}
So my questions are:
- Why the second code compiles fine why the first fails?
- Is there any way to use
or_else
in the first case?