How do I modify a container while iterating over i

2019-03-04 05:57发布

I'm referring to the container itself, not the contents of the container. I want to insert, remove, append, etc. I made an abstraction of my problem below:

fn f() {
    let mut numbers = vec![10, 11, 12, 14, 15];

    for index in 0..numbers.len() {
        process(numbers[index]);

        if numbers[index] == 12 {
            numbers.insert(index + 1);
        }
    }
}

Function f would work, but the number of times it loops over the container does not change as the size of the container changes.

fn g() {
    let mut numbers = vec![10, 11, 12, 14, 15];

    for (index, num) in numbers.iter().enumerate() {
        process(num);

        if num == 12 {
            numbers.insert(index + 1);
        }
    }
}

Function g looks like the most idiomatic Rust way to do this, but it does not compile due to an illegal mutable borrow references occurring.

fn h() {
    let mut numbers = vec![10, 11, 12, 14, 15];

    let mut index = 0;
    while index < numbers.len() {
        process(numbers[index]);

        if numbers[index] == 12 {
            numbers.insert(index + 1);
        }

        index += 1;
    }
}

Function h is the only version that works but it does not seem like the right way to do it. I'm basically just simulating a C style for loop with a while loop. I'm hoping someone knows of a more succinct way of writing it, preferably with a for loop instead.

0条回答
登录 后发表回答