I need some help figuring out the Rust borrow checker. The following is a minimal example of the problem I’m facing:
struct VecMutRef<'a> {
vec: &'a mut Vec<usize>,
}
trait Length {
fn len(&self) -> usize;
}
impl<'a> Length for VecMutRef<'a> {
fn len(&self) -> usize {
self.vec.len()
}
}
fn f<'a>(v: &'a mut Vec<usize>) -> usize
where
VecMutRef<'a>: Length,
{
let first = g(v);
let second = g(v);
first + second
}
fn g<'a>(v: &'a mut Vec<usize>) -> usize
where
VecMutRef<'a>: Length,
{
let vec = VecMutRef { vec: v };
vec.len()
}
The compiler complains that I cannot borrow *v twice in the function f. I was thinking by the time the first call to the function g is returned, it’s done with the mutable reference to v, so I’m free to mutably borrow *v again. But apparently, that’s not the case. It would be great if someone could explain to me what’s wrong and suggest a possible workaround. I understand that in this particular example, I don’t need a mutable reference to Vec just to get its length. The example is just for an illustrative purpose.