I am encountering an issue where the compiler says that data is borrowed mutably more than once. I am borrowing the data in a loop, however the borrows are only used locally in the loop, and so the next iteration the borrow should have finished.
The (for me) confusing thing is, that it works for a local variable, but not when the borrow happens through a method defined in a trait, and the variable is passed as a mutable reference to a generic typed parameter that is bounded to that trait.
The following code is a simplified example, but shows the exact same error:
trait GetElem<'a, T> {
type ElemRef: Deref<Target=T>;
fn get_at(&'a mut self, index: usize) -> Self::ElemRef;
}
struct Ref<'a, T>(&'a T);
impl<'a, T> Deref for Ref<'a, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.0
}
}
impl<'a, T: 'a> GetElem<'a, T> for Vec<T> {
type ElemRef = Ref<'a, T>;
fn get_at(&'a mut self, index: usize) -> Self::ElemRef {
Ref(self.get(index).unwrap())
}
}
fn test<'a, C: 'a + GetElem<'a, i32>>(passed_data: &'a mut C) {
let mut local_data = vec![1, 2];
let x = local_data.get_at(0);
let tmp = *x;
let y = local_data.get_at(1);
let _ = tmp + *y;
let x = passed_data.get_at(0);
let tmp = *x;
let y = passed_data.get_at(1);
let _ = tmp + *y;
}
Or see it on the playground
So, in the example, I have both a passed_data
(which is behind a mutable reference to a type implementing the GetElem<i32>
trait) and a local_data
, which is a Vec<i32>
.
For both, I attempt to do the same thing: get a mutable reference to the first element, copy the value to a temporary variable, get a mutable reference to the second value, and then compute the sum of both.
This works for the local_data
, but fails for the passed_data
with the following error:
error[E0499]: cannot borrow `*passed_data` as mutable more than once at a time