2

Consider the following code example:

fn main() {
    let mut arr : Vec<Vec<usize>> = Vec::new();
    for _ in 0..10 {
        arr.push(Vec::new());
    }
    for i in 0..10 {
        arr[i].push(i);
        arr[i].push(i+5);
    }
    for x in arr[0].iter() {
        arr[1].push(*x);
    }
    println!("Test {:?}", arr[1]);
}

Which fails to compile with the following error:

error[E0502]: cannot borrow `arr` as mutable because it is also borrowed as immutable

I gather this is because I performed the immutable borrow of arrby calling iter() and then modifying arr in the same loop (thereby using a mutable borrow). This behavior of the rust compiler makes total sense to me to prevent changing the very thing that is being iterated over during a for loop, however in this specific case I know that adding to arr[1] won't change arr[0]. So how do I tell this rust compiler and compile this program without needing to use clone?

  • 1
    [Here's one way to solve it using slice patterns as in oli_obk's answer to the other question.](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=865604ea100319338a7b0e5eab2c9b0a) – trent May 24 '20 at 01:09

0 Answers0