I believe this example should compile. How can I get the compiler to accept this bit of code?
struct Cat {
v: Vec<usize>,
}
impl Cat {
fn meow(&mut self) -> Option<&mut usize> {
let at_zero = self.v.get_mut(0);
if at_zero.is_some() {
return at_zero;
}
return self.v.get_mut(1);
}
}
My reasoning is that if we hit the first return, then the second borrow never takes place. And if we get to the second return, the first borrow should have expired by now?
error[E0499]: cannot borrow `self.v` as mutable more than once at a time
--> src/lib.rs:12:16
|
6 | fn meow(&mut self) -> Option<&mut usize> {
| - let's call the lifetime of this reference `'1`
7 | let at_zero = self.v.get_mut(0);
| ------ first mutable borrow occurs here
8 | if at_zero.is_some() {
9 | return at_zero;
| ------- returning this value requires that `self.v` is borrowed for `'1`
...
12 | return self.v.get_mut(1);
| ^^^^^^ second mutable borrow occurs here
This code is based on a larger problem I'm trying to solve. The actual code is something along the lines of...
struct Generator {
v: Vec<Option<usize>>,
i: usize,
}
impl Generator {
fn new() -> Self {
Generator {
v: vec![
Some(0), None, Some(1), Some(2), None, None, None, Some(3), None
],
i: 0,
}
}
fn depleted(&self) -> bool {
self.v.len() == self.i
}
fn next(&mut self) -> Option<&usize> {
let next = self.v.get(self.i);
self.i += 1;
match next {
Some(next) => next.as_ref(),
None => None,
}
}
}
struct Transformer {
generator: Generator,
}
impl Transformer {
fn new() -> Self {
Transformer {
generator: Generator::new(),
}
}
fn next(&mut self) -> Option<&usize> {
while !self.generator.depleted() {
let next = self.generator.next();
if next.is_some() {
return next;
}
}
return None;
}
}