Help with VecDeque of read only references

Hey everyone I'm new to Rust and can't understand how to get this code compiling.

pub fn reallocate_items<'a, T>(items_needed: &usize, vec: &'a mut VecDeque<&'a T>, item: &'a T) {
    if &vec.len() == items_needed {
        vec.pop_back();
    }
    vec.push_front(item);
}

...

let items_vec: Vec<T> = vec![item1.clone(), item2.clone(), item3.clone(), item4.clone()];
let items_needed: usize = 2;
let mut vec_deq_items: VecDeque<&T> = VecDeque::with_capacity(items_needed);

for item in items_vec.iter() {
    reallocate_items(&items_needed, &mut vec_deq_items, item);
}

assert_eq!(vec_deq_items.len(), 2);
assert_eq!(vec_deq_items[0], &item4);
assert_eq!(vec_deq_items[1], &item3);


Got this error:
cannot borrow `vec_deq_items` as mutable more than once at a time `vec_deq_items` was mutably borrowed here in the previous iteration of the loop rustc E0499

Any tips to get it working?

If I extract the code from the function to inside the loop it compiles. Maybe that's the way?

Thank you!

This parameter type forces the lifetime of the mutable borrow of the container (deque) to be the same as the lifetime of the items (&'a T), which is almost always a mistake and leads to this type of error. Instead, leave out the lifetime for the mutable borrow:

which the compiler will treat as equivalent to specifying a separate lifetime for it. Usually, &mut references should not share lifetimes with other references.

1 Like

Wow, I can't believe it that one detail fixed everything.
I was just following the compiler suggestions and got there, but now it's ok!
Thank you!!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.