Hi, I'm not sure if this has been asked. I have been playing with this for a while and can't figure out why:
Here is a simplified example showing what I'm trying to do. Basically, I'm creating a trait that provides iter_mut
on a wrapper type.
trait Foo<'a, T: 'a> {
type Iter: Iterator<Item = &'a mut T>;
fn iter_mut(&'a mut self) -> Self::Iter;
}
struct Bar<T> {
v: Vec<T>,
}
impl<'a, T: 'a> Foo<'a, T> for Bar<T> {
type Iter = std::slice::IterMut<'a, T>;
fn iter_mut(&'a mut self) -> Self::Iter {
self.v.iter_mut()
}
}
fn test<'a, IN: Foo<'a, i32>>(t: &'a mut IN) {
t.iter_mut().for_each(|v| *v += 1);
t.iter_mut().for_each(|v| *v += 2);
}
fn main() {
let mut b = Bar { v: vec![0_i32; 10] };
b.iter_mut().for_each(|v| *v += 1);
b.iter_mut().for_each(|v| *v += 2);
println!("{:?}", b.v)
}
The compiler complains the test
function mutably borrows twice. But the same code in the main
function has no problem. Here is the playground code to show the compile error.
Can anyone kindly provide some clue how I can fix this? Thanks!