Simple borrow checker problem

It's probably the very thing that borrow checker prevents but I really would like to do the following:

fn test_mut() {
    let mut vv = vec![
            vec![1, 2, 3],
            vec![4, 5, 6],
    call(&mut vv[0], &vv[1]);

fn call(vec1: &mut Vec<i32>, vec2: &Vec<i32>) {
    for (v1, v2) in vec1.iter_mut().zip(vec2) {
        *v1 += *v2;

So obviously I can't borrow vv mutably if later I use it immutably. What would be the most idiomatic way around it? I can't take ownership of vectors and I would like to avoid cloning.

In this case you can use split_first_mut to create the non-overlapping references you want. You are in luck because the borrows you want are non-overlapping.

Actually, my indexes (0 and 1 here) will come from variables and in fact they can be the same index. So I don't want to manipulate vectors, but only content of one vector (items in vector will f64).
I'm trying to apply this iterator - How to mutate another item in a vector, but not the vector itself, while iterating over the vector? - Stack Overflow as it sounds similar but I can't figure out how.

You can use split_at_mut for a more flexible splitting function.


Thanks. It kinda works, but is a bit ugly. Sometimes second index is lower, sometimes higher. Also, I have to add some logic to prevent index be the same. But still, I prefer this to unsafe.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.